using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MadRunFabric.Common;
using MadRunFabric.Model.PLCAutomationApi;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;
using PLCAutomationApi.IRepositories;

namespace PLCAutomationApi.Controllers
{
    /// <summary>
    /// 访问接口ip管理
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class PLCIPManageController : BaseController
    {
        private readonly ILogger<PLCIPManageController> _logger;
        private readonly IPLC_IPManageRepository _ipmanageRepository;


        public PLCIPManageController(ILogger<PLCIPManageController> logger, IPLC_IPManageRepository ipmanageRepository)
        {
            _logger = logger;
            _ipmanageRepository = ipmanageRepository;

        }

        public IActionResult Index()
        {
            return View();
        }

        //[Authorize]
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPageAsync    (string ipaddress, string stime, string etime, string macaddress, int pageindex = 1, int pagesize = 10)
        {
            try
            {
                //排序字段
                var sort = Builders<PLC_IPManage>.Sort.Descending("createtime");

                //根据条件查询集合
                var flist = new List<FilterDefinition<PLC_IPManage>>();
                flist.Add(Builders<PLC_IPManage>.Filter.Eq("deleteflag", 0));
                if (!string.IsNullOrWhiteSpace(ipaddress))
                    flist.Add(Builders<PLC_IPManage>.Filter.Where(s => s.ipaddress .Equals(ipaddress)));
                if (!string.IsNullOrWhiteSpace(macaddress))
                    flist.Add(Builders<PLC_IPManage>.Filter.Where(s => s.macaddress .Equals(macaddress)));
                if (!string.IsNullOrWhiteSpace(stime))
                {
                    DateTime dt2 = new DateTime();
                    if (DateTime.TryParse(stime.Trim(), out dt2))
                        flist.Add(Builders<PLC_IPManage>.Filter.Gt("createtime", stime + " 00:00:00"));
                }
                if (!string.IsNullOrWhiteSpace(etime))
                {
                    DateTime dt2 = new DateTime();
                    if (DateTime.TryParse(etime.Trim(), out dt2))
                        flist.Add(Builders<PLC_IPManage>.Filter.Lt("createtime", etime + " 23:59:59"));
                }
                var filter = Builders<PLC_IPManage>.Filter.And(flist);
                var list = await _ipmanageRepository.GetByPage(filter, pageindex, pagesize, sort);
                var count = await _ipmanageRepository.CountAsync(filter);
                var obj = new
                {
                    state = "success",
                    message = "根据条件获取分页数据成功",
                    rows = list,
                    total = count,
                };
                return Content(obj.ToJson());
               
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据条件获取分页数据异常");
                return Error("根据条件获取分页数据异常");
            }
        }

        /// <summary>
        /// 添加信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(string  ipaddress,string macaddress)
        {
            if (string.IsNullOrEmpty(ipaddress))
                return Error("ip地址不能为空");
            if (string.IsNullOrEmpty(macaddress))
                return Error("mac地址不能为空");
            long n = await _ipmanageRepository.Count(x => x.ipaddress == ipaddress && x.macaddress == macaddress&&x.deleteflag ==0);
            if (n > 0)
                return Error("此ip信息已存在");
            var model = new PLC_IPManage();
            model.ipaddress = ipaddress;
            model.macaddress = macaddress;
            model.createtime  = DateTime .Now;
            model.forbidread   = 0;
            model.forbidwrite  = 0;
            model.deleteflag = 0;
            
            bool b = await _ipmanageRepository.Add(model);
            if (b)
                return Success("添加成功");
            return Error("添加失败");
        }

        [HttpPost("delete")]
        public async Task<IActionResult> Remove(string[] ids)
        {
            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var ml = await _ipmanageRepository.GetSingle(item);
                    ml.deleteflag = 1;
                    if (await _ipmanageRepository.Update(ml))
                        res += 1;
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败，请查看后重新操作");
                else
                    return Error("删除失败，请查看后重新操作");
            }
            else
                return Error("请选择要删除的记录");
        }

        [HttpPost("update")]
        public async Task<IActionResult> UpdateData(string id, int? forbidread, int? forbidwrite,int? deleteflag)//(string dataname, string datavalue,string inputdate)
        {
            try
            {
                PLC_IPManage comodel = new PLC_IPManage();

                var list = new List<FilterDefinition<PLC_IPManage>>();
                var filterBuilder = Builders<PLC_IPManage>.Filter;
                list.Add(filterBuilder.Eq("id", id));
                var filter = Builders<PLC_IPManage>.Filter.And(list);
                var count = await _ipmanageRepository.CountAsync(filter);
                if (count > 0)
                {
                    var dModel = await _ipmanageRepository.GetSingle(s => s.id.Equals(id) & s.deleteflag == 0, null);
                    if (forbidread != null)
                    {
                        dModel.forbidread = (int)forbidread;
                    }
                    if (forbidwrite != null)
                    {
                        dModel.forbidwrite = (int)forbidwrite;
                    }
                    if (deleteflag != null)
                    {
                        dModel.deleteflag = (int)deleteflag;
                    }
                    var tt = await _ipmanageRepository.Update(dModel);
                    if (tt)
                        return Success("修改数据成功");
                }
                return Error("修改数据失败");


            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改数据异常");
                return Error("修改数据失败");
            }
        }

        [HttpGet("getsingle")]
        public async Task<IActionResult> GetSingleAsync(string id)
        {
            if (id != null && id.Trim() != "")
            {
                try
                {
                    var dModel = await _ipmanageRepository.GetSingle(id.Trim());

                    if (dModel != null)
                    {
                        return Success("获取参数成功", dModel);
                    }
                    else
                    {
                        return Error("获取参数失败");
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "获取参数实体异常");
                    return Error("获取参数失败");
                }
            }
            else
            {
                return Error("获取参数失败");
            }

        }

        [HttpPost("getauthority")]
        public async Task<IActionResult> GetAuthority(string ipaddress, string macaddress)
        {
            try
            {
                PLC_IPManage comodel = new PLC_IPManage();

                var list = new List<FilterDefinition<PLC_IPManage>>();
                var filterBuilder = Builders<PLC_IPManage>.Filter;
                list.Add(filterBuilder.Eq("ipaddress", ipaddress));
                list.Add(filterBuilder.Eq("macaddress", macaddress));
                var filter = Builders<PLC_IPManage>.Filter.And(list);
                var count = await _ipmanageRepository.CountAsync(filter);
                if (count > 0)
                {
                    var dModel = await _ipmanageRepository.GetSingle(s => s.ipaddress.Equals(ipaddress) & s.macaddress == macaddress & s.deleteflag == 0, null);
                    var forbidread = dModel.forbidread;
                    var forbidwrite = dModel.forbidwrite;
                    //var tt = await _ipmanageRepository.Update(dModel);
                    var obj = new
                    {
                        state = "success",
                        message = "根据条件获取权限成功",
                        forbidread,
                        forbidwrite
                    };
                    return Content(obj.ToJson());
                    
                }
                return Error("获取失败");


            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取权限数据异常");
                return Error("获取权限数据失败");
            }
        }
    }
}