using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
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>
    /// 水电气数据录入
    /// </summary>
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class InputDataController : BaseController
    {
        private readonly ILogger<InputDataController> _logger;
        private readonly IPLC_InputDataRepository _plc_inputdataRepository;
        private readonly IPLC_MonthDataRepository _plc_monthdataRepository;


        public InputDataController(ILogger<InputDataController> logger, IPLC_InputDataRepository plc_inputdataRepository, IPLC_MonthDataRepository plc_monthdataRepository)
        {
            _logger = logger;
            _plc_inputdataRepository = plc_inputdataRepository;
            _plc_monthdataRepository = plc_monthdataRepository;
        }

        [HttpGet("index")]
        public IActionResult Index()
        {
            return View();
        }

        //[Authorize]
        [HttpPost("add")]
        public async Task<IActionResult> AddData(string[] dataname,string[] datavalue,string inputtime,string projectname)
        {
            try
            {
                string ytime = DateTime.Now.AddDays (-1).ToString("yyyy-MM-dd");
                PLC_InputData comodel = new PLC_InputData();
                if (!string.IsNullOrWhiteSpace(inputtime))
                {
                    DateTime dt2 = new DateTime();
                    if (DateTime.TryParse(inputtime.Trim(), out dt2))
                        ytime = dt2.AddDays(-1).ToString("yyyy-MM-dd");

                }
                else
                {
                    inputtime = DateTime.Now.ToString("yyyy-MM-dd");
                }
                int t = dataname.Length;
                int res = 0;
                for (int i = 0; i < dataname.Length; i++)
                {
                    #region 判断是否有当天记录，若有则删除
                    //Dictionary<string, string> dic = new Dictionary<string, string>();
                    //dic.Add("deleteflag", "1");

                    var list = new List<FilterDefinition<PLC_InputData>>();
                    var filterBuilder = Builders<PLC_InputData>.Filter;
                    list.Add(filterBuilder.Eq("dataname", dataname[i]));
                    list.Add(filterBuilder.Eq("inputtime", inputtime));
                    list.Add(filterBuilder.Eq("projectname", projectname));
                    var filter = Builders<PLC_InputData>.Filter.And(list);
                    var count = await _plc_inputdataRepository.CountAsync(filter);
                    if (count > 0)
                    {
                        var dModel = await _plc_inputdataRepository.GetSingle(s => s.dataname .Equals(dataname[i])&s.inputtime == inputtime&s.projectname ==projectname  & s.deleteflag == 0, null);
                        if (dModel != null)
                        {
                            dModel.deleteflag = 1;
                            var tt = await _plc_inputdataRepository.Update(dModel);
                        }
                    }
                    #endregion

                    #region 更新昨天的止数
                    var fModel = await _plc_inputdataRepository.GetSingle(s => s.dataname.Equals(dataname[i]) & s.inputtime == ytime&s.projectname ==projectname  & s.deleteflag == 0, null);
                    if (fModel != null)
                    {
                        fModel.endvalue = datavalue[i];
                        var n = await _plc_inputdataRepository.Update(fModel);
                    }
                    #endregion

                    #region 保存月数据
                    string year = DateTime.Now.Year.ToString();
                    int  mon = Convert.ToDateTime(inputtime.Trim()).Month;// DateTime.Parse(inputtime.Trim());
                    var aModel = await _plc_monthdataRepository.GetSingle(s => s.datayear==year  & s.datamonth  == mon&s.dataname == dataname[i]&s.projectname ==projectname , null);
                    if (aModel != null)
                    {

                        //判断更新止数
                        if (aModel.endday <= Convert.ToDateTime(inputtime.Trim()).Day)
                        {
                            aModel.endday = Convert.ToDateTime(inputtime.Trim()).Day;
                            aModel.endvalue = datavalue[i];
                            aModel.endtime = inputtime.Trim();
                            var n = await _plc_monthdataRepository.Update(aModel);

                            #region 判断如果为每月最后一天则将当前数做为下月起数
                            DateTime dtn = Convert.ToDateTime(inputtime.Trim());
                            DateTime startMonth = dtn.AddDays(1 - dtn.Day);  //本月月初  
                            DateTime endMonth = startMonth.AddMonths(1).AddDays(-1);
                            if (endMonth.Day == dtn.Day)//最后一天
                            {
                                string byear = startMonth.AddMonths(1).Year.ToString();
                                int bmon = startMonth.AddMonths(1).Month;
                                var bModel = await _plc_monthdataRepository.GetSingle(s => s.datayear == byear & s.datamonth == bmon & s.dataname == dataname[i] & s.projectname == projectname, null);
                                if (bModel != null)
                                {
                                    //判断更新止数
                                    if (bModel.endday <= Convert.ToDateTime(startMonth.AddMonths(1)).Day)
                                    {
                                        bModel.endday = Convert.ToDateTime(startMonth.AddMonths(1)).Day;
                                        bModel.endvalue = datavalue[i];
                                        bModel.endtime = startMonth.AddMonths(1).ToString ("yyyy-MM-dd");
                                        var bn = await _plc_monthdataRepository.Update(bModel);

                                        
                                    }
                                    else if (bModel.startday >= Convert.ToDateTime(startMonth.AddMonths(1)).Day)
                                    {
                                        bModel.startday = Convert.ToDateTime(startMonth.AddMonths(1)).Day;
                                        bModel.startvalue = datavalue[i];
                                        bModel.starttime = startMonth.AddMonths(1).ToString("yyyy-MM-dd");
                                        var bn = await _plc_monthdataRepository.Update(bModel);
                                       
                                    }
                                }
                                else
                                {
                                    #region
                                    var amodel = new PLC_MonthData();
                                    amodel.dataname = dataname[i];
                                    amodel.startvalue = datavalue[i];
                                    amodel.endvalue = datavalue[i];
                                    amodel.datamonth = startMonth.AddMonths(1).Month;
                                    amodel.datayear = startMonth.AddMonths(1).Year.ToString();
                                    amodel.startday = startMonth.AddMonths(1).Day;
                                    amodel.endday = startMonth.AddMonths(1).Day;
                                    amodel.starttime = inputtime.Trim();
                                    amodel.endtime = inputtime.Trim();
                                    if (dataname[i].Contains("水"))
                                    { amodel.datakind = 0; }
                                    else if (dataname[i].Contains("天然气") || dataname[i].Contains("燃气"))
                                    { amodel.datakind = 2; }
                                    else if (dataname[i].Contains("氧"))
                                    { amodel.datakind = 3; }
                                    else
                                    { amodel.datakind = 1; }
                                    amodel.projectname = projectname;
                                    await _plc_monthdataRepository.Add(amodel);
                                    #endregion
                                }
                            }
                            #endregion
                        }
                        else if (aModel.startday >= Convert.ToDateTime(inputtime.Trim()).Day)
                        {
                            aModel.startday = Convert.ToDateTime(inputtime.Trim()).Day;
                            aModel.startvalue = datavalue[i];
                            aModel.starttime = inputtime.Trim();
                            var n = await _plc_monthdataRepository.Update(aModel);
                            #region 判断如果为每月最后一天则将当前数做为下月起数
                            DateTime dtn = Convert.ToDateTime(inputtime.Trim());
                            DateTime startMonth = dtn.AddDays(1 - dtn.Day);  //本月月初  
                            DateTime endMonth = startMonth.AddMonths(1).AddDays(-1);
                            if (endMonth.Day == dtn.Day)//最后一天
                            {
                                string byear = startMonth.AddMonths(1).Year.ToString();
                                int bmon = startMonth.AddMonths(1).Month;
                                var bModel = await _plc_monthdataRepository.GetSingle(s => s.datayear == byear & s.datamonth == bmon & s.dataname == dataname[i] & s.projectname == projectname, null);
                                if (bModel != null)
                                {
                                    //判断更新止数
                                    if (bModel.endday <= Convert.ToDateTime(startMonth.AddMonths(1)).Day)
                                    {
                                        bModel.endday = Convert.ToDateTime(startMonth.AddMonths(1)).Day;
                                        bModel.endvalue = datavalue[i];
                                        bModel.endtime = startMonth.AddMonths(1).ToString("yyyy-MM-dd");
                                        var bn = await _plc_monthdataRepository.Update(bModel);


                                    }
                                    else if (bModel.startday >= Convert.ToDateTime(startMonth.AddMonths(1)).Day)
                                    {
                                        bModel.startday = Convert.ToDateTime(startMonth.AddMonths(1)).Day;
                                        bModel.startvalue = datavalue[i];
                                        bModel.starttime = startMonth.AddMonths(1).ToString("yyyy-MM-dd");
                                        var bn = await _plc_monthdataRepository.Update(bModel);

                                    }
                                }
                                else
                                {
                                    #region
                                    var amodel = new PLC_MonthData();
                                    amodel.dataname = dataname[i];
                                    amodel.startvalue = datavalue[i];
                                    amodel.endvalue = datavalue[i];
                                    amodel.datamonth = startMonth.AddMonths(1).Month;
                                    amodel.datayear = startMonth.AddMonths(1).Year.ToString();
                                    amodel.startday = startMonth.AddMonths(1).Day;
                                    amodel.endday = startMonth.AddMonths(1).Day;
                                    amodel.starttime = inputtime.Trim();
                                    amodel.endtime = inputtime.Trim();
                                    if (dataname[i].Contains("水"))
                                    { amodel.datakind = 0; }
                                    else if (dataname[i].Contains("天然气") || dataname[i].Contains("燃气"))
                                    { amodel.datakind = 2; }
                                    else if (dataname[i].Contains("氧"))
                                    { amodel.datakind = 3; }
                                    else
                                    { amodel.datakind = 1; }
                                    amodel.projectname = projectname;
                                    await _plc_monthdataRepository.Add(amodel);
                                    #endregion
                                }
                            }
                            #endregion
                        }

                    }
                    else
                    {
                        var amodel = new PLC_MonthData();
                        amodel.dataname = dataname[i];
                        amodel.startvalue  = datavalue[i];
                        amodel.endvalue = datavalue[i];
                        amodel.datamonth = mon;
                        amodel.datayear = year;
                        amodel.startday = Convert.ToDateTime(inputtime.Trim()).Day;
                        amodel.endday = Convert.ToDateTime(inputtime.Trim()).Day;
                        amodel.starttime = inputtime.Trim();
                        amodel.endtime = inputtime.Trim();
                        if (dataname[i].Contains("水"))
                        { amodel.datakind = 0; }
                        else if (dataname[i].Contains("天然气") || dataname[i].Contains("燃气"))
                        { amodel.datakind = 2; }
                        else if (dataname[i].Contains("氧"))
                        { amodel.datakind = 3; }
                        else
                        { amodel.datakind = 1; }
                        amodel.projectname = projectname;
                        await _plc_monthdataRepository.Add(amodel);
                    }
                    #endregion

                    var cmodel = new PLC_InputData();
                    cmodel.dataname = dataname[i];
                    cmodel.startvalue = datavalue[i];
                    cmodel.inputtime = inputtime;
                    cmodel.createusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; //"8000";
                    cmodel.deleteflag = 0;
                    cmodel.createtime = DateTime.Now.ToLocalTime();
                    if (dataname[i].Contains("水"))
                    { cmodel.datakind = 0; }
                    else if (dataname[i].Contains("天然气") || dataname[i].Contains("燃气"))
                    { cmodel.datakind = 2; }
                    else if (dataname[i].Contains("氧"))
                    { cmodel.datakind = 3; }
                    else
                    { cmodel.datakind = 1; }
                    cmodel.projectname = projectname;
                    if (await _plc_inputdataRepository.Add(cmodel))
                        res++;
                }
                if (res == t)
                {
                    return Success("添加数据成功");
                }
                else
                {
                    return Error("添加数据失败");
                }

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加水电气数据异常");
                return Error("添加水电气数据失败");
            }
        }

        //[Authorize]
        [HttpPost("update")]
        public async Task<IActionResult> UpdateData(string id, string datavalue)//(string dataname, string datavalue,string inputdate)
        {
            try
            {
                PLC_InputData comodel = new PLC_InputData();
                          
                var list = new List<FilterDefinition<PLC_InputData>>();
                var filterBuilder = Builders<PLC_InputData>.Filter;
                //list.Add(filterBuilder.Eq("dataname", dataname));
                //list.Add(filterBuilder.Eq("inputtime", DateTime.Now.ToString("yyyy-MM-dd")));
                list.Add(filterBuilder.Eq("id", id));
                var filter = Builders<PLC_InputData>.Filter.And(list);
                var count = await _plc_inputdataRepository.CountAsync(filter);
                if (count > 0)
                {
                    var dModel = await _plc_inputdataRepository.GetSingle(s => s.id .Equals(id) & s.deleteflag == 0, null);
                    dModel.startvalue = datavalue;
                    string inputtime = dModel.inputtime;
                    string dataname = dModel.dataname;
                    var tt = await _plc_inputdataRepository.Update(dModel);
                    if (tt)
                    {
                        #region 保存月数据
                        string year = DateTime.Now.Year.ToString();
                        int mon = Convert.ToDateTime(inputtime.Trim()).Month;// DateTime.Parse(inputtime.Trim());
                        var aModel = await _plc_monthdataRepository.GetSingle(s => s.datayear == year & s.datamonth == mon & s.dataname == dataname&s.projectname ==dModel .projectname , null);
                        if (aModel != null)
                        {

                            //判断更新止数
                            if (aModel.endday <= Convert.ToDateTime(inputtime.Trim()).Day)
                            {
                                aModel.endday = Convert.ToDateTime(inputtime.Trim()).Day;
                                aModel.endvalue = datavalue;
                                aModel.endtime = inputtime.Trim();
                                var n = await _plc_monthdataRepository.Update(aModel);
                                #region 判断如果为每月最后一天则将当前数做为下月起数
                                DateTime dtn = Convert.ToDateTime(inputtime.Trim());
                                DateTime startMonth = dtn.AddDays(1 - dtn.Day);  //本月月初  
                                DateTime endMonth = startMonth.AddMonths(1).AddDays(-1);
                                if (endMonth.Day == dtn.Day)//最后一天
                                {
                                    string byear = startMonth.AddMonths(1).Year.ToString();
                                    int bmon = startMonth.AddMonths(1).Month;
                                    var bModel = await _plc_monthdataRepository.GetSingle(s => s.datayear == byear & s.datamonth == bmon & s.dataname == dataname & s.projectname == dModel.projectname, null);
                                    if (bModel != null)
                                    {
                                        //判断更新止数
                                        if (bModel.endday <= Convert.ToDateTime(startMonth.AddMonths(1)).Day)
                                        {
                                            bModel.endday = Convert.ToDateTime(startMonth.AddMonths(1)).Day;
                                            bModel.endvalue = datavalue;
                                            bModel.endtime = startMonth.AddMonths(1).ToString("yyyy-MM-dd");
                                            var bn = await _plc_monthdataRepository.Update(bModel);


                                        }
                                        else if (bModel.startday >= Convert.ToDateTime(startMonth.AddMonths(1)).Day)
                                        {
                                            bModel.startday = Convert.ToDateTime(startMonth.AddMonths(1)).Day;
                                            bModel.startvalue = datavalue;
                                            bModel.starttime = startMonth.AddMonths(1).ToString("yyyy-MM-dd");
                                            var bn = await _plc_monthdataRepository.Update(bModel);

                                        }
                                    }
                                    else
                                    {
                                        #region
                                        var amodel = new PLC_MonthData();
                                        amodel.dataname = dataname;
                                        amodel.startvalue = datavalue;
                                        amodel.datamonth = mon;
                                        amodel.datayear = year;
                                        amodel.startday = Convert.ToDateTime(inputtime.Trim()).Day;
                                        amodel.endday = Convert.ToDateTime(inputtime.Trim()).Day;
                                        amodel.starttime = inputtime.Trim();
                                        amodel.endtime = inputtime.Trim();
                                        amodel.projectname = dModel.projectname;
                                        await _plc_monthdataRepository.Add(amodel);
                                        #endregion
                                    }
                                }
                                #endregion
                            }
                            else if (aModel.startday>= Convert.ToDateTime(inputtime.Trim()).Day)
                            {
                                aModel.startday = Convert.ToDateTime(inputtime.Trim()).Day;
                                aModel.startvalue = datavalue;
                                aModel.starttime = inputtime.Trim();
                                var n = await _plc_monthdataRepository.Update(aModel);
                                #region 判断如果为每月最后一天则将当前数做为下月起数
                                DateTime dtn = Convert.ToDateTime(inputtime.Trim());
                                DateTime startMonth = dtn.AddDays(1 - dtn.Day);  //本月月初  
                                DateTime endMonth = startMonth.AddMonths(1).AddDays(-1);
                                if (endMonth.Day == dtn.Day)//最后一天
                                {
                                    string byear = startMonth.AddMonths(1).Year.ToString();
                                    int bmon = startMonth.AddMonths(1).Month;
                                    var bModel = await _plc_monthdataRepository.GetSingle(s => s.datayear == byear & s.datamonth == bmon & s.dataname == dataname & s.projectname == dModel.projectname, null);
                                    if (bModel != null)
                                    {
                                        //判断更新止数
                                        if (bModel.endday <= Convert.ToDateTime(startMonth.AddMonths(1)).Day)
                                        {
                                            bModel.endday = Convert.ToDateTime(startMonth.AddMonths(1)).Day;
                                            bModel.endvalue = datavalue;
                                            bModel.endtime = startMonth.AddMonths(1).ToString("yyyy-MM-dd");
                                            var bn = await _plc_monthdataRepository.Update(bModel);


                                        }
                                        else if (bModel.startday >= Convert.ToDateTime(startMonth.AddMonths(1)).Day)
                                        {
                                            bModel.startday = Convert.ToDateTime(startMonth.AddMonths(1)).Day;
                                            bModel.startvalue = datavalue;
                                            bModel.starttime = startMonth.AddMonths(1).ToString("yyyy-MM-dd");
                                            var bn = await _plc_monthdataRepository.Update(bModel);

                                        }
                                    }
                                    else
                                    {
                                        #region
                                        var amodel = new PLC_MonthData();
                                        amodel.dataname = dataname;
                                        amodel.startvalue = datavalue;
                                        amodel.datamonth = mon;
                                        amodel.datayear = year;
                                        amodel.startday = Convert.ToDateTime(inputtime.Trim()).Day;
                                        amodel.endday = Convert.ToDateTime(inputtime.Trim()).Day;
                                        amodel.starttime = inputtime.Trim();
                                        amodel.endtime = inputtime.Trim();
                                        amodel.projectname = dModel.projectname;
                                        await _plc_monthdataRepository.Add(amodel);
                                        #endregion
                                    }
                                }
                                #endregion
                            }

                        }
                        else
                        {
                            var amodel = new PLC_MonthData();
                            amodel.dataname = dataname;
                            amodel.startvalue = datavalue;
                            amodel.datamonth = mon;
                            amodel.datayear = year;
                            amodel.startday = Convert.ToDateTime(inputtime.Trim()).Day;
                            amodel.endday = Convert.ToDateTime(inputtime.Trim()).Day;
                            amodel.starttime = inputtime.Trim();
                            amodel.endtime = inputtime.Trim();
                            amodel.projectname = dModel.projectname;
                            await _plc_monthdataRepository.Add(amodel);
                        }
                        #endregion

                        return Success("修改数据成功");
                    }
                }
                return Error("修改数据失败");
                

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改水电气数据异常");
                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 _plc_inputdataRepository.GetSingle(item);
                    ml.deleteflag = 1;
                    if (await _plc_inputdataRepository.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("请选择要删除的记录");
        }

        //[Authorize]
        [HttpPost("deleteby")]
        public async Task<IActionResult> DeleteData(string dataname, string inputdate)
        {
            try
            {
                PLC_InputData comodel = new PLC_InputData();

                var list = new List<FilterDefinition<PLC_InputData>>();
                var filterBuilder = Builders<PLC_InputData>.Filter;
                list.Add(filterBuilder.Eq("dataname", dataname));
                list.Add(filterBuilder.Eq("inputtime", DateTime.Now.ToString("yyyy-MM-dd")));
                var filter = Builders<PLC_InputData>.Filter.And(list);
                var count = await _plc_inputdataRepository.CountAsync(filter);
                if (count > 0)
                {
                    var dModel = await _plc_inputdataRepository.GetSingle(s => s.dataname.Equals(dataname) & s.inputtime == inputdate & s.deleteflag == 0, null);
                    dModel.deleteflag = 1;
                    var tt = await _plc_inputdataRepository.Update(dModel);
                    if (tt)
                        return Success("删除成功");
                }
                return Error("删除失败");


            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除水电气数据异常");
                return Error("删除水电气数据失败");
            }
        }


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

                //根据条件查询集合
                var flist = new List<FilterDefinition<PLC_InputData>>();
                flist.Add(Builders<PLC_InputData>.Filter.Eq("deleteflag", 0));
                if (!string.IsNullOrWhiteSpace(dataname))
                    flist.Add(Builders<PLC_InputData>.Filter.Where(s => s.dataname.Equals(dataname)));
                if (!string.IsNullOrWhiteSpace(projectname))
                    flist.Add(Builders<PLC_InputData>.Filter.Where(s => s.projectname.Equals(projectname)));
                if (!string.IsNullOrWhiteSpace(stime))
                {
                    DateTime dt2 = new DateTime();
                    if (DateTime.TryParse(stime.Trim(), out dt2))
                        flist.Add(Builders<PLC_InputData>.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_InputData>.Filter.Lt("createtime", etime + " 23:59:59"));
                }
                var filter = Builders<PLC_InputData>.Filter.And(flist);
                var list = await _plc_inputdataRepository.GetByPage(filter, pageindex, pagesize, sort);
                var count = await _plc_inputdataRepository.CountAsync(filter);
                var obj = new
                {
                    state = "success",
                    message = "根据条件获取分页数据成功",
                    rows = list,
                    total = count,
                };
                return Content(obj.ToJson());
                //return Success("根据条件获取值班电话分页数据成功", list);0
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据条件获取分页数据异常");
                return Error("根据条件获取分页数据异常");
            }
        }

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

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

        }

        
    }
}