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

namespace EquipmentApi.Controllers.workordermanage
{
    /// <summary>
    /// 设备运行
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class WoEquipmentRunningController : BaseController
    {
        private readonly ILogger<WoEquipmentRunningController> _logger;
        private readonly IConfiguration _configuration;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        private readonly IWo_EquipmentRunningRepository _wo_equipmentrunningrepository;
        private readonly IWo_EquipmentRunning_PlanRepository _wo_equipmentrunning_planrepository;
        private readonly IHangfire_PlanRepository _hangfire_planrepository;
        private readonly IWo_EquipmentRunning_ItemsRepository _wo_equipmentrunning_itemsrepository;
        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 IHangfireService _hangfireService;
        private readonly IEqp_Equipment_InfoRepository _eqp_equipment_infoRepository;
        private readonly IWo_Repair_BaseRepository _wo_repair_baseRepository;
        private readonly IWo_MattersRepository _wo_mattersRepository;
        private readonly ISignTokenService _signTokenService;
        public WoEquipmentRunningController(
            ILogger<WoEquipmentRunningController> logger,
            IConfiguration configuration,
            ISys_User_AccountRepository sys_user_accountRepository,
            IWo_EquipmentRunningRepository wo_equipmentrunningrepository,
            IWo_EquipmentRunning_ItemsRepository wo_equipmentrunning_itemsrepository,
            IWo_Order_User_MapRepository wo_order_user_maprepository,
            IWo_TimeOutRepository wo_timeoutrepository, 
            IPro_Project_InfoRepository pro_project_infoRepository,
            IWo_EquipmentRunning_PlanRepository wo_equipmentrunning_planrepository,
            IEqp_Equipment_InfoRepository eqp_equipment_infoRepository,
            IHangfire_PlanRepository hangfire_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_equipmentrunningrepository = wo_equipmentrunningrepository;
            _wo_equipmentrunning_itemsrepository = wo_equipmentrunning_itemsrepository;
            _wo_order_user_maprepository = wo_order_user_maprepository;
            _wo_timeoutrepository = wo_timeoutrepository;
            _pro_project_infoRepository = pro_project_infoRepository;
            _wo_equipmentrunning_planrepository = wo_equipmentrunning_planrepository;
            _hangfire_planrepository = hangfire_planrepository;
            _hangfireService = hangfireService;
            _eqp_equipment_infoRepository = eqp_equipment_infoRepository;
            _wo_repair_baseRepository = wo_repair_baseRepository;
            _wo_mattersRepository = wo_mattersRepository;
            _signTokenService = signTokenService;
        }

        /// <summary>
        /// 获取设备运行工单列表 - 关联查询
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlistsbypage")]
        public async Task<IActionResult> GetListsByPageAsync(string projectid, string matterid, string wocode, string createby, string daytype, 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_equipmentrunningrepository.GetListsByPage(projectid, matterid, wocode, createby, daytype, stime, etime, state, nowusercode, userinfo, pageIndex, pageSize, out recordCount);
            var list = new List<Wo_EquipmentRunningDto>();
            #region 遍历计算是否超时
            foreach (var item in result)
            {
                var newModel = new Wo_EquipmentRunningDto();
                newModel = item;
                double timeoutlong = 0;
                if (item.wostate == (int)EnumEquipmentRunningState.deal || item.wostate == (int)EnumEquipmentRunningState.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[] mattername = 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)
                        {
                            mattername[i] = matter.matter;
                        }
                        else
                            mattername[i] = "";
                    }
                    newModel.matternames = mattername;
                }
                #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,
                total = recordCount,
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 获取洗涤工单列表 - 关联查询
        /// </summary>
        /// <returns></returns>
        [HttpGet("getapplists")]
        public IActionResult GetAppLists(string projectid, string matterid, string checkby, string daytype, int state, string stime, string etime)
        {
            string rolecode = User.Claims.FirstOrDefault(c => c.Type == "RoleCode").Value;
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            var result = _wo_equipmentrunningrepository.GetAppLists(projectid, matterid, checkby, daytype, state, stime, etime, rolecode, usercode);
            return Success("获取成功", result);
        }

        /// <summary>
        /// 获取设备运行详情 by id - 关联查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("getdetails")]
        public async Task<IActionResult> GetDetails(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_equipmentrunningrepository.GetDetails(id);
            if (model != null)
            {
                #region 检查事项
                if (model.matterids != null)
                {
                    string[] mattername = 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)
                            mattername[i] = matter.matter;
                        else
                            mattername[i] = "";
                    }
                    model.matternames = mattername;
                }
                #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_equipmentrunning_itemsrepository.Get(i => i.wocode.Equals(model.wocode));
                model.itemlist = itemlists.ToList();
                #endregion
                #region 上次巡检情况
                var sort = Builders<Wo_EquipmentRunning>.Sort.Descending("createtime");
                var lModel = await _wo_equipmentrunningrepository.GetSingle(s => s.planid == model.planid & s.dealtime < DateTime.Now & s.isdelete == 0, sort);
                if (lModel != null)
                {
                    model.lastcheckresultid = lModel.quipmenttype;
                    model.lastchecktime = lModel.dealtime;
                }
                #endregion
                #region 标记消息提醒工单（消息提醒，App推送）
                if (channelcode > 0)
                {
                    if (model.wostate == 0 || model.wostate == 1 || (model.wostate == 3 && model.isreturnmsg == 1))
                    {
                        //维修工单号
                        var listmap = await _wo_order_user_maprepository.Get(x => x.woid == model.id && x.wocode == model.wocode && x.channelcode == channelcode && x.readby == usercode);
                        listmap = listmap.Where(x => x.wostate == model.wostate);
                        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.wocontent) ? "" : ",工单内容:" + model.wocontent) + (string.IsNullOrEmpty(model.checkcontent) ? "" : ",异常说明:" + model.checkcontent); //运维内容
                            //modelmap.note = model.checkcontent;
                            bool b = await _wo_order_user_maprepository.Add(modelmap);
                        }
                        else
                        {
                            modelmap.isread = 1;
                            modelmap.isnotice = 1;
                            modelmap.note = model.woname + (string.IsNullOrEmpty(model.wocontent) ? "" : ",工单内容:" + model.wocontent) + (string.IsNullOrEmpty(model.checkcontent) ? "" : ",异常说明:" + model.checkcontent); //运维内容
                            //modelmap.note = model.checkcontent;
                            bool b = await _wo_order_user_maprepository.UpdateOne(modelmap);
                        }
                    }

                }
                #endregion
                return Success("获取成功！", model);
            }
            return Error("获取失败");
        }

        /// <summary>
        /// 获取上次设备运行信息 by equipmentid
        /// </summary>
        [HttpGet("getlastdetails")]
        public async Task<IActionResult> GetLastDetailsAsync(string matterids)
        {
            if (string.IsNullOrEmpty(matterids))
                return Error("操作参数失败");
            try
            {
                var sort = Builders<Wo_EquipmentRunning>.Sort.Descending("createtime");
                var dModel = await _wo_equipmentrunningrepository.GetSingle(s => s.matterids.Contains(matterids) & s.dealtime < DateTime.Now & s.isdelete == 0, sort);

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

        #region 添加修改工单
        [AllowAnonymous]
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(string planid)
        {
            _logger.LogError("WoEquipmentRunningController/AddAsync  ");
            if (string.IsNullOrWhiteSpace(planid))
            {
                _logger.LogError("AddAsync Error  计划不能为空");
                return Error("计划不能为空");
            }
            var ret = false;
            var planmodel = await _wo_equipmentrunning_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_equipmentrunning_planrepository.UpdateOne(planmodel);
                    removeTask(planid);
                    _logger.LogError("AddAsync Error 计划已结束，计划名称：" + planmodel.planname);
                    return Error("计划已结束");
                }
                ret=await addwoAsync(planmodel);
            }
            if (ret)
            {
                _logger.LogError("WoEquipmentRunningController/AddAsync  添加成功");
                return Success("添加成功");
            }
            else
            {
                _logger.LogError("WoEquipmentRunningController/AddAsync  添加失败");
                return Error("添加失败");
            }
        }

        public async Task<bool> addwoAsync(Wo_EquipmentRunning_Plan planmodel)
        {
            _logger.LogError("WoEquipmentRunningController/addwoAsync Start  ");
            int res = 0; int count = 0;
            var hangfiremodel = await _hangfire_planrepository.GetSingle(planmodel.hangfireid);
            var model = new Wo_EquipmentRunning();
            #region 基本信息
            model.woname = planmodel.planname;
            model.wocontent = planmodel.plancontent;
            model.projectid = planmodel.projectid;
            model.matterids = planmodel.matterids;
            //model.systemid = planmodel.systemid;
            //model.equipmentid = planmodel.equipmentid;
            model.planid = planmodel.id;    //巡检计划id
            model.extensionlist = planmodel.extensionlist;    //默认值[]
            model.isreturnmsg = planmodel.isreturnmsg;

            model.isdelete = 0;
            model.checkpic = new List<FileBaseModel>();
            #endregion
            #region 获取上一次巡检信息
            var sort = Builders<Wo_EquipmentRunning>.Sort.Descending("createtime");
            var dModel = await _wo_equipmentrunningrepository.GetSingle(s => s.planid.Equals(planmodel.id) & s.isdelete == 0, sort);
            if (dModel != null)
            {
                model.lastchecktime = dModel.lastchecktime;
                model.lastcheckresultid = dModel.lastcheckresultid;
            }
            #endregion

            if (hangfiremodel != null)
            {
                foreach (var item in hangfiremodel.extensiontime)
                {
                    Thread.Sleep(500);
                    model.id = ObjectId.GenerateNewId().ToString();
                    model.wocode = UniqueData.Gener("", 2);
                    //model.wocode = DateTime.Now.ToString("yyMMddHHmmssffffff");
                    model.wodate = DateTime.Now.ToString("yyyy-MM-dd");
                    model.starttime = DateTime.Parse(DateTime.Now.AddDays(item.startdate - 1).ToString("yyyy-MM-dd") + " " + item.starttime.ToString("HH:mm"));
                    model.endtime = DateTime.Parse(DateTime.Now.AddDays(item.enddate - 1).ToString("yyyy-MM-dd") + " " + item.endtime.ToString("HH:mm"));
                    model.createtime = DateTime.Now;
                    //开始时间小于当前时间不创建工单
                    if (model.starttime < DateTime.Now)
                    { continue; }
                    if (await _wo_equipmentrunningrepository.Add(model))
                    {
                        AddItems(model.id, model.wocode, (int)EnumEquipmentRunningState.create, 0, 0, "", "", "创建工单", "");
                        res += 1;
                    }
                    count++;
                }
            }
            if (res == count && res > 0)
            {
                _logger.LogError("addwoAsync添加工单成功，工单名称：" + planmodel.planname + "，工单内容：" + planmodel.plancontent + ",添加了" + count + "条工单");
                return true;
            }
            else
            {
                _logger.LogError("addwoAsync添加工单失败，工单名称：" + planmodel.planname + "，工单内容：" + planmodel.plancontent + ",添加了" + count + "条工单");
                return false;
            }
        }

        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(WoEquipmentRunningInput input)
        {
            var planmodel = await _wo_equipmentrunningrepository.GetSingle(input.planid);
            if (planmodel != null)
            {
                var model = new Wo_EquipmentRunning();
                var ordercode = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                #region 基本信息
                model.woname = input.woname;
                model.wocontent = input.wocontent;
                model.projectid = input.projectid;
                model.matterids=input.matterids;
                //model.equipmentid = input.equipmentid;
                model.extensionlist = input.extensionlist;
                model.starttime = input.starttime;
                model.endtime = input.endtime;
                #endregion
                if (await _wo_equipmentrunningrepository.UpdateOne(model))
                    return Success("修改成功");
            }
            return Error("修改失败");
        }
        #endregion
        #region 添加修改工单重做
        ///// <summary>
        ///// 添加设备运行工单信息 - 不用
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //[HttpPost("add")]
        //public async Task<IActionResult> AddAsync(WoEquipmentRunningInput input)
        //{
        //    if (string.IsNullOrEmpty(input.projectid))
        //        return Error("项目名称不能为空");
        //    else
        //    {
        //        var pro = await _pro_project_infoRepository.GetSingle(input.projectid);
        //        if (pro != null)
        //        {
        //            if (pro.isend == 1)
        //            {
        //                return Error("暂停巡检工单");
        //            }
        //        }
        //    }
        //    //if (string.IsNullOrEmpty(input.sysnameid))
        //    //    return Error("系统名称不能为空");
        //    if (string.IsNullOrEmpty(input.equipmentid))
        //        return Error("设备名称不能为空");
        //    #region 获取上一次巡检信息
        //    var sort = Builders<Wo_EquipmentRunning>.Sort.Descending("createtime");
        //    var dModel = await _wo_equipmentrunningrepository.GetSingle(s => s.equipmentid.Equals(input.equipmentid) & s.isdelete == 0, sort);
        //    #endregion

        //    var model = new Wo_EquipmentRunning();
        //    //时间戳作为工单编号
        //    var ordercode = DateTime.Now.ToString("yyyyMMddHHmmssfff");
        //    #region 添加信息
        //    model.id = ObjectId.GenerateNewId().ToString();
        //    model.wocode = ordercode;
        //    model.projectid = input.projectid;
        //    //model.sysnameid = input.sysnameid;
        //    model.equipmentid = input.equipmentid;
        //    model.planid = input.planid;    //巡检计划id
        //    model.advancelong = input.advancelong;//提前显示时长
        //    if (dModel != null)
        //    {
        //        model.lastchecktime = dModel.lastchecktime;
        //        //model.thischeckime = dModel.thischeckime;
        //        model.lastcheckresultid = dModel.lastcheckresultid;
        //        model.abnormalcontent = dModel.abnormalcontent;
        //        model.expirytime = dModel.expirytime.AddDays(1);
        //    }
        //    else
        //    {
        //        model.expirytime = input.expirytime;//工单到期时间
        //    }
        //    model.advancetime = input.expirytime.AddMinutes(-input.advancelong);//提前显示时间
        //    model.checkpic = new List<FileBaseModel>();          //默认值[]
        //    model.extensionlist = new List<ExtensionModel>();    //默认值[]
        //    model.createtime = DateTime.Now;
        //    model.createby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
        //    #endregion
        //    bool b = await _wo_equipmentrunningrepository.Add(model);
        //    if (b)
        //    {
        //        return Success("添加成功");
        //    }
        //    return Error("添加失败");
        //}

        ///// <summary>
        ///// 修改设备运行工单信息 - 不用
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //[HttpPost("update")]
        //public async Task<IActionResult> UpdateAsync(WoEquipmentRunningInput input)
        //{
        //    if (string.IsNullOrEmpty(input.projectid))
        //        return Error("项目名称不能为空");
        //    else
        //    {
        //        var pro = await _pro_project_infoRepository.GetSingle(input.projectid);
        //        if (pro != null)
        //        {
        //            if (pro.isend == 1)
        //            {
        //                return Error("暂停巡检工单");
        //            }
        //        }
        //    }
        //    //if (string.IsNullOrEmpty(input.sysnameid))
        //    //    return Error("系统名称不能为空");
        //    if (string.IsNullOrEmpty(input.equipmentid))
        //        return Error("设备名称不能为空");
        //    var model = new Wo_EquipmentRunning();
        //    model = await _wo_equipmentrunningrepository.GetSingle(input.id);
        //    if (model == null)
        //        return Error("操作失败");
        //    #region 添加信息
        //    model.projectid = input.projectid;
        //    //model.sysnameid = input.sysnameid;
        //    model.equipmentid = input.equipmentid;
        //    model.lastchecktime = input.lastchecktime;
        //    //model.thischeckime = input.thischeckime;
        //    model.lastcheckresultid = input.lastcheckresultid;
        //    model.abnormalcontent = input.abnormalcontent;
        //    model.createtime = DateTime.Now;
        //    model.createby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
        //    #endregion
        //    bool b = await _wo_equipmentrunningrepository.UpdateOne(model);
        //    if (b)
        //        return Success("修改成功");
        //    return Error("修改失败");
        //}
        #endregion
        #region 处理信息
        #region 处理工单
        /// <summary>
        /// 处理设备运行工单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("deal")]
        public async Task<IActionResult> UpdateDealAsync(WoEquipmentRunningInput input)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            
            if (input.quipmenttype==0 && string.IsNullOrEmpty(input.checkcontent))
                return Error("异常说明不能为空");
            var model = new Wo_EquipmentRunning();
            model = await _wo_equipmentrunningrepository.GetSingle(input.id);
            if (model == null)
                return Error("操作失败");
            if (model.wostate == (int)EnumEquipmentRunningState.deal || model.wostate == (int)EnumEquipmentRunningState.hangup)
            {
                return Error("已经处理过了，不能再次处理");
            }
            #region 添加信息
            model.quipmenttype = input.quipmenttype;
            model.checkcontent = input.checkcontent;
            if (input.checkpic != null)
            {
                model.checkpic = input.checkpic;
            }
            else
            {
                model.checkpic = new List<FileBaseModel>();
            }
            if (input.extensionlist != null)
            {
                model.extensionlist = input.extensionlist;
            }
            else
            {
                model.extensionlist = new List<ExtensionFileModel>();
            }
            if (input.wostate == 3)
                model.wostate = (int)EnumEquipmentRunningState.deal;    //任务状态:0创建工单，1已转派，6挂起，9已完成;
            if (input.wostate == 6)
                model.wostate = (int)EnumEquipmentRunningState.hangup;
            model.dealtime = DateTime.Now;
            model.dealby = usercode;
            #endregion
            bool b = await _wo_equipmentrunningrepository.UpdateOne(model);
            if (b)
            {
                //添加工单轨迹 - 记录
                int islast = input.wostate == (int)EnumEquipmentRunningState.deal ? 1 : 0;    //是否最后一步 0否 1是
                AddItems(model.id, model.wocode, model.wostate, 0, islast, "", "", "处理工单，状态：" + (input.quipmenttype == 1 ? "正常" : "异常") + "，说明：" + input.checkcontent, usercode);
                return Success("处理成功");
            }
            return Error("处理失败");

        }
        #endregion
        #region 处理工单重做
        ///// <summary>
        ///// 处理设备运行工单
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //[HttpPost("deal")]
        //public async Task<IActionResult> UpdateDealAsync(WoEquipmentRunningInput input)
        //{
        //    string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

        //    //if (string.IsNullOrEmpty(input.checkby))
        //    //    return Error("巡检人不能为空");
        //    if (string.IsNullOrEmpty(input.checkcontent))
        //        return Error("异常说明不能为空");
        //    var model = new Wo_EquipmentRunning();
        //    model = await _wo_equipmentrunningrepository.GetSingle(input.id);
        //    if (model == null)
        //        return Error("操作失败");
        //    if (model.wostate == (int)EnumEquipmentRunningState.deal || model.wostate == (int)EnumEquipmentRunningState.hangup)
        //    {
        //        return Error("已经处理过了，不能再次处理");
        //    }
        //    #region 添加信息
        //    //model.thischeckime = input.thischeckime;  
        //    model.thischeckime = DateTime.Now;    //20180804 lihai 本次巡检时间 修改成处理时候添加当前时间
        //    //model.checkby = input.checkby;
        //    model.quipmenttype = input.quipmenttype;
        //    model.checkcontent = input.checkcontent;
        //    if (input.checkpic != null)
        //    {
        //        model.checkpic = input.checkpic;
        //    }
        //    else
        //    {
        //        model.checkpic = new List<FileBaseModel>();
        //    }
        //    if (input.extensionlist != null)
        //    {
        //        model.extensionlist = input.extensionlist;
        //    }
        //    else
        //    {
        //        model.extensionlist = new List<ExtensionModel>();
        //    }
        //    if (input.wostate == 3)
        //        model.wostate = (int)EnumEquipmentRunningState.deal;    //任务状态:0创建工单，1已转派，6挂起，9已完成;
        //    if (input.wostate == 6)
        //        model.wostate = (int)EnumEquipmentRunningState.hangup;
        //    if (input.wostate == 9)
        //        model.wostate = input.wostate;
        //    model.dealtime = DateTime.Now;
        //    model.dealby = usercode;
        //    #endregion
        //    bool b = await _wo_equipmentrunningrepository.UpdateOne(model);
        //    if (b)
        //    {
        //        //添加工单轨迹 - 记录
        //        int islast = input.wostate == 3 ? 1 : 0;    //是否最后一步 0否 1是
        //        AddItems(model.wocode, model.wostate, 0, islast, "", "", "处理工单，工单编号：" + model.wocode + "，说明：" + input.checkcontent, usercode);
        //        return Success("处理成功");
        //    }
        //    return Error("处理失败");

        //}
        #endregion

        /// <summary>
        /// 抢单
        /// </summary>
        /// <param name="wocode"></param>
        /// <param name="channel"></param>
        /// <returns></returns>
        [HttpPost("grab")]
        public async Task<IActionResult> UpdateGrabAsync(string id)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            #region 未处理工单超限
            int limitcount = _wo_repair_baseRepository.GetLimitCount(usercode);
            if (limitcount > 0)
            {
                return Error("你已经有" + limitcount + "个未处理工单，已超上限");
            }
            #endregion
            var model = await _wo_equipmentrunningrepository.GetSingle(id);
            #region 获取失败
            if (model == null)
                return Error("操作失败");
            #endregion
           
            model.checkby = usercode; //巡检人

            model.wostate= (int)EnumEquipmentRunningState.grab;
            bool b = await _wo_equipmentrunningrepository.UpdateOne(model);
            if (b)
            {
                int islast = 0;    //是否最后一步 0否 1是
                AddItems(model.id, model.wocode, model.wostate, 0, islast, usercode, "", usercode+"操作抢单", usercode);
                #region 标记消息提醒工单（消息提醒，App推送）
                //工单信息
                var listmap = await _wo_order_user_maprepository.Get(x => x.wocode == model.wocode && x.channelcode == 3 && x.readby == usercode);
                var modelmap = listmap.FirstOrDefault();
                if (modelmap != null)
                {
                    //删除工单关系表中对应工单
                    bool boo = await _wo_order_user_maprepository.Remove(modelmap.id);
                }
                #endregion
                return Success("抢单成功");
            }
            return Error("抢单失败");
        }

        /// <summary>
        /// 转派设备运行工单
        /// </summary>
        /// <param name="id"></param>
        /// <param name="touser"></param>
        /// <param name="des"></param>
        /// <param name="wostate"></param>
        /// <param name="ishasten">是否催办（0不催办1催办）</param>
        /// <returns></returns>
        [HttpPost("assign")]
        public async Task<IActionResult> UpdateAssignAsync(string id, string touser, string des, int wostate, int ishasten)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            if (string.IsNullOrEmpty(touser))
                return Error("转派的对象不能为空");
            #region 未处理工单超限
            int limitcount = _wo_repair_baseRepository.GetLimitCount(usercode);
            if (limitcount > 0)
            {
                return Error(touser + "已经有" + limitcount + "个未处理工单，已超上限");
            }
            #endregion
            var model = await _wo_equipmentrunningrepository.GetSingle(id);
            if (model == null)
                return Error("操作失败");
            model.checkby = touser; //巡检人
                                    //任务状态:0创建工单，1已转派，2挂起，9已完成;
            if (wostate == 1)
                model.wostate = (int)EnumEquipmentRunningState.assign;
            if (wostate == 3)
                model.wostate = (int)EnumEquipmentRunningState.deal;
            if (wostate == 6)
                model.wostate = (int)EnumEquipmentRunningState.hangup;
            bool b = await _wo_equipmentrunningrepository.UpdateOne(model);
            if (b)
            {
                int islast = wostate == (int)EnumEquipmentRunningState.deal ? 1 : 0;    //是否最后一步 0否 1是
                AddItems(model.id, model.wocode, model.wostate, ishasten, islast, touser, "", "转派工单至员工" + touser + "，说明：" + des, usercode);
                #region 标记消息提醒工单（消息提醒，App推送）
                //工单信息
                var listmap = await _wo_order_user_maprepository.Get(x => x.wocode == model.wocode && x.channelcode == 3 && x.readby == touser);
                var modelmap = listmap.FirstOrDefault();
                if (modelmap != null)
                {
                    //删除工单关系表中对应工单
                    bool boo = await _wo_order_user_maprepository.Remove(modelmap.id);
                }
                #endregion
                return Success("转派处理工单成功");
            }
            return Error("转派处理工单失败");

        }
        /// <summary>
        /// 批量转派工单
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="touser"></param>
        /// <param name="des"></param>
        /// <param name="wostate"></param>
        /// <param name="ishasten">是否催办（0不催办1催办）</param>
        /// <returns></returns>
        [HttpPost("assignmany")]
        public async Task<IActionResult> UpdateAssignManyAsync(string[] ids, string touser, string des, int wostate, int ishasten)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            if (string.IsNullOrEmpty(touser))
                return Error("转派的对象不能为空");
            int res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var model = await _wo_equipmentrunningrepository.GetSingle(item);
                    if (model != null)
                    {
                        model.checkby = touser; //巡检人
                                                //任务状态:0创建工单，1已转派，2挂起，9已完成;
                        if (wostate == 1)
                            model.wostate = (int)EnumEquipmentRunningState.assign;
                        if (wostate == 3)
                            model.wostate = (int)EnumEquipmentRunningState.deal;
                        if (wostate == 6)
                            model.wostate = (int)EnumEquipmentRunningState.hangup;
                        bool b = await _wo_equipmentrunningrepository.UpdateOne(model);
                        if (b)
                        {
                            int islast = wostate == 3 ? 1 : 0;    //是否最后一步 0否 1是
                            AddItems(model.id, model.wocode, model.wostate, ishasten, islast, touser, "", "转派工单至员工" + touser + "，说明：" + des, usercode);
                            #region 标记消息提醒工单（消息提醒，App推送）
                            //工单信息
                            var listmap = await _wo_order_user_maprepository.Get(x => x.wocode == model.wocode && x.channelcode == 3 && 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("转派处理工单失败");
            }
        }

        /// <summary>
        /// 删除设备运行工单
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> RemoveAsync(string[] ids)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                try
                {
                    foreach (var item in ids)
                    {
                        var ml = await _wo_equipmentrunningrepository.GetSingle(item);
                        if (ml != null)
                        {
                            ml.isdelete = -1;
                            ml.deleteby = usercode;
                            ml.deletetime = DateTime.Now;
                            if (await _wo_equipmentrunningrepository.UpdateOne(ml))
                            {
                                res += 1;
                                var clmodel = new Wo_TimeOut();
                                clmodel = await _wo_timeoutrepository.GetSingle(c => c.woid == ml.id && c.wotype == (int)EnumWoType.inspection);
                                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>
        /// <param name="wocode">工单编号</param>
        /// <param name="wostate">工单状态</param>
        /// <param name="ishasten">是否催办（0不催办1催办）</param>
        /// <param name="islast">是否最后一步 0否 1是</param>
        /// <param name="touser">指派下一步人员</param>
        /// <param name="todept">指派下一步部门</param>
        /// <param name="detail">处理说明</param>
        /// <param name="usercode">当前操作人</param>
        private async void AddItems(string woid,string wocode, int wostate, int ishasten, int islast, string touser, string todept, string detail,string usercode)
        {
            try
            {
                #region 更新流程
                if (wostate > 0)
                {
                    var list = await _wo_equipmentrunning_itemsrepository.Get(Builders<Wo_EquipmentRunning_Items>.Filter.Eq("woid", woid), null, Builders<Wo_EquipmentRunning_Items>.Sort.Descending("createtime"));
                    if (list.Count() > 0)
                    {
                        var itemmodel = list.FirstOrDefault();
                        itemmodel.sureuser = usercode;
                        itemmodel.suretime = DateTime.Now;
                        itemmodel.itemstate = 1;
                        itemmodel.islast = islast;
                        await _wo_equipmentrunning_itemsrepository.UpdateOne(itemmodel);
                    }
                }
                #endregion
                #region 添加下一步明细
                var model = new Wo_EquipmentRunning_Items();
                model.woid = woid;
                model.wocode = wocode;
                model.wostate = wostate;
                model.itemstate = 0;
                model.isdelete = 0;
                model.createby = usercode;
                model.createtime = DateTime.Now;
                model.detail = detail;
                model.islast = islast;
                if (wostate < (int)EnumEquipmentRunningState.deal)
                {
                    model.ishasten = ishasten;
                    #region 创建、转派、抢单
                    model.touser = touser;
                    model.todept = todept;
                    #endregion
                }
                else if (wostate == (int)EnumEquipmentRunningState.deal)
                {
                    #region 结单
                    model.dealtime = DateTime.Now;
                    model.dealuser = usercode;
                    #endregion
                }
                await _wo_equipmentrunning_itemsrepository.Add(model);
                #endregion
            }
            catch (Exception ex)
            {
                _logger.LogDebug("工单日志记录异常", ex);
            }
        }

        #endregion

        #region 删除计划
        private void removeTask(string id)
        {
            _hangfireService.RemovePlan(id);
        }
        #endregion

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