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 Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;
using MongoDB.Bson;
using Api.SignToken;
using MadRunFabric.Model.HangfireApi.Model;
using MadRunFabric.Model.EquipmentApi.Model;
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 WoMaintainPlanController : BaseController
    {
        private readonly ILogger<WoMaintainPlanController> _logger;
        private readonly IConfiguration _configuration;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        private readonly IWo_Maintain_BaseRepository _wo_maintain_baseRepository;
        private readonly IWo_Maintain_PlanRepository _wo_maintain_planRepository;
        private readonly IEqp_Equipment_InfoRepository _eqp_equipment_infoRepository;
        private readonly IHangfire_PlanRepository _hangfire_planrepository;
        private readonly IHangfireService _hangfireService;
        private readonly IPro_Project_InfoRepository _pro_project_infoRepository;
        private readonly IWo_Maintain_ItemsRepository _wo_maintain_itemsRepository;
        private readonly IWo_MattersRepository _wo_mattersRepository;
        private readonly ISignTokenService _signTokenService;
        public WoMaintainPlanController(ILogger<WoMaintainPlanController> logger,
            IConfiguration configuration,
            ISys_User_AccountRepository sys_user_accountRepository,
            IWo_Maintain_BaseRepository wo_maintain_baseRepository, IWo_Maintain_PlanRepository wo_maintain_planRepository,
            IHangfire_PlanRepository hangfire_planrepository,IHangfireService hangfireService, ISignTokenService signTokenService,
            IEqp_Equipment_InfoRepository eqp_equipment_infoRepository, IPro_Project_InfoRepository pro_project_infoRepository,
            IWo_Maintain_ItemsRepository wo_maintain_itemsRepository, IWo_MattersRepository wo_mattersRepository)
        {
            _logger = logger;
            _configuration = configuration;
            _sys_user_accountRepository = sys_user_accountRepository;
            _wo_maintain_baseRepository = wo_maintain_baseRepository;
            _wo_maintain_planRepository = wo_maintain_planRepository;
            _hangfire_planrepository = hangfire_planrepository;
            _hangfireService = hangfireService;
            _eqp_equipment_infoRepository = eqp_equipment_infoRepository;
            _pro_project_infoRepository = pro_project_infoRepository;
            _wo_maintain_itemsRepository = wo_maintain_itemsRepository;
            _wo_mattersRepository = wo_mattersRepository;
            _signTokenService = signTokenService;
        }

        /// <summary>
        /// 获取保养计划列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        //[Authorize]
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPageAsync(string keyword, string projectid, string stime, string etime, 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_planRepository.GetListsByPage(keyword, projectid, stime, etime,nowusercode,userinfo, pageindex, pagesize, out recordCount);
            var list = result.ToList();
            foreach (var item in list)
            {
                if (!string.IsNullOrWhiteSpace(item.hangfireid))
                {
                    var hfmo = await _hangfire_planrepository.GetSingle(item.hangfireid);
                    if (hfmo != null)
                    {
                        item.plancycle = hfmo.plancycle;
                        item.planinterval = hfmo.planinterval;
                        item.plantimes = hfmo.plantimes;
                        item.extensiontime = hfmo.extensiontime;
                    }
                }
                #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] = "";
                //    }
                //    item.equipmentname = equname;
                //}
                #endregion
            }
            var obj = new
            {
                rows = list,
                total = recordCount,
            };
            return Success("获取成功", obj);
        }

        //[Authorize]
        [HttpGet("getlist")]
        public async Task<IActionResult> GetListsAsync(string key, string stime, string etime)
        {
            try
            {
                //排序字段
                var sort = Builders<Wo_Maintain_Plan>.Sort.Descending("createtime");

                //根据条件查询集合
                var flist = new List<FilterDefinition<Wo_Maintain_Plan>>();
                flist.Add(Builders<Wo_Maintain_Plan>.Filter.Eq("isdelete", false));
                if (!string.IsNullOrWhiteSpace(key))
                    flist.Add(Builders<Wo_Maintain_Plan>.Filter.Where(s => s.planname.Contains(key)));
                if (!string.IsNullOrWhiteSpace(stime))
                {
                    DateTime dt2 = new DateTime();
                    if (DateTime.TryParse(stime.Trim() + " 00:00:00", out dt2))
                        flist.Add(Builders<Wo_Maintain_Plan>.Filter.Gt("createtime", stime));
                }
                if (!string.IsNullOrWhiteSpace(etime))
                {
                    DateTime dt2 = new DateTime();
                    if (DateTime.TryParse(etime.Trim() + " 23:59:59", out dt2))
                        flist.Add(Builders<Wo_Maintain_Plan>.Filter.Lt("createtime", etime));
                }
                var filter = Builders<Wo_Maintain_Plan>.Filter.And(flist);
                var vlist = await _wo_maintain_planRepository.Get(filter,null, sort);
                var obj = new
                {
                    list = vlist
                };
                return Success("根据条件获取保养计划数据成功", obj);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据条件获取保养计划数据异常");
                return Error("根据条件获取保养计划数据异常");
            }
        }

        /// <summary>
        /// 获取实体
        /// </summary>
        //[Authorize]
        [HttpGet("getsingle")]
        public async Task<IActionResult> GetSingleAsync(string id)
        {
            try
            {
                if (string.IsNullOrEmpty(id))
                    return Error("参数错误");
                var model = _wo_maintain_planRepository.GetDetails(id);
                if (model != null)
                {
                    if (!string.IsNullOrWhiteSpace(model.hangfireid))
                    {
                        var hfmo = await _hangfire_planrepository.GetSingle(model.hangfireid);
                        if (hfmo != null)
                        {
                            model.plancycle = hfmo.plancycle;
                            model.planinterval = hfmo.planinterval;
                            model.plantimes = hfmo.plantimes;
                            model.extensiontime = hfmo.extensiontime;
                        }
                    }
                    #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
                    return Success("获取成功！", model);
                }
                return Error("获取失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "设备运行工单异常");
                return Error("获取失败");
            }
        }

        /// <summary>
        /// 添加保养计划
        /// </summary>
        //[Authorize]
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(WoMaintainPlanInput input)
        {
            if (string.IsNullOrWhiteSpace(input.projectid))
            {
                return Error("请选择项目");
            }
            else
            {
                var pro = await _pro_project_infoRepository.GetSingle(input.projectid);
                if (pro != null)
                {
                    if (pro.isend == 1)
                    {
                        return Error("暂停保养计划");
                    }
                }
            }
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            Wo_Maintain_Plan clmodel = new Wo_Maintain_Plan();
            var b = false;
            #region 赋值
            clmodel.id = ObjectId.GenerateNewId().ToString();
            clmodel.projectid = input.projectid;//项目名称
            clmodel.matterids = input.matterids;
            //clmodel.systemid = input.systemid;//系统名称
            //clmodel.equipmentid = input.equipmentid;//设备名称
            clmodel.planname = input.planname;//保养计划名称
            clmodel.plancontent = input.plancontent;//保养计划内容
            clmodel.planclaim = input.planclaim;//保养计划要求
            clmodel.planstate = input.planstate;
            clmodel.startdate = input.startdate;
            clmodel.enddate = input.enddate;
            if (input.extensionlist != null)
            {
                clmodel.extensionlist = input.extensionlist;
            }
            else
            {
                clmodel.extensionlist = new List<ExtensionFileModel>();
            }
            if (input.maintaintype != null)
            {
                clmodel.maintaintype = input.maintaintype;
            }
            else
            {
                clmodel.maintaintype = new List<string>();
            }
            if (input.maintainfile != null)
            {
                clmodel.maintainfile = input.maintainfile;
            }
            else
            {
                clmodel.maintainfile = new List<FileBaseModel>();
            }
            clmodel.createby = usercode;
            clmodel.createtime = DateTime.Now;
            clmodel.isdelete = false;
            #endregion


            b = await _wo_maintain_planRepository.Add(clmodel);
            if (b)
            {
                #region 添加设备保养工单
                    #region 添加定时计划
                    var planid = await addplan(input, "");
                    clmodel.hangfireid = planid;
                    await _wo_maintain_planRepository.UpdateOne(clmodel);
                    //添加定时计划
                    SetTask(clmodel.id, input.plancycle, input.planinterval, input.plantimes);
                #endregion
                if (DateTime.Now.Date == input.startdate.Date)
                {
                    await addwoAsync(clmodel);
                }
                #endregion                    
                return Success("保养计划保存成功");
            }
            return Error("保养计划保存失败");
        }

        /// <summary>
        /// 修改保养计划
        /// </summary>
        //[Authorize]
        [HttpPost("update")]
        public async Task<IActionResult> EditAsync(WoMaintainPlanInput input)
        {
            if (string.IsNullOrWhiteSpace(input.projectid))
            {
                return Error("请选择项目");
            }
            else
            {
                var pro = await _pro_project_infoRepository.GetSingle(input.projectid);
                if (pro != null)
                {
                    if (pro.isend == 1)
                    {
                        return Error("暂停保养计划");
                    }
                }
            }
            var res = false;
            var clmodel = await _wo_maintain_planRepository.GetSingle(input.id);
            if (clmodel == null)
                return Error("操作失败");
            #region 赋值
            clmodel.projectid = input.projectid;//项目名称
            clmodel.matterids = input.matterids;
            //clmodel.systemid = input.systemid;//系统名称
            //clmodel.equipmentid = input.equipmentid;//设备名称
            clmodel.planname = input.planname;//保养计划名称
            clmodel.plancontent = input.plancontent;//保养计划内容
            clmodel.planclaim = input.planclaim;//保养计划要求
            clmodel.planstate = input.planstate;
            clmodel.startdate = input.startdate;
            clmodel.enddate = input.enddate;
            if (input.extensionlist != null)
            {
                clmodel.extensionlist = input.extensionlist;
            }
            else
            {
                clmodel.extensionlist = new List<ExtensionFileModel>();
            }
            if (input.maintaintype != null)
            {
                clmodel.maintaintype = input.maintaintype;
            }
            else
            {
                clmodel.maintaintype = new List<string>();
            }
            if (input.maintainfile != null)
            {
                clmodel.maintainfile = input.maintainfile;
            }
            else
            {
                clmodel.maintainfile = new List<FileBaseModel>();
            }
            #endregion
            res = _wo_maintain_planRepository.UpdateOne(clmodel).Result;
            if (res)
            {
                await addplan(input, clmodel.hangfireid);
                SetTask(clmodel.id, input.plancycle, input.planinterval, input.plantimes);
            }
            if (res)
                return Success("保养计划保存成功");
            else
            {
                return Error("保养计划保存失败");
            }
        }

        [Authorize]
        [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_maintain_planRepository.GetSingle(item);
                        ml.isdelete = true;
                        ml.deleteby = usercode;
                        ml.deletetime = DateTime.Now;
                        if (await _wo_maintain_planRepository.UpdateOne(ml))
                        {
                            #region 查询此计划是否有未执行的工单，若有一并删除
                            var rl = await _wo_maintain_baseRepository.Get(r => r.planid.Equals(item) && r.wostate == (int)EnumEquipmentRunningState.create);
                            if (rl.Count() > 0)
                            {
                                foreach (var itemrun in rl)
                                {
                                    itemrun.isdelete = true;
                                    itemrun.deleteby = usercode;
                                    itemrun.deletetime = DateTime.Now;
                                    await _wo_maintain_baseRepository.UpdateOne(itemrun);
                                }
                            }
                            #endregion
                            removeTask(ml.id);
                            res += 1;
                        }
                    }
                    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="ids"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost("start")]
        public async Task<IActionResult> StartAsync(string[] ids)
        {
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                try
                {
                    foreach (var item in ids)
                    {
                        var ml = await _wo_maintain_planRepository.GetSingle(item);
                        ml.planstate = 0;
                        if (await _wo_maintain_planRepository.UpdateOne(ml))
                        {
                            var hl = await _hangfire_planrepository.GetSingle(ml.hangfireid);

                            SetTask(item, hl.plancycle, hl.planinterval, hl.plantimes);
                            res += 1;
                        }
                    }
                    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="ids"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost("stop")]
        public async Task<IActionResult> StopAsync(string[] ids)
        {
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                try
                {
                    foreach (var item in ids)
                    {
                        var ml = await _wo_maintain_planRepository.GetSingle(item);
                        ml.planstate = 1;
                        if (await _wo_maintain_planRepository.UpdateOne(ml))
                        {
                            removeTask(ml.id);
                            res += 1;
                        }
                    }
                    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("请选择要操作的记录");
        }

        #region 保存计划任务
        private async Task<string> addplan(WoMaintainPlanInput input, string planid)
        {
            var model = new HangfirePlan();
            if (!string.IsNullOrWhiteSpace(planid))
            {
                model = await _hangfire_planrepository.GetSingle(planid);
            }
            else
            {
                model.id = ObjectId.GenerateNewId().ToString();
                model.wotype = (int)EnumWoType.maintain;

                model.createby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                model.createtime = DateTime.Now;
                model.isdelete = 0;
            }
            model.plantype = (int)enummainplantype.timing;
            model.plancycle = input.plancycle;
            model.plantimes = input.plantimes;
            model.planinterval = input.planinterval;
            model.planstate = input.planstate;
            model.extensiontime = input.extensiontime;
            var b = false;
            if (string.IsNullOrWhiteSpace(planid))
                b = await _hangfire_planrepository.Add(model);
            else
                b = await _hangfire_planrepository.UpdateOne(model);

            if (b)
                return model.id;
            else
                return "";
        }
        #endregion

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

        #region 设置定时任务 无法调用
        private void SetTask(string planid, int plancycle, int planinterval, int plantimes)
        {
            _logger.LogError("WoMaintainPlanController/SetTask start");
            _hangfireService.AddWoMaintainBase(planid, plancycle, planinterval, plantimes);
        }
        #endregion

        #region 添加工单
        public async Task<bool> addwoAsync(Wo_Maintain_Plan planmodel)
        {
            int res = 0; int count = 0;
            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;

            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);
                    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 (clmodel.starttime.Month < DateTime.Now.Month)
                    { continue; }
                    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 true;
            }
            else
            {
                _logger.LogError("即时添加工单失败，工单名称：" + planmodel.planname + "，工单内容：" + planmodel.plancontent + ",添加了" + count + "条工单");
                return false;
            }
        }
        /// <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
    }
}