using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using EquipmentApi.IRepositories;
using MadRunFabric.Model;
using EquipmentApi.Model.Input;
using MadRunFabric.Common;
using MadRunFabric.Common.Enums;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;
using EquipmentApi.Model.Dto;
using MadRunFabric.Model.MessageApi;
using Api.SignToken;
using MadRunFabric.Model.EquipmentApi.Model;
using MongoDB.Bson;
using System.Threading;
using MadRunFabric.Model.HangfireApi.Model;
using Microsoft.Extensions.Configuration;

namespace EquipmentApi.Controllers.workordermanage
{
    /// <summary>
    /// 设备保养工单控制器
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class WoMaintainBaseController : BaseController
    {
        private readonly ILogger<WoMaintainBaseController> _logger;
        private readonly IConfiguration _configuration;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        private readonly IWo_Maintain_PlanRepository _wo_maintain_planRepository;
        private readonly IWo_Maintain_BaseRepository _wo_maintain_baseRepository;
        private readonly IWo_Maintain_ItemsRepository _wo_maintain_itemsRepository;
        private readonly IHangfire_PlanRepository _hangfire_planrepository;
        private readonly IWo_Order_User_MapRepository _wo_order_user_maprepository;
        private readonly IWo_TimeOutRepository _wo_timeoutrepository;
        private readonly IPro_Project_InfoRepository _pro_project_infoRepository;
        private readonly IEqp_Equipment_InfoRepository _eqp_equipment_infoRepository;
        private readonly IHangfireService _hangfireService;
        private readonly IWo_Repair_BaseRepository _wo_repair_baseRepository;
        private readonly ISignTokenService _signTokenService;
        private readonly IWo_MattersRepository _wo_mattersRepository;
        public WoMaintainBaseController(ILogger<WoMaintainBaseController> logger,
            IConfiguration configuration,
            ISys_User_AccountRepository sys_user_accountRepository,
            IWo_Maintain_BaseRepository wo_maintain_baseRepository, IWo_Maintain_ItemsRepository wo_maintain_itemsRepository,
            IWo_Order_User_MapRepository wo_order_user_maprepository, IWo_TimeOutRepository wo_timeoutrepository,
            IPro_Project_InfoRepository pro_project_infoRepository, IEqp_Equipment_InfoRepository eqp_equipment_infoRepository,
            IHangfire_PlanRepository hangfire_planrepository, IWo_Maintain_PlanRepository wo_maintain_planRepository,
            IHangfireService hangfireService, IWo_Repair_BaseRepository wo_repair_baseRepository,
            ISignTokenService signTokenService, IWo_MattersRepository wo_mattersRepository)
        {
            _logger = logger;
            _configuration = configuration;
            _sys_user_accountRepository = sys_user_accountRepository;
            _wo_maintain_baseRepository = wo_maintain_baseRepository;
            _wo_maintain_itemsRepository = wo_maintain_itemsRepository;
            _wo_order_user_maprepository = wo_order_user_maprepository;
            _wo_timeoutrepository = wo_timeoutrepository;
            _pro_project_infoRepository = pro_project_infoRepository;
            _eqp_equipment_infoRepository = eqp_equipment_infoRepository;
            _wo_maintain_planRepository = wo_maintain_planRepository;
            _hangfire_planrepository = hangfire_planrepository;
            _hangfireService = hangfireService;
            _wo_repair_baseRepository = wo_repair_baseRepository;
            _signTokenService = signTokenService;
            _wo_mattersRepository = wo_mattersRepository;
        }
        /// <summary>
        /// 获取保养工单列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPageAsync(string projectid, string matterid, string maintainman, string stime, string etime, int state = -1, int pageindex = 1, int pagesize = 10)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            int recordCount = 0;
            var result = _wo_maintain_baseRepository.GetListsByPage(projectid, matterid, maintainman, stime, etime, state,  nowusercode,userinfo, pageindex, pagesize, out recordCount);
            var list = new List<Wo_Maintain_BaseDto>();
            #region 遍历计算是否超时
            foreach (var item in result)
            {
                var newModel = new Wo_Maintain_BaseDto();
                newModel = item;
                double timeoutlong = 0;
                if (item.wostate == (int)EnumWoMaintainState.deal || item.wostate == (int)EnumWoMaintainState.hangup)
                {
                    if (item.dealtime > item.endtime)
                        timeoutlong = (item.dealtime - item.endtime).TotalSeconds;
                }
                else
                {
                    if (DateTime.Now > item.endtime)
                        timeoutlong = (DateTime.Now - item.endtime).TotalSeconds;
                }
                newModel.timeoutlong = (int)Math.Ceiling(timeoutlong);
                #region 检查事项
                if (item.matterids != null)
                {
                    string[] equname = new string[item.matterids.Length];
                    for (int i = 0; i < item.matterids.Length; i++)
                    {
                        var matter = await _wo_mattersRepository.GetSingle(item.matterids[i]);
                        if (matter != null)
                        {
                            equname[i] = matter.matter;
                        }
                        else
                            equname[i] = "";
                    }
                    item.matternames = equname;
                }
                #endregion
                #region
                //if (item.equipmentid != null)
                //{
                //    string[] equname = new string[item.equipmentid.Length];
                //    for (int i = 0; i < item.equipmentid.Length; i++)
                //    {
                //        var eqpmo = await _eqp_equipment_infoRepository.GetSingle(item.equipmentid[i]);
                //        if (eqpmo != null)
                //        {
                //            equname[i] = eqpmo.equipment_name;
                //        }
                //        else
                //            equname[i] = "";
                //    }
                //    newModel.equipmentname = equname;
                //}
                #endregion
                list.Add(newModel);
            }
            #endregion
            var obj = new
            {
                rows = list.ToList(),
                total = recordCount,
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 获取实体
        /// </summary>
        [HttpGet("getsingle")]
        public async Task<IActionResult> GetSingleAsync(string id,int channelcode = 0)
        {
            //操作人
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");
            var model = _wo_maintain_baseRepository.GetDetails(id);
            if (model != null)
            {
                #region 检查事项
                if (model.matterids != null)
                {
                    string[] equname = new string[model.matterids.Length];
                    for (int i = 0; i < model.matterids.Length; i++)
                    {
                        var matter = await _wo_mattersRepository.GetSingle(model.matterids[i]);
                        if (matter != null)
                        {
                            equname[i] = matter.matter;
                        }
                        else
                            equname[i] = "";
                    }
                    model.matternames = equname;
                }
                #endregion
                #region 设备名称
                //if (model.equipmentid != null)
                //{
                //    string[] equname = new string[model.equipmentid.Length];
                //    for (int i = 0; i < model.equipmentid.Length; i++)
                //    {
                //        var eqpmo = await _eqp_equipment_infoRepository.GetSingle(model.equipmentid[i]);
                //        if (eqpmo != null)
                //            equname[i] = eqpmo.equipment_name;
                //        else
                //            equname[i] = "";
                //    }
                //    model.equipmentname = equname;
                //}
                #endregion
                #region 处理流程
                var itemlists = await _wo_maintain_itemsRepository.Get(i => i.wocode.Equals(model.wocode));
                model.itemlist = itemlists.ToList();
                #endregion
                #region 标记消息提醒工单（消息提醒，App推送）
                if (channelcode > 0)
                {                    
                    //int wostatemap = -1;
                    //if (model.wostate == 0)
                    //{
                    //    wostatemap = model.wostate; // 0;
                    //    listmap = listmap.Where(x => x.wostate == 0);
                    //}
                    if (model.wostate == 0 || model.wostate == 1)
                    {
                        //维修工单号
                        var listmap = await _wo_order_user_maprepository.Get(x => x.woid == model.id && x.wocode == model.wocode && x.channelcode == channelcode && x.readby == usercode);
                        var modelmap = listmap.FirstOrDefault();
                        if (modelmap == null)
                        {
                            //添加是否已读关系表
                            modelmap = new Wo_Order_User_Map();
                            modelmap.woid = model.id;
                            modelmap.wocode = model.wocode;
                            modelmap.wostate = model.wostate;
                            modelmap.readby = usercode;
                            modelmap.channelcode = channelcode;   //工单类型（枚举EnumOrderState） 维修工单 = 1, 保养工单 = 2, 运行工单 = 3, 超时工单 = 4
                            modelmap.isread = 1;
                            modelmap.isnotice = 1;
                            modelmap.readtime = DateTime.Now;
                            modelmap.note = model.woname + (string.IsNullOrEmpty(model.maintaincontent) ? "" : ",保养内容:" + model.maintaincontent); //保养内容
                           // modelmap.note = model.maintaincontent;
                            bool b = await _wo_order_user_maprepository.Add(modelmap);
                        }
                        else
                        {
                            modelmap.isread = 1;
                            modelmap.isnotice = 1;
                            modelmap.note = model.woname + (string.IsNullOrEmpty(model.maintaincontent) ? "" : ",保养内容:" + model.maintaincontent); //保养内容
                            //modelmap.note = model.maintaincontent;
                            bool b = await _wo_order_user_maprepository.UpdateOne(modelmap);
                        }
                    }
                }
                #endregion
                #region 上次保养情况
                var sort = Builders<Wo_Maintain_Base>.Sort.Descending("dealtime");
                var lModel = await _wo_maintain_baseRepository.GetSingle(s => s.planid == model.planid & s.dealtime < DateTime.Now & s.isdelete == false, sort);
                if (lModel != null)
                {
                    model.lastmaintainresult = lModel.equipstate;
                    model.lastmaintaintime = lModel.dealtime;
                    model.lastmaintaintype = lModel.maintaintype;
                }
                #endregion
                return Success("获取成功！", model);
            }
            return Error("获取失败");

        }

        /// <summary>
        /// 获取上次保养信息
        /// </summary>
        [HttpGet("getlastbyplan")]
        public async Task<IActionResult> GetLastByPlanAsync(string plan)
        {
            if (!string.IsNullOrWhiteSpace(plan))
            {
                var sort = Builders<Wo_Maintain_Base>.Sort.Descending("createtime");
                var dModel = await _wo_maintain_baseRepository.GetSingle(s => s.planid.Equals(plan) & s.isdelete == false, sort);

                if (dModel != null)
                {
                    return Success("获取保养工单成功", dModel);
                }
                else
                {
                    return Error("获取保养工单失败");
                }
            }
            else
            {
                return Error("获取参数失败");
            }

        }

        /// <summary>
        /// 添加保养工单
        /// </summary>
        [AllowAnonymous]
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(string planid)
        {
            _logger.LogError("WoMaintainBaseController/AddAsync  ");
            if (string.IsNullOrWhiteSpace(planid))
            {
                _logger.LogError("AddAsync Error  计划不能为空");
                return Error("计划不能为空");
            }

            int res = 0; int count = 0;
            var planmodel = await _wo_maintain_planRepository.GetSingle(planid);
            if (planmodel != null)
            {
                if (DateTime.Now.Date < planmodel.startdate.Date)
                {
                    _logger.LogError("AddAsync Error 未到计划执行时间，计划名称：" + planmodel.planname);
                    return Error("未到计划执行时间");
                }
                if (DateTime.Now.Date > planmodel.enddate.Date)
                {
                    planmodel.planstate = 1;
                    await _wo_maintain_planRepository.UpdateOne(planmodel);
                    removeTask(planid);
                    _logger.LogError("AddAsync Error 计划已结束，计划名称：" + planmodel.planname );
                    return Error("计划已结束");
                }
                var hangfiremodel = await _hangfire_planrepository.GetSingle(planmodel.hangfireid);

                Wo_Maintain_Base clmodel = new Wo_Maintain_Base();
                #region 基本信息
                clmodel.woname = planmodel.planname;
                clmodel.maintaincontent = planmodel.plancontent;
                clmodel.projectid = planmodel.projectid;
                clmodel.matterids = planmodel.matterids;
                //clmodel.systemid = planmodel.systemid;
                //clmodel.equipmentid = planmodel.equipmentid;
                clmodel.planid = planmodel.id;    //巡检计划id
                clmodel.extensionlist = planmodel.extensionlist;    //默认值[]

                clmodel.isdelete = false;
                clmodel.maintainpic = new List<FileBaseModel>();
                clmodel.maintaintype = planmodel.maintaintype;      //默认值[]
                clmodel.wostate = (int)EnumWoMaintainState.create;//任务状态:0创建工单，1已转派，2挂起，9已完成

                clmodel.maintainuser = new List<string>();
                clmodel.maintainusername = new List<string>();
                clmodel.dealuser = new List<string>();
                clmodel.dealusername = new List<string>();
                #endregion
                #region 获取上一次巡检信息
                var sort = Builders<Wo_Maintain_Base>.Sort.Descending("createtime");
                var dmodel = await _wo_maintain_baseRepository.GetSingle(s => s.planid.Equals(planmodel.id) & s.isdelete == false, sort);
                if (dmodel != null)
                {
                    clmodel.lastmaintaintime = dmodel.dealtime;
                    clmodel.lastmaintainresult = dmodel.equipstate;
                    if (dmodel.lastmaintaintype != null)
                    {
                        clmodel.lastmaintaintype = dmodel.maintaintype;
                    }
                    else
                    {
                        clmodel.lastmaintaintype = new List<string>();
                    }
                    
                }
                #endregion

                if (hangfiremodel != null)
                {
                    foreach (var item in hangfiremodel.extensiontime)
                    {
                        Thread.Sleep(500);
                        clmodel.id = ObjectId.GenerateNewId().ToString();
                        //clmodel.wocode = DateTime.Now.ToString("yyMMddHHmmssffffff");
                        clmodel.wocode = UniqueData.Gener("", 2);
                        //clmodel.wodate = DateTime.Now.ToString("yyyy-MM-dd");
                        //clmodel.starttime = DateTime.Parse(DateTime.Now.AddDays(item.startdate - 1).ToString("yyyy-MM-dd") + " " + item.starttime.ToString("HH:mm"));
                        //clmodel.endtime = DateTime.Parse(DateTime.Now.AddDays(item.enddate - 1).ToString("yyyy-MM-dd") + " " + item.endtime.ToString("HH:mm"));
                        DateTime dtnow = DateTime.Now;
                        clmodel.wodate = dtnow.ToString("yyyy-MM-dd");
                        if (hangfiremodel.plancycle == (int)EnumPlanCycle.darly)
                        {
                            #region 周期是天
                            clmodel.starttime = DateTime.Parse(dtnow.AddDays(item.startdate - 1).ToString("yyyy-MM-dd") + " " + item.starttime.ToString("HH:mm"));
                            clmodel.endtime = DateTime.Parse(dtnow.AddDays(item.enddate - 1).ToString("yyyy-MM-dd") + " " + item.endtime.ToString("HH:mm"));
                            #endregion
                        }
                        else if (hangfiremodel.plancycle == (int)EnumPlanCycle.monthly)
                        {
                            dtnow = new DateTime(dtnow.Year, dtnow.Month, 1);
                            #region 周期是月
                            clmodel.starttime = DateTime.Parse(dtnow.AddMonths(item.startdate - 1).ToString("yyyy-MM-dd") + " 00:00");
                            clmodel.endtime = DateTime.Parse(dtnow.AddMonths(item.enddate).AddDays(-1).ToString("yyyy-MM-dd") + " 23:59:59");
                            #endregion
                        }
                        clmodel.createtime = DateTime.Now;
                        if (await _wo_maintain_baseRepository.Add(clmodel))
                        {
                            AddItems(clmodel.id, clmodel.wocode, (int)EnumWoMaintainState.create, 0, 0, "", "", "创建工单", "");
                            res += 1;
                        }
                        count++;
                    }
                }
            }
            if (res == count && res > 0)
            {
                _logger.LogError("添加工单成功，工单名称：" + planmodel.planname + "，工单内容：" + planmodel.plancontent + ",添加了" + count + "条工单");
                return Success("添加成功");
            }
            else
            {
                _logger.LogError("添加工单失败，工单名称：" + planmodel.planname + "，工单内容：" + planmodel.plancontent + ",添加了" + count + "条工单");
                return Error("添加失败");
            }
        }
        #region  添加修改工单重做
        //[AllowAnonymous]
        //[HttpPost("add")]
        //public async Task<IActionResult> AddAsync(WoMaintainBaseInput input)
        //{
        //    if (string.IsNullOrWhiteSpace(input.proname))
        //    {
        //        return Error("请选择项目");
        //    }
        //    else
        //    {
        //        var pro = await _pro_project_infoRepository.GetSingle(input.proname);
        //        if (pro != null)
        //        {
        //            if (pro.isend == 1)
        //            {
        //                return Error("暂停保养工单");
        //            }
        //        }
        //    }
        //    Wo_Maintain_Base clmodel = new Wo_Maintain_Base();
        //    var res = false;
        //    clmodel.id = ObjectId.GenerateNewId().ToString();
        //    clmodel.wocode = DateTime.Now.ToString("yyyyMMddHHmmssfff");

        //    clmodel.projectid = input.proname;//项目名称
        //    clmodel.systemid = input.sysname;//系统名称
        //    clmodel.equipmentid = input.equipname;//设备名称
        //    clmodel.planid = input.plan;//保养计划

        //    clmodel.wostate = (int)EnumWoMaintainState.create;//任务状态:0创建工单，1已转派，2挂起，9已完成
            
        //    #region 获取上一次巡检信息
        //    //var sort = Builders<Wo_Maintain_Base>.Sort.Descending("createtime");
        //    //var dmodel = await _wo_maintain_baseRepository.GetSingle(s => s.equipname.Equals(input.equipname) & s.isdelete == false & s.plan==input.plan, sort);
        //    //if (dmodel != null)
        //    //{
        //    //    clmodel.lastmaintaintime = dmodel.dealtime;
        //    //    //modelequ.thischeckime = dModel.thischeckime;
        //    //    clmodel.lastmaintainresult = dmodel.equipstate;//
        //    //    if (dmodel.lastmaintaintype != null)
        //    //    {
        //    //        clmodel.lastmaintaintype = dmodel.maintaintype;
        //    //    }
        //    //    else
        //    //    {
        //    //        clmodel.lastmaintaintype = new List<string>();
        //    //    }
        //    //}
        //    //else
        //    //{
        //    //    clmodel.lastmaintaintype = new List<string>();
        //    //}
        //    #endregion
        //    #region 本次保养情况
        //    clmodel.maintaincontent = input.maintaincontent;
        //    if (!string.IsNullOrWhiteSpace(input.timemaintaintype1))
        //    {
        //        var maintype= new List<string>();
        //        var typearr = input.timemaintaintype1.Split(',');
        //        foreach (var item in typearr)
        //        {
        //            maintype.Add(item);
        //        }
        //        clmodel.timemaintaintype = maintype;
        //    }
        //    #endregion
        //    clmodel.maintaintype = new List<string>();      //默认值[]
        //    clmodel.maintainpic = new List<FileBaseModel>();//默认值[]

        //    clmodel.createtime = DateTime.Now;
        //    clmodel.isdelete = false;

        //    res = await _wo_maintain_baseRepository.Add(clmodel);
        //    if (res)
        //    {
        //        //string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
        //        AddItems(clmodel.wocode, clmodel.wostate, 0, "", "", "添加工单,工单编号：" + clmodel.wocode, null, "");
        //        return Success("保养工单添加成功");
        //    }
        //    else
        //    {
        //        return Error("保养工单添加失败");
        //    }
        //}
        #endregion
       

        /// <summary>
        /// 处理保养工单
        /// </summary>
        [HttpPost("deal")]
        public async Task<IActionResult> UpdateDealAsync(WoMaintainBaseInput input)
        {
            if (input.equipstate == 0 && string.IsNullOrEmpty(input.exceptiondes))
                return Error("异常说明不能为空");
            if (!string.IsNullOrWhiteSpace(input.id))
            {
                string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                string optusername = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
                //var userstr = _signTokenService.GetUserInfoAsync(optuser).Result;

                
                var userinfos = _sys_user_accountRepository.GetUserInfo(optuser);                

                Wo_Maintain_Base clmodel = await _wo_maintain_baseRepository.GetSingle(input.id);
                var res = false;
                if (clmodel != null)
                {
                    if (clmodel.wostate == (int)EnumWoMaintainState.deal || clmodel.wostate == (int)EnumWoMaintainState.hangup)
                    {
                        return Error("已经处理过了，不能再次处理");
                    }
                    clmodel.maintaintime = DateTime.Now;//本次保养时间
                    if (!string.IsNullOrEmpty(input.maintaincontent))
                        clmodel.maintaincontent = input.maintaincontent;//本次保养内容
                    
                    if (input.maintaintype != null)
                    {
                        clmodel.maintaintype = input.maintaintype;
                    }
                    else
                    {
                        clmodel.maintaintype = new List<string>();
                    }
                    clmodel.replacedes = input.replacedes;//更换说明
                    if (input.maintainpic != null)
                    {
                        clmodel.maintainpic = input.maintainpic;
                    }
                    else
                    {
                        clmodel.maintainpic = new List<FileBaseModel>();
                    }
                    if (input.extensionlist != null)
                    {
                        clmodel.extensionlist = input.extensionlist;
                    }
                    else
                    {
                        clmodel.extensionlist = new List<ExtensionFileModel>();
                    }
                    clmodel.equipstate = input.equipstate;//设备状态 0正常，1异常 
                    clmodel.exceptiondes = input.exceptiondes;//异常说明
                    if (input.wostate == 3)
                        clmodel.wostate = (int)EnumWoMaintainState.deal;//任务状态:0创建工单，1已转派，6挂起;
                    if (input.wostate == 6)
                        clmodel.wostate = (int)EnumWoMaintainState.hangup;
                    clmodel.dealtime = DateTime.Now;
                    #region 处理人
                    string dealuserinfos = optuser + "-" + optusername;
                    clmodel.dealuser.Add(optuser);
                    clmodel.dealusername.Add(optusername);

                    if (input.dealuser != null)
                    {
                        foreach (string struser in input.dealuser)
                        {
                            if (!clmodel.dealuser.Contains(struser))
                            {
                                ////var dealuserstr = _signTokenService.GetUserInfoAsync(optuser).Result;
                                //var dealuserinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();
                                var dealuserinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

                                clmodel.dealuser.Add(optuser);
                                clmodel.dealusername.Add(optusername);

                                dealuserinfos = dealuserinfos + "、" + dealuserinfo.usercode + "-" + dealuserinfo.username;
                            }
                        }
                    }
                    #endregion
                    res = await _wo_maintain_baseRepository.UpdateOne(clmodel);
                    if (res)
                    {
                        int islast = input.wostate == (int)EnumWoMaintainState.deal ? 1 : 0;
                        AddItems(clmodel.id,clmodel.wocode, clmodel.wostate,0, islast, "", "", dealuserinfos+"处理工单，工单编号：" + clmodel.wocode + "，说明：" + input.exceptiondes, optuser);
                        return Success("处理工单成功");
                    }
                    else
                    {
                        return Error("处理工单失败");
                    }
                }
                else
                {
                    return Error("处理工单失败");
                }
            }
            return Error("保存失败");
        }

        /// <summary>
        /// 抢单
        /// </summary>
        /// <param name="wocode"></param>
        /// <param name="channel"></param>
        /// <returns></returns>
        [HttpPost("grab")]
        public async Task<IActionResult> UpdateGrabAsync(string id)
        {
            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string optusername = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
            #region 未处理工单超限
            int limitcount = _wo_repair_baseRepository.GetLimitCount(optuser);
            if (limitcount > 0)
            {
                return Error("你已经有" + limitcount + "个未处理工单，已超上限");
            }
            #endregion
            var model = await _wo_maintain_baseRepository.GetSingle(id);
            if (model == null)
                return Error("操作失败");
            //model.maintainman = usercode; //巡检人
            model.maintainuser = new List<string>() { optuser }; //巡检人
            model.maintainusername = new List<string>() { optusername };
            model.wostate = (int)EnumWoMaintainState.grab;
            bool b = await _wo_maintain_baseRepository.UpdateOne(model);
            if (b)
            {
                int islast = 0;    //是否最后一步 0否 1是
                AddItems(model.id, model.wocode, model.wostate, 0, islast, optuser, "", optuser + "操作抢单", optuser);
                #region 标记消息提醒工单（消息提醒，App推送）
                //工单信息
                var listmap = await _wo_order_user_maprepository.Get(x => x.wocode == model.wocode && x.channelcode == 3 && x.readby == optuser);
                var modelmap = listmap.FirstOrDefault();
                if (modelmap != null)
                {
                    //删除工单关系表中对应工单
                    bool boo = await _wo_order_user_maprepository.Remove(modelmap.id);
                }
                #endregion
                return Success("抢单成功");
            }
            return Error("抢单失败");
        }

        /// <summary>
        /// 转派保养工单
        /// </summary>
        [HttpPost("assign")]
        public async Task<IActionResult> UpdateAssignAsync(string woid, string touser, string des, int wostate, int ishasten)
        {
            if (string.IsNullOrEmpty(touser))
                return Error("转派的对象不能为空");
            #region 未处理工单超限
            int limitcount = _wo_repair_baseRepository.GetLimitCount(touser);
            if (limitcount > 0)
            {
                return Error(touser+"已经有" + limitcount + "个未处理工单，已超上限");
            }
            #endregion
            #region 判断是否维修工
            //var touserstr = _signTokenService.GetUserInfoAsync(touser).Result;

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(touser);
            var touserinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            //var toresult = touserstr.ToJObject();
            //if (toresult["state"].ToString() != "success")
            //{
            //    return Error(touser + "工号不存在");
            //}
            //var touserinfo = toresult["data"].ToString().ToObject<UserInfoModel>();
            if (touserinfo == null)
                return Error(touser + "工号不存在");

            if (touserinfo.level != 1)
            {
                return Error(touser + "不是维修工");
            }
            #endregion
            Wo_Maintain_Base clmodel = await _wo_maintain_baseRepository.GetSingle(woid);
            if (clmodel != null)
            {
                //clmodel.maintainman = touser;//保养人
                clmodel.maintainuser = new List<string>() { touser }; //巡检人
                clmodel.maintainusername = new List<string>() { touserinfo.username };
                //clmodel.wostate = wostate;//任务状态:0创建工单，1已转派，2挂起，9已完成;
                if (wostate == 1)
                    clmodel.wostate = (int)EnumWoMaintainState.assign;
                if (wostate == 3)
                    clmodel.wostate = (int)EnumWoMaintainState.deal;
                if (wostate == 6)
                    clmodel.wostate = (int)EnumWoMaintainState.hangup;

                var res = await _wo_maintain_baseRepository.UpdateOne(clmodel);
                if (res)
                {
                    int islast = wostate == 3 ? 1 : 0;
                    string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                    AddItems(clmodel.id,clmodel.wocode, clmodel.wostate, ishasten, islast, touser, "", "转派处理工单，工单编号：" + clmodel.wocode + "，说明：" + des, optuser);
                    #region 标记消息提醒工单（消息提醒，App推送）
                    //工单信息
                    var listmap = await _wo_order_user_maprepository.Get(x => x.wocode == clmodel.wocode && x.channelcode == 2 && x.readby == touser);
                    var modelmap = listmap.FirstOrDefault();
                    if (modelmap != null)
                    {
                        //删除工单关系表中对应工单
                        bool boo = await _wo_order_user_maprepository.Remove(modelmap.id);
                    }
                    #endregion
                    return Success("转派处理工单成功");
                }
                else
                {
                    return Error("转派处理工单失败");
                }
            }

            return Error("保存失败");
        }

        /// <summary>
        /// 批量转派保养工单
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="touser"></param>
        /// <param name="des"></param>
        /// <param name="wostate"></param>
        /// <returns></returns>
        [HttpPost("assignmany")]
        public async Task<IActionResult> UpdateAssignManyAsync(string[] ids, string touser, string des, int wostate, int ishasten)
        {
            if (string.IsNullOrEmpty(touser))
                return Error("转派的对象不能为空");
            #region 判断是否维修工
            //var touserstr = _signTokenService.GetUserInfoAsync(touser).Result;

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(touser);
            var touserinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            //var toresult = touserstr.ToJObject();
            //if (toresult["state"].ToString() != "success")
            //{
            //    return Error(touser + "工号不存在");
            //}
            //var touserinfo = toresult["data"].ToString().ToObject<UserInfoModel>();
            if (touserinfo == null)
                return Error(touser + "工号不存在");

            if (touserinfo.level != 1)
            {
                return Error(touser + "不是维修工");
            }
            #endregion
            int res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    Wo_Maintain_Base clmodel = await _wo_maintain_baseRepository.GetSingle(item);
                    if (clmodel != null)
                    {
                        //clmodel.maintainman = touser;//保养人
                        clmodel.maintainuser = new List<string>() { touser }; //巡检人
                        clmodel.maintainusername = new List<string>() { touserinfo.username };
                        //clmodel.wostate = wostate;//任务状态:0创建工单，1已转派，2挂起，9已完成;
                        if (wostate == 1)
                            clmodel.wostate = (int)EnumWoMaintainState.assign;
                        if (wostate == 3)
                            clmodel.wostate = (int)EnumWoMaintainState.deal;
                        if (wostate == 6)
                            clmodel.wostate = (int)EnumWoMaintainState.hangup;

                        var b = await _wo_maintain_baseRepository.UpdateOne(clmodel);
                        if (b)
                        {
                            int islast = wostate == 3 ? 1 : 0;
                            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                            AddItems(clmodel.id,clmodel.wocode, clmodel.wostate, ishasten, islast, touser, "", "转派处理工单，工单编号：" + clmodel.wocode + "，说明：" + des,  optuser);
                            #region 标记消息提醒工单（消息提醒，App推送）
                            //工单信息
                            var listmap = await _wo_order_user_maprepository.Get(x => x.wocode == clmodel.wocode && x.channelcode == 2 && x.readby == touser);
                            var modelmap = listmap.FirstOrDefault();
                            if (modelmap != null)
                            {
                                //删除工单关系表中对应工单
                                bool boo = await _wo_order_user_maprepository.Remove(modelmap.id);
                            }
                            #endregion
                            res++;
                        }
                    }
                }
            }
            if (res == ids.Length)
            {
                return Success("转派处理工单成功");
            }
            else if (res > 0 && res < ids.Length)
            {
                return Error("部分工单转派失败，请稍后重试");
            }
            else
            {
                return Error("转派处理工单失败");
            }
        }

        [HttpPost("delete")]
        public async Task<IActionResult> RemoveAsync(string[] ids)
        {
            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                try
                {
                    foreach (var item in ids)
                    {
                        var ml = await _wo_maintain_baseRepository.GetSingle(item);
                        if (ml != null)
                        {
                            ml.isdelete = true;
                            if (await _wo_maintain_baseRepository.UpdateOne(ml))
                            {
                                res += 1;
                                var clmodel = await _wo_timeoutrepository.GetSingle(c => c.woid == ml.id && c.wotype == (int)EnumWoType.maintain);
                                if (clmodel != null)
                                {
                                    clmodel.isdelete = true;
                                    await _wo_timeoutrepository.UpdateOne(clmodel);
                                }
                            }
                        }
                    }
                    if (res == ids.Length)
                        return Success("删除成功");
                    else if (res > 0 && res < ids.Length)
                        return Error("部分删除失败，请查看后重新操作");
                    else
                        return Error("删除失败，请查看后重新操作");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "保养工单删除异常");
                    return Error("保养工单删除失败");
                }
            }
            else
                return Error("请选择要删除的记录");
        }
        /// <summary>
        /// 更新处理人员
        /// </summary>
        [HttpPost("updatedealuser")]
        public async Task<IActionResult> UpdateDealUserAsync(string woid, List<string> dealusers)
        {
            if (string.IsNullOrEmpty(woid))
            {
                _logger.LogError("updatedealuser操作失败woid为空");
                return Error("操作失败");
            }
            if (dealusers == null)
            {
                dealusers = new List<string>();
            }
            if (dealusers != null && dealusers.Count() > 4)
            {
                return Error("协助人员不能超过4人");
            }

            string optuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string optusername = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            //var userstr = _signTokenService.GetUserInfoAsync(optuser).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(optuser);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            var cls = await _wo_maintain_baseRepository.Get(p => p.id == woid && p.isdelete == false);
            var clmodel = cls.FirstOrDefault();
            if (clmodel != null && (clmodel.wostate == (int)EnumWoMaintainState.assign || clmodel.wostate == (int)EnumWoMaintainState.grab) && string.Join(',', clmodel.maintainuser).Contains(optuser))
            {
                dealusers = dealusers.Distinct().ToList();//去重
                List<string> dealusernames = new List<string>();

                string adduserinfos = string.Empty;
                string deluserinfos = string.Empty;
                var addusers = dealusers.Except(clmodel.dealuser).ToList();
                var delusers = clmodel.dealuser.Except(dealusers).ToList();
                var allusers = dealusers.Union(clmodel.dealuser).ToList();

                foreach (var dealuser in allusers)
                {
                    //var touserstr = _signTokenService.GetUserInfoAsync(dealuser).Result;
                    //var toresult = touserstr.ToJObject();
                    //if (toresult["state"].ToString() != "success")
                    //{
                    //    return Error(dealuser + "工号不存在");
                    //}
                    //var touserinfo = toresult["data"].ToString().ToObject<UserInfoModel>();
                    
                    var userinfos2 = _sys_user_accountRepository.GetUserInfo(dealuser);
                    var touserinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos2.ToJson());

                    if (touserinfo.level != 1)
                    {
                        return Error(dealuser + "不是维修工");
                    }

                    if (addusers.Contains(dealuser))//新增人员
                    {
                        int limitcount = _wo_repair_baseRepository.GetLimitCount(dealuser);
                        if (limitcount > 0)
                        {
                            return Error(dealuser + "已经有" + limitcount + "个未处理工单，已超上限");
                        }
                        if (string.IsNullOrEmpty(adduserinfos))
                            adduserinfos = touserinfo.usercode + "-" + touserinfo.username;
                        else
                            adduserinfos = adduserinfos + "、" + touserinfo.usercode + "-" + touserinfo.username;
                    }
                    if (delusers.Contains(dealuser))//删除人员
                    {
                        if (string.IsNullOrEmpty(deluserinfos))
                            deluserinfos = touserinfo.usercode + "-" + touserinfo.username;
                        else
                            deluserinfos = deluserinfos + "、" + touserinfo.usercode + "-" + touserinfo.username;
                    }
                    else
                    {
                        dealusernames.Add(touserinfo.username);
                    }
                }

                clmodel.dealuser = dealusers;
                clmodel.dealusername = dealusernames;
                await _wo_maintain_baseRepository.UpdateOne(clmodel);


                string dealuserinfos = string.Empty;
                if (!string.IsNullOrEmpty(adduserinfos))
                    dealuserinfos = dealuserinfos + " 新增协助人员：" + adduserinfos;
                if (!string.IsNullOrEmpty(deluserinfos))
                    dealuserinfos = (string.IsNullOrEmpty(dealuserinfos) ? " " : "，") + "删除协助人员：" + deluserinfos;
                AddItems(clmodel.id, clmodel.wocode, clmodel.wostate, 0, 0, "", "", dealuserinfos, optuser);
                return Success("操作成功");
            }
            else
            {
                _logger.LogError("updatedealuser操作失败clmodel为空");
                return Error("操作失败");
            }
        }
        #region 删除计划
        private void removeTask(string id)
        {
            _hangfireService.RemovePlan(id);
        }
        #endregion

        #region 记录工单的历史轨迹
        /// <summary>
        /// 添加工单记录
        /// </summary>
        /// <param name="wocode">工单编号</param>
        /// <param name="wostate">工单状态</param>
        /// <param name="islast">是否最后一步 0否 1是</param>
        /// <param name="touser">指派下一步人员</param>
        /// <param name="todept">指派下一步部门</param>
        /// <param name="detail">处理说明</param>
        /// <param name="files">附件</param>
        /// <param name="optuser">当前操作人</param>
        private async void AddItems(string woid, string wocode, int wostate, int ishasten, int islast, string touser,
            string todept, string detail, string optuser)
        {
            #region 更新流程
            if (wostate > 0)
            {
                var ll = await _wo_maintain_itemsRepository.Get(Builders<Wo_Maintain_Items>.Filter.Eq("woid", woid), null, Builders<Wo_Maintain_Items>.Sort.Descending("createtime"));
                if (ll.Count() > 0)
                {
                    Wo_Maintain_Items itemsmodelo = ll.FirstOrDefault();
                    itemsmodelo.sureuser = optuser;
                    itemsmodelo.suretime = DateTime.Now;
                    itemsmodelo.itemstate = 1;
                    itemsmodelo.islast = islast;

                    await _wo_maintain_itemsRepository.UpdateOne(itemsmodelo);
                }
            }
            #endregion
            #region 添加下一步明细
            Wo_Maintain_Items itemsmodel = new Wo_Maintain_Items();
            itemsmodel.woid = woid;
            itemsmodel.wocode = wocode;
            itemsmodel.wostate = wostate;
            itemsmodel.itemstate = 0;
            itemsmodel.isdelete = false;
            itemsmodel.createby = optuser;
            itemsmodel.createtime = DateTime.Now;
            itemsmodel.detail = detail;
            itemsmodel.islast = islast;
            if (wostate < (int)EnumWoMaintainState.deal)
            {
                itemsmodel.ishasten = ishasten;
                #region 创建、转派、抢单
                itemsmodel.touser = touser;
                itemsmodel.todept = todept;
                #endregion
            }
            else if (wostate == (int)EnumWoMaintainState.deal)
            {
                #region 结单
                itemsmodel.dealtime = DateTime.Now;
                itemsmodel.dealuser = optuser;
                #endregion
            }
            await _wo_maintain_itemsRepository.Add(itemsmodel);
            #endregion
        }

        #endregion
        [HttpGet("mtchart")]
        public async Task<IActionResult> getchartAsync(string projectid)
        {
            var result = _wo_maintain_baseRepository.GetChart(projectid);
            foreach (var item in result)
            {
                item.yxjcounts = (int)await _wo_maintain_baseRepository.Count(runn => runn.projectid.Equals(projectid) && runn.wodate.Equals(item.wodate) && runn.wostate >= (int)EnumWoMaintainState.deal);
                item.wxjcounts = (int)await _wo_maintain_baseRepository.Count(runn => runn.projectid.Equals(projectid) && runn.wodate.Equals(item.wodate) && runn.wostate < (int)EnumWoMaintainState.deal);
                item.abcounts = (int)await _wo_maintain_baseRepository.Count(runn => runn.projectid.Equals(projectid) && runn.wodate.Equals(item.wodate) && runn.equipstate == (int)EnumWoMEquipmentState.abnormal);
            }
            var list = result.ToList().OrderByDescending(c => c.wodate);
            return Success("报表获取", list);
        }
    }
}