using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MadRunFabric.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
using MessageApi.IRepositories;
using MadRunFabric.Common.Enums;
using MadRunFabric.Model;
using System.Security.Claims;
using Microsoft.Extensions.Caching.Distributed;
using MadRunFabric.Model.MessageApi;
using MessageApi.Model;
using Microsoft.Extensions.Configuration;

namespace MessageApi.Controllers
{
    /// <summary>
    /// 消息通知 - 工单
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class MessageController : BaseController
    {
        private readonly ILogger<MessageController> _logger;
        private readonly IDistributedCache _cache;
        private readonly IWo_Repair_BaseRepository _wo_repair_baseRepository;
        private readonly IWo_Maintain_BaseRepository _wo_maintain_baserepository;
        private readonly IWo_Maintain_PlanRepository _wo_maintain_planrepository;
        private readonly IWo_EquipmentRunningRepository _wo_equipmentrunningrepository;
        private readonly IEqp_Equipment_InfoRepository _eqp_equipment_inforepository;
        private readonly IWo_Order_User_MapRepository _wo_order_user_maprepository;
        private readonly IWo_TimeOutRepository _wo_timeoutrepository;
        private readonly ISys_Role_InfoRepository _sys_roleinfoRepository;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        private readonly IDistri_WorkorderRepository _distri_workorderrepository;
        private readonly ISys_ClassGroupRepository _sys_classgrouprepository;
        private readonly IDistri_Workorder_PlanTaskRepository _distri_workorder_plantaskrepository;
        private readonly ISys_ClassGroup_User_MapRepository _sys_classgroup_user_maprepository;
        private readonly IConfiguration _configuration;
        private readonly IWo_MattersRepository _wo_mattersRepository;
        private readonly IusercoldandclintidRepository _usercoldandclintidRepository;
        public MessageController(
            ILogger<MessageController> logger,
            IDistributedCache cache,
            IWo_Repair_BaseRepository wo_repair_baseRepository,
            IWo_Maintain_BaseRepository wo_maintain_baserepository,
            IWo_Maintain_PlanRepository wo_maintain_planrepository,
            IWo_EquipmentRunningRepository wo_equipmentrunningrepository,
            IEqp_Equipment_InfoRepository eqp_equipment_inforepository,
            IWo_Order_User_MapRepository wo_order_user_maprepository,
            IWo_TimeOutRepository wo_timeoutrepository,
            ISys_Role_InfoRepository sys_roleinfoRepository,
            ISys_User_AccountRepository sys_user_accountRepository,
            IDistri_WorkorderRepository distri_workorderrepository,
            ISys_ClassGroupRepository sys_classgrouprepository,
            IDistri_Workorder_PlanTaskRepository distri_workorder_plantaskrepository,
            ISys_ClassGroup_User_MapRepository sys_classgroup_user_maprepository,
            IConfiguration configuration, IWo_MattersRepository wo_mattersRepository,
            IusercoldandclintidRepository usercoldandclintidRepository
            )
        {
            _logger = logger;
            _cache = cache;
            _wo_repair_baseRepository = wo_repair_baseRepository;
            _wo_maintain_baserepository = wo_maintain_baserepository;
            _wo_maintain_planrepository = wo_maintain_planrepository;
            _wo_equipmentrunningrepository = wo_equipmentrunningrepository;
            _eqp_equipment_inforepository = eqp_equipment_inforepository;
            _wo_order_user_maprepository = wo_order_user_maprepository;
            _wo_timeoutrepository = wo_timeoutrepository;
            _sys_roleinfoRepository = sys_roleinfoRepository;
            _sys_user_accountRepository = sys_user_accountRepository;
            _distri_workorderrepository = distri_workorderrepository;
            _sys_classgrouprepository = sys_classgrouprepository;
            _distri_workorder_plantaskrepository = distri_workorder_plantaskrepository;
            _sys_classgroup_user_maprepository = sys_classgroup_user_maprepository;
            _configuration = configuration;
            _wo_mattersRepository = wo_mattersRepository;
            _usercoldandclintidRepository = usercoldandclintidRepository;
        }

        /// <summary>
        /// 保存App客户端ClientId值
        /// </summary>
        /// <returns></returns>
        [HttpPost("putpushclientinfo")]
        public async Task<IActionResult> PutAppClientIdAsync(string clientid, int apptype = 1)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            #region 丢弃不用
            //var list = new List<AppClientListDto>();
            ////获取角色code: 运维员工 YWYG 、运维主管 YWZG 、运营副经理 YWFJL 、运营经理 YWJL 、运营总监 YWZJ 、运营副总 YWFZ 、运营总经理 YWZJL
            ////配送：电梯岗 SSY_DTG 、配送岗	 SSY_PSG 、配送主管 SSY_ZG
            //string rolecode = "";
            //var modelUser = await _sys_user_accountRepository.GetSingle(x => x.usercode == usercode);
            //if (modelUser != null)
            //{
            //    var roleinfo = await _sys_roleinfoRepository.GetSingle(x => x.id == modelUser.role_id);
            //    rolecode = roleinfo.role_code;
            //}
            ////获取redis缓存
            //var clientidStr = await _cache.GetStringAsync("clientidlist");
            //if (!string.IsNullOrEmpty(clientidStr) && clientidStr != "null")
            //    list = clientidStr.ToList<AppClientListDto>();

            //var rolecodeStr = "YWYG,YWZG,YWFJL,YWJL,YWZJ,YWFZ,YWZJL,SSY_DTG,SSY_PSG,SSY_ZG";
            //if (rolecodeStr.Contains(rolecode))
            //{
            //    if (!string.IsNullOrEmpty(clientid))
            //    {
            //        var count = 0;

            //        #region 去重 - 保证只有一个坐席账号，且只往一个登录账号的手机上推送
            //        var lists = list.Where(x => x.usercode == usercode).ToList();
            //        if (lists != null) count = lists.Count();
            //        if (count > 0)
            //        {
            //            foreach (var item in lists)
            //            {
            //                list.Remove(item);
            //            }
            //        }
            //        //存入redis缓存
            //        list.Add(new AppClientListDto
            //        {
            //            apptype = apptype,
            //            clientid = clientid,
            //            usercode = usercode
            //        });
            //        await _cache.SetStringAsync($"clientidlist", list.ToJson());
            //        #endregion

            //        return Success("保存ClientId成功");
            //    }
            //    return Success("没有获取到该设备clientid");
            //} 
            #endregion
           // var usercode = "888888";
            ///判断数据库中有没有存这条记录 
            var isclintid = await _usercoldandclintidRepository.GetSingle(p=>p.usercode==usercode);
            if (isclintid == null)
            {
                MadRunFabric.Model.EquipmentApi.Model.usercoldandclintid userclint = new MadRunFabric.Model.EquipmentApi.Model.usercoldandclintid();
                userclint.usercode = usercode;
                userclint.clintid = clientid;
                userclint.apptype = apptype;
                var a = _usercoldandclintidRepository.AddRetID(userclint);
                if (a.Result != null || a.Result != "")
                {
                    return Success("成功");
                }
                else
                {
                    return Error("失败");
                }
            }
            else
            {
                isclintid.clintid = clientid;
                var a = _usercoldandclintidRepository.UpdateOne(isclintid);
                if (a.Result)
                {
                    return Success("成功");
                }
                else
                {
                    return Error("失败");
                }
            }
        }

        /// <summary>
        /// 获取App客户端ClientId列表
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("getclientidlist")]
        public async Task<IActionResult> GetAppClientIdlistAsync()
        {
            var list = new List<AppClientListDto>();
            ////获取redis缓存
            //var clientidStr = await _cache.GetStringAsync("clientidlist");
            //if (!string.IsNullOrEmpty(clientidStr) && clientidStr != "null")
            //    list = clientidStr.ToList<AppClientListDto>();
            return Success("获取客户端ClientId列表", list);
        }

        /// <summary>
        /// 记录已推送信息
        /// </summary>
        /// <param name="wocode"></param>
        /// <param name="channelcode">//工单类型（枚举EnumOrderState） 维修工单 = 1, 保养工单 = 2, 运行工单 = 3, 超时工单 = 4, 配送工单 = 5, 计划工单 = 6</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("addappmessage")]
        public async Task<IActionResult> addAppMessageAsync(string woid, string wocode, int wostate, string usercode, int channelcode = 0)
        {
            if (!string.IsNullOrEmpty(wocode))
            {
                #region 标记消息提醒工单（消息提醒，App推送）
                if (channelcode > 0)
                {
                    #region 查询 4个表 by channelcode
                    var content = string.Empty;
                    if (channelcode == 1)
                    {
                        //维修工单 - 未处理完成
                        var listrepair_base = await _wo_repair_baseRepository.Get(x => x.wostate < 3 && x.isdelete == 0);
                        var model_repair_base = listrepair_base.FirstOrDefault(x => x.wocode == wocode && x.id == woid);
                        if (model_repair_base != null)
                            content = "故障说明:" + model_repair_base.faultdescripe;
                    }
                    if (channelcode == 2)
                    {
                        //保养工单 - 未处理完成
                        var listmaintain_base = await _wo_maintain_baserepository.Get(x => x.wostate < 3 && x.isdelete == false);
                        var model_maintain_base = listmaintain_base.FirstOrDefault(x => x.wocode == wocode && x.id == woid);
                        if (model_maintain_base != null)
                            content = model_maintain_base.woname + (string.IsNullOrEmpty(model_maintain_base.maintaincontent) ? "" : ",保养内容:" + model_maintain_base.maintaincontent);
                    }
                    if (channelcode == 3)
                    {
                        //设备巡检工单 - 未处理完成
                        var listequipmentrunning = await _wo_equipmentrunningrepository.Get(x => x.wostate <= 3 && x.isdelete == 0);
                        var model_equipmentrunning = listequipmentrunning.FirstOrDefault(x => x.wocode == wocode && x.id == woid);
                        if (model_equipmentrunning != null)
                            content = model_equipmentrunning.woname + (string.IsNullOrEmpty(model_equipmentrunning.wocontent) ? "" : ",工单内容:" + model_equipmentrunning.wocontent) + (string.IsNullOrEmpty(model_equipmentrunning.checkcontent) ? "" : ",异常说明:" + model_equipmentrunning.checkcontent);
                    }
                    if (channelcode == 4)
                    {
                        //超时工单 - 所有
                        var listetimeout = await _wo_timeoutrepository.Get(x => x.isdelete == false && x.istimeout == 1);
                        var model_etimeout = listetimeout.FirstOrDefault(x => x.wocode == wocode && x.id == woid);
                        if (model_etimeout != null)
                            content = "超时原因:" + model_etimeout.timeoutreason;  //超时原因
                    }
                    if (channelcode == 5)
                    {
                        //配送工单 - 所有
                        var listdistri = await _distri_workorderrepository.Get(x => x.isdelete == 0 && x.wostate == (int)EnumDistributionState.create);
                        var model_distri = listdistri.FirstOrDefault(x => x.wocode == wocode && x.id == woid);
                        if (model_distri != null)
                        {
                            string goodsDetail = (model_distri.goodslist != null && model_distri.goodslist.Count > 0) ? ",配送物品:" + model_distri.goodslist.Select(x => x.goodsname).ToJson() : "";
                            content = "配送内容:" + model_distri.detail + goodsDetail;  //配送内容
                        }
                    }
                    if (channelcode == 6)
                    {
                        //超时工单 - 所有
                        var listdistri = await _distri_workorder_plantaskrepository.Get(x => x.isdelete == 0 && x.planwostate == (int)EnumDistriWorkOrderPlanWOstate.create);
                        var model_distri = listdistri.FirstOrDefault(x => x.wocode == wocode && x.id == woid);
                        if (model_distri != null)
                        {
                            string goodsDetail = (model_distri.goodslist != null && model_distri.goodslist.Count > 0) ? ",配送计划工单物品:" + model_distri.goodslist.Select(x => x.goodsname).ToJson() : "";
                            content = "配送计划工单内容:" + model_distri.content + goodsDetail;  //配送内容
                        }
                    }
                    #endregion

                    //维修工单号
                    var listmap = await _wo_order_user_maprepository.Get(x => x.wocode == wocode && x.wostate.Equals(wostate) && x.woid == woid && x.channelcode == channelcode && x.readby == usercode);
                    var modelmap = listmap.FirstOrDefault();
                    if (modelmap == null)
                    {
                        //添加是否已读关系表
                        modelmap = new Wo_Order_User_Map();
                        modelmap.woid = woid;
                        modelmap.wocode = wocode;
                        modelmap.wostate = wostate;
                        modelmap.readby = usercode;
                        modelmap.channelcode = channelcode;   //工单类型（枚举EnumOrderState） 维修工单 = 1, 保养工单 = 2, 运行工单 = 3, 超时工单 = 4
                        modelmap.ispush = 1;
                        modelmap.isread = 0;
                        modelmap.readtime = DateTime.Now;
                        modelmap.note = content;
                        bool b = await _wo_order_user_maprepository.Add(modelmap);
                    }
                    else
                    {
                        if (modelmap.ispush != 1)
                        {
                            modelmap.ispush = 1;
                            modelmap.note = content;
                            bool b = await _wo_order_user_maprepository.UpdateOne(modelmap);
                        }
                    }
                    return Success("推送记录成功");
                }
                #endregion
            }
            return Success("参数错误");
        }

        /// <summary>
        /// Push 消息通知 - 设备维修（报修工单）
        /// 维修工单/保养工单/巡检工单/超时工单 
        /// </summary>
        /// <param name="messagetype">消息类型 (1消息通知信息，2推送信息)</param>
        /// <returns></returns>
        [HttpGet("getmessagelists")]
        [AllowAnonymous]
        public async Task<IActionResult> GetMessagesLists(string usercode)
        {
            #region 不同地方
            //int messagetype = 2;    //推送
            //运维员工YWYG，运维主管YWZG
            string rolecode = "";
            string projectlist = "";
            //获取角色code，运维员工维护项目id
            var modelUser = await _sys_user_accountRepository.GetSingle(x => x.usercode == usercode);
            if (modelUser != null)
            {
                var roleinfo = await _sys_roleinfoRepository.GetSingle(x => x.id == modelUser.role_id);
                rolecode = roleinfo.role_code;
                projectlist = string.Join(",", modelUser.projectlist);
            }
            //工单用户查看关系表 - 已查看订单
            var listmap = await _wo_order_user_maprepository.Get(x => x.readby.Equals(usercode));    // && x.isread == 1
            listmap = listmap.Where(x => x.ispush == 1);
            #endregion

            //维修工单 - 未处理完成
            var listrepair_base = await _wo_repair_baseRepository.Get(x => x.wostate < 3 && x.isdelete == 0);
            //保养工单 - 未处理完成
            var listmaintain_base = await _wo_maintain_baserepository.Get(x => x.wostate < 3 && x.isdelete == false);
            //设备巡检工单 - 未处理完成
            var listequipmentrunning = await _wo_equipmentrunningrepository.Get(x => x.wostate <= 3 && x.isdelete == 0);
            //超时工单 - 所有
            var listetimeout = await _wo_timeoutrepository.Get(x=>x.isdelete == false && x.istimeout == 1);
            //配送工单 - 新工单，派单(派单/强制派单)
            var listdistri = await _distri_workorderrepository.Get(x => x.wostate <= (int)EnumDistributionState.assign && x.isdelete == 0 && x.totype != (int)EnumDistributionTotype.robbery); //&& (x.totype == (int)EnumDistributionTotype.send || x.totype == (int)EnumDistributionTotype.assign)
            //班次
            var query_classgroup = await _sys_classgrouprepository.Get(x => x.isdelete == 0);
            //排班
            var query_usermap = await _sys_classgroup_user_maprepository.Get(x => x.isdelete == 0 && x.isstatus == 1);//配送工单 - 新工单，派单(派单/强制派单)
            //计划工单
            var listwotask = await _distri_workorder_plantaskrepository.Get(x => x.isdelete == 0 && x.planwostate != (int)EnumDistriWorkOrderPlanWOstate.start);

            //设备信息
            var listequipment_info = await _eqp_equipment_inforepository.Get(x => x.isdelete == 0);            
            //检查事项
            var listmatter = await _wo_mattersRepository.Get(x => x.isdelete == false);
            var list = new List<MessageListDto>();

            #region 条件判断 - 工单消息提醒和推送流程
            //1、运维员工 YWYG < 2、运维主管 YWZG < 3、运营副经理 YWFJL < 4、运营经理 YWJL < 5、运营总监 YWZJ < 6、运营副总 YWFZ < 7、运营总经理 YWZJL
            //说明工单（延迟时间配置DelayPushTime）：
            //   1、新单未抢单 和 未转派 运维员工；（例如9:00）
            //   2、超过 1 * 几分钟 无人抢单行为推送给 运维主管；（例如9:05）
            //   3、超过 3 * 几分钟 无派单行为推送给 运营副经理；（例如9:15）
            //   4、超过 4 * 几分钟 无管理行为推送给 运营经理和运营总监；（例如9:20）
            //   5、超过 6 * 几分钟 无管理行为推送给 运营副总和运营总经理；（例如9:30）
            int timespan = 0;
            int.TryParse(_configuration["PushMessage:DelayPushTime"], out timespan);
            DateTime nowTime = DateTime.Now.ToLocalTime();            

            listrepair_base = listrepair_base.Where(x => projectlist.Contains(x.projectid));
            listmaintain_base = listmaintain_base.Where(x =>projectlist.Contains(x.projectid));
            listequipmentrunning = listequipmentrunning.Where(x => projectlist.Contains(x.projectid));
            ////listetimeout = listetimeout.Where(x => projectlist.Contains(x.projectid));
            listdistri = listdistri.Where(x => projectlist.Contains(x.projectid));

            #region 配送工单 参与 排班条件
            //随机工单
            DateTime dtnow = DateTime.Now;
            string nowDay = dtnow.ToString("yyyy-MM-dd");
            var listClassUser = query_usermap.Where(x => x.date == nowDay).ToList();     //.Where(x=>x.date == nowDay)
            //var query_result = new List<Distri_WorkorderDto>();
            //此法写的原因是要查询对应时间段的工单，需要或||拼接 ----------------------------------------------
            var list_distri = new List<Distri_Workorder>();
            if (!string.IsNullOrEmpty(rolecode))
            {
                //var query1 = new List<Distri_WorkorderDto>();
                ////条件拼接（时间段查询） -----------------
                //非值班 && x.roleList.Select(r => r.rolecode).Contains(rolecode) 以排班的选中角色为准   
                var listClass = query_classgroup.ToList();
                if (rolecode.Equals("SSY_DTG"))
                    listClass = query_classgroup.ToList().Where(x => x.iswork == false).ToList();

                if (listClass != null && listClass.Count > 0)
                {
                    #region 获取新工单 by 排班/班次  - 电梯岗 -----------------------------------------
                    //获取新工单
                    var query_zero = listdistri.Where(x => x.wostate == (int)EnumDistributionState.create).ToList();
                    listClassUser = listClassUser.Where(x => x.date == nowDay && x.usercode == usercode).ToList();
                    foreach (var item in listClassUser)
                    {
                        #region 调用条件 - 日期和班别code

                        //获取条件 - 日期和班别code                           
                        var list_code = new List<string> { };   //班别code
                        var dayone = item.date;
                        var list_r = item.classgroupList.ToList();
                        foreach (var item_r in list_r)
                        {
                            if (item_r.roleList != null && item_r.roleList.Count > 0)
                            {
                                //角色 - 班别
                                var mode_r = item_r.roleList.FirstOrDefault(x => x.ischeck == true);  //rolecode SSY_PSG  // && x.rolecode == rolecode
                                if (mode_r != null)
                                    list_code.Add(item_r.code);
                            }
                        }

                        if (list_code != null && list_code.Count > 0)
                        {
                            listClass = listClass.Where(x => list_code.Contains(x.code)).ToList();
                            var model_Class = listClass.FirstOrDefault(x => DateTime.Parse(nowDay + " " + x.starttime) <= dtnow && DateTime.Parse(nowDay + " " + x.endtime) >= dtnow);
                            if (model_Class != null)
                            {
                                list_distri = list_distri.Union(query_zero.Where(x => x.createtime >= DateTime.Parse(dayone + " " + model_Class.starttime) && x.createtime <= DateTime.Parse(dayone + " " + model_Class.endtime))).ToList();
                            }
                            //foreach (var item_Class in listClass)
                            //{
                            //    list_distri = list_distri.Union(query_zero.Where(x => x.createtime >= DateTime.Parse(dayone + " " + item_Class.starttime) && x.createtime <= DateTime.Parse(dayone + " " + item_Class.endtime))).ToList();
                            //}
                        }
                        #endregion
                    }
                    #endregion
                }
            }
            #endregion

            if (rolecode.Equals("YWYG"))
            {
                //1、已抢单 和 已转派 运维员工  <-->  新单 - 未抢单 和 未转派 运维员工  -- 合并两List
                listrepair_base = listrepair_base.Where(x => x.wostate == 1 && x.touser.Contains(usercode))
                    .Concat(listrepair_base.Where(x => x.wostate == 0));
                listmaintain_base = listmaintain_base.Where(x => x.wostate == 1 && x.maintainuser.Contains(usercode))
                    .Concat(listmaintain_base.Where(x => x.wostate == 0));
                listequipmentrunning = listequipmentrunning.Where(x => x.wostate == 1 && x.checkby.Equals(usercode))
                    .Concat(listequipmentrunning.Where(x => x.wostate == 0));
                listetimeout = listetimeout.Where(x => x.touser.Equals(usercode));
            }
            else if (rolecode.Equals("SSY_PSG"))
            {
                //rolecode.Equals("SSY_DTG") || 
                //20、配送岗   <-->  新单 、派单(派单/强制派单)  -- 合并两List
                //listdistri = listdistri.Where(x => x.wostate == (int)EnumDistributionState.assign && x.touser.Contains(usercode))
                //       .Concat(listdistri.Where(x => x.wostate == (int)EnumDistributionState.create));
                listdistri = listdistri.Where(x => x.wostate == (int)EnumDistributionState.assign && x.touser.Contains(usercode))
                    .Concat(list_distri);    //合并新建工单，和接单工单
                listwotask = listwotask.Where(x => x.joinuserlist.Count > 0 && x.joinuserlist.Contains(usercode));
            }
            else if (rolecode.Equals("SSY_DTG"))
            {
                listwotask = listwotask.Where(x => x.joinuserlist.Count > 0 && x.joinuserlist.Contains(usercode));
            }
            else if (rolecode.Equals("SSY_ZG"))
            {
                DateTime dTime = nowTime.AddMinutes(timespan * 4);    //推迟4 * 几分钟
                //21、无人抢单 - 配送主管   <-->  新单 、派单(派单/强制派单)  -- 合并两List
                listdistri = listdistri.Where(x => x.wostate == (int)EnumDistributionState.create && x.createtime < dTime);
            }
            else if (rolecode.Equals("YWZG"))
            {
                DateTime dTime = nowTime.AddMinutes(timespan * 1);    //推迟1 * 几分钟
                //2、无人抢单 - 运维主管
                listrepair_base = listrepair_base.Where(x => x.wostate == 0 && x.createtime < dTime);
                listmaintain_base = listmaintain_base.Where(x => x.wostate == 0 && x.createtime < dTime);
                listequipmentrunning = listequipmentrunning.Where(x => (x.wostate == 0 && x.createtime < dTime) || x.wostate == 3); //包含完成工单(完成巡检后给对应的管理员发送信息)
                listetimeout = listetimeout.Where(x => x.createtime < dTime);
            }
            else if (rolecode.Equals("YWFJL"))
            {
                DateTime dTime = nowTime.AddMinutes(timespan * 3);    //推迟3 * 几分钟
                //3、无派单 - 运营副经理
                listrepair_base = listrepair_base.Where(x => x.wostate == 0 && x.createtime < dTime);
                listmaintain_base = listmaintain_base.Where(x => x.wostate == 0 && x.createtime < dTime);
                listequipmentrunning = listequipmentrunning.Where(x => x.wostate == 0 && x.createtime < dTime);
                listetimeout = listetimeout.Where(x => x.createtime < dTime);
            }
            else if (rolecode.Equals("YWJL") || rolecode.Equals("YWZJ"))
            {
                DateTime dTime = nowTime.AddMinutes(timespan * 4);    //推迟4 * 几分钟
                //无管理 - 运营经理 和 运营总监
                listrepair_base = listrepair_base.Where(x => x.wostate == 0 && x.createtime < dTime);
                listmaintain_base = listmaintain_base.Where(x => x.wostate == 0 && x.createtime < dTime);
                listequipmentrunning = listequipmentrunning.Where(x => x.wostate == 0 && x.createtime < dTime);
                listetimeout = listetimeout.Where(x => x.createtime < dTime);
            }
            else if (rolecode.Equals("YWFZ") || rolecode.Equals("YWZJL"))
            {
                DateTime dTime = nowTime.AddMinutes(timespan * 6);    //推迟6 * 几分钟
                //无管理 - 运营副总 和 运营总经理
                listrepair_base = listrepair_base.Where(x => x.wostate == 0 && x.createtime < dTime);
                listmaintain_base = listmaintain_base.Where(x => x.wostate == 0 && x.createtime < dTime);
                listequipmentrunning = listequipmentrunning.Where(x => x.wostate == 0 && x.createtime < dTime);
                listetimeout = listetimeout.Where(x => x.createtime < dTime);
            }
            else
            {
                //其他角色或空是，不显示消息提醒
                return Success("角色（" + rolecode + "）不获取消息提醒", new { rows = new List<MessageListDto>(), total = -1 });
            }
            #endregion

            if (rolecode.Equals("SSY_PSG") || rolecode.Equals("SSY_DTG"))
            {
                #region 配送计划工单 - 配送
                foreach (var item in listwotask)
                {
                    string statename = string.Empty;
                    if (item.planwostate == (int)EnumDistriWorkOrderPlanWOstate.start)
                        statename = "新建计划工单";
                    var listmapwo = listmap.Where(x => x.wocode.Equals(item.wocode) && x.wostate.Equals(item.planwostate) && x.channelcode == (int)EnumOrderState.配送计划工单);
                    var modelmap = listmapwo.FirstOrDefault();
                    //未推送
                    if (modelmap == null)
                    {
                        string goodsDetail = (item.goodslist != null && item.goodslist.Count > 0) ? ",配送计划物品:" + item.goodslist.Select(x => x.goodsname).ToJson() : "";
                        list.Add(new MessageListDto
                        {
                            id = item.id,
                            woid = item.id,
                            channelcode = (int)EnumOrderState.配送计划工单,
                            wotype = (int)EnumWoType.配送计划,
                            wocode = item.wocode,
                            proname = "配送计划工单:" + item.wocode,
                            title = item.wocode,
                            content = "配送计划工单说明:" + item.content + goodsDetail,
                            wostate = item.planwostate,
                            statename = statename, //工单状态
                            checkby = string.Join(",", item.joinuserlist),    //接单人
                            createby = item.createtby,
                            createtime = item.createtime,
                            isread = 0,
                        });
                    }
                }
                #endregion

                #region 配送工单
                foreach (var item in listdistri)
                {
                    string statename = string.Empty;
                    if (item.wostate == (int)EnumDistributionState.create)
                        statename = "新建工单";
                    if (item.wostate == (int)EnumDistributionState.assign)
                        statename = "派单/强制派单";
                    var listmapwo = listmap.Where(x => x.wocode.Equals(item.wocode) && x.wostate.Equals(item.wostate) && x.channelcode == (int)EnumOrderState.配送工单);
                    var modelmap = listmapwo.FirstOrDefault();
                    //未推送
                    if (modelmap == null)
                    {
                        string goodsDetail = (item.goodslist != null && item.goodslist.Count > 0) ? ",配送物品:" + item.goodslist.Select(x => x.goodsname).ToJson() : "";
                        list.Add(new MessageListDto
                        {
                            id = item.id,
                            woid = item.id,
                            channelcode = (int)EnumOrderState.配送工单,
                            wotype = (int)EnumWoType.配送,
                            wocode = item.wocode,
                            proname = "配送工单:" + item.wocode,
                            title = item.wocode,
                            content = "配送说明:" + item.detail + goodsDetail,
                            wostate = item.wostate,
                            statename = statename, //工单状态
                            checkby = string.Join(",", item.touser),    //接单人
                            createby = item.createtby,
                            createtime = item.createtime,
                            isread = 0,
                        });
                    }
                }
                #endregion
            }
            else
            {

                #region 维修工单
                foreach (var item in listrepair_base)
                {
                    string statename = string.Empty;
                    if (item.wostate == (int)EnumWorkOrderState.create)
                        statename = "新建工单";
                    if (item.wostate == (int)EnumWorkOrderState.assign)
                        statename = "已转派/已抢单";
                    if (item.wostate >= (int)EnumWorkOrderState.deal)
                        statename = "已完成";
                    if (item.wostate == (int)EnumWorkOrderState.hangup)
                        statename = "已挂起";
                    var listmapwo = listmap.Where(x => x.wocode.Equals(item.wocode) && x.wostate.Equals(item.wostate) && x.channelcode == (int)EnumOrderState.维修工单);
                    var modelmap = listmapwo.FirstOrDefault();
                    //未推送
                    if (modelmap == null)
                    {
                        list.Add(new MessageListDto
                        {
                            id = item.id,
                            woid = item.id,
                            channelcode = (int)EnumOrderState.维修工单,
                            wotype = (int)EnumWoType.维修,
                            wocode = item.wocode,
                            proname = "维修工单:" + item.wocode, // + " " + item.proname,
                            title = item.wocode,
                            content = "故障说明:" + item.faultdescripe,
                            wostate = item.wostate,
                            statename = statename, //工单状态
                            checkby = string.Join(",", item.touser),    //接单人
                            createby = item.createuser,
                            createtime = item.createtime,
                            isread = 0,
                        });
                    }
                }
                #endregion

                #region 保养工单
                foreach (var item in listmaintain_base)
                {
                    string statename = string.Empty;
                    if (item.wostate == (int)EnumWorkOrderState.create)
                        statename = "新建工单";
                    if (item.wostate == (int)EnumWorkOrderState.assign)
                        statename = "已转派/已抢单";
                    if (item.wostate >= (int)EnumWorkOrderState.deal)
                        statename = "已完成";
                    if (item.wostate == (int)EnumWorkOrderState.hangup)
                        statename = "已挂起";
                    var listmapwo = listmap.Where(x => x.wocode.Equals(item.wocode) && x.wostate.Equals(item.wostate) && x.channelcode == (int)EnumOrderState.保养工单);
                    var modelmap = listmapwo.FirstOrDefault();
                    //未推送
                    if (modelmap == null)
                    {
                        list.Add(new MessageListDto
                        {
                            id = item.id,
                            woid = item.id,
                            channelcode = (int)EnumOrderState.保养工单,
                            wotype = (int)EnumWoType.保养,
                            wocode = item.wocode,
                            proname = "保养工单:" + item.wocode, // + " " + item.proname,
                            title = item.wocode,
                            content = item.woname + (string.IsNullOrEmpty(item.maintaincontent) ? "" : ",保养内容:" + item.maintaincontent), //保养内容
                            wostate = item.wostate,
                            statename = statename, //工单状态
                                                   //checkby = item.maintainman, //保修人
                            checkby = string.Join(",", item.maintainuser),
                            createby = item.createby,
                            createtime = item.createtime,
                            isread = 0,
                        });
                    }
                }
                #endregion

                #region 设备巡检工单
                foreach (var item in listequipmentrunning)
                {
                    #region 检查事项
                    var matternames = "";
                    if (item.matterids != null && item.matterids.Count() > 0)
                    {
                        var matterids = string.Join(",", item.matterids);
                        if (!string.IsNullOrEmpty(matterids))
                        {
                            var mattermodel = listmatter.FirstOrDefault(x => matterids.Contains(x.id));
                            matternames = mattermodel != null ? mattermodel.matter : "";
                        }
                    }
                    #endregion
                    #region
                    ////判断巡检中设备id是否为空
                    //var modelequname = new Eqp_Equipment_Info();
                    //if (item.equipmentid != null && item.equipmentid.Count() > 0)
                    //{
                    //    var equipmentids = string.Join(",", item.equipmentid);
                    //    if (!string.IsNullOrEmpty(equipmentids))
                    //        modelequname = listequipment_info.FirstOrDefault(x => equipmentids.Contains(x.id));
                    //}
                    //string equipmentname = string.Empty;
                    //equipmentname = modelequname != null ? modelequname.equipment_name : "";
                    #endregion
                    string statename = string.Empty;
                    if (item.wostate == (int)EnumWorkOrderState.create)
                        statename = "新建工单";
                    if (item.wostate == (int)EnumWorkOrderState.assign)
                        statename = "已转派/已抢单";
                    if (item.wostate >= (int)EnumEquipmentRunningState.grab && item.wostate < (int)EnumEquipmentRunningState.deal)
                        statename = "未完成";
                    if (item.wostate >= (int)EnumEquipmentRunningState.deal)
                        statename = "已完成";
                    if (item.wostate == (int)EnumEquipmentRunningState.hangup)
                        statename = "已挂起";

                    var listmapwo = listmap.Where(x => x.wocode.Equals(item.wocode) && x.wostate.Equals(item.wostate) && x.channelcode == (int)EnumOrderState.巡检工单);
                    #region 条件 - 工单需要提醒时
                    if (item.wostate == 0 || (item.wostate == 3 && item.isreturnmsg == 1))
                    {
                        listmapwo = listmapwo.Where(x => x.wostate == item.wostate);
                    }
                    #endregion

                    var modelmap = listmapwo.FirstOrDefault();
                    var orderStateTitle = item.wostate == 3 ? "已完成" : "";
                    //var contentStr = "设备名称:" + equipmentname;
                    var contentStr = "检查事项:" + matternames;

                    if (item.quipmenttype == 0)
                        contentStr += "运维异常说明:" + item.checkcontent;
                    //未推送
                    if (modelmap == null)
                    {
                        list.Add(new MessageListDto
                        {
                            id = item.id,
                            woid = item.id,
                            channelcode = (int)EnumOrderState.巡检工单,
                            wotype = (int)EnumWoType.巡检,
                            wocode = item.wocode,
                            //proname = "设备运行工单:" + item.wocode + orderStateTitle + " 设备名称:" + equipmentname,
                            proname = "设备运行工单:" + item.wocode + orderStateTitle + " 检查事项:" + matternames,
                            title = item.wocode,
                            content = item.woname + (string.IsNullOrEmpty(item.wocontent) ? "" : ",工单内容:" + item.wocontent) + (string.IsNullOrEmpty(item.checkcontent) ? "" : ",异常说明:" + item.checkcontent), //运维内容
                            wostate = item.wostate,
                            statename = statename, //工单状态
                            checkby = item.checkby, //巡检人
                            createby = item.createby,
                            createtime = item.createtime,
                            isread = 0,
                        });
                    }
                }
                #endregion

                #region 超时工单
                foreach (var item in listetimeout)
                {
                    string statename = string.Empty;
                    if (item.isover == true)
                        statename = "已完结";
                    else
                        statename = "否完结";
                    var listmapwo = listmap.Where(x => x.wocode.Equals(item.wocode) && x.channelcode == (int)EnumOrderState.超时工单);
                    var modelmap = listmapwo.FirstOrDefault();
                    //未推送
                    if (modelmap == null)
                    {
                        list.Add(new MessageListDto
                        {
                            id = item.id,
                            woid = item.id,
                            channelcode = (int)EnumOrderState.超时工单,
                            wotype = item.wotype,
                            wocode = item.wocode,
                            proname = "超时工单（" + Enum.GetName(typeof(EnumWoType), item.wotype) + "）:" + item.wocode + ",延迟时长：" + item.times,
                            title = item.wocode,
                            content = "超时原因:" + item.timeoutreason, //超时原因
                            wostate = 99,   //超时工单无需根据状态处理转派，故默认写个参数值99
                            statename = statename, //工单状态
                            createby = item.manager,
                            createtime = item.createtime,
                            isread = 0,
                        });
                    }
                }
                #endregion
            }

            

            //升序排序 - （跟消息提醒排序相反，推送时先推日期比较早的工单，后推送日期比较晚的工单，故短信排在手机最上面）
            list = list.OrderBy(x => x.createtime).ToList();
            var obj = new
            {
                rows = list,
                total = list.Count, //消息数
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 测试 - 批量修改消息内容和id
        /// </summary>
        /// <returns></returns>
        [HttpGet("getmessagelist_ceshi")]
        public async Task<IActionResult> GetMessagesList_ceshi()
        {
            var listrepair_bases = await _wo_repair_baseRepository.Get(x => x.isdelete == 0);
            var listmaintain_bases = await _wo_maintain_baserepository.Get(x => x.isdelete == false);
            var listequipmentrunnings = await _wo_equipmentrunningrepository.Get(x => x.isdelete == 0);
            var listetimeouts = await _wo_timeoutrepository.Get(x => x.isdelete == false);

            var listmap = await _wo_order_user_maprepository.GetAll();

            int i = 0;
            foreach (var item in listmap)
            {
                string statename = string.Empty;
                var woid = string.Empty;
                string content = string.Empty;
                #region 获取工单id
                //维修工单
                if (item.channelcode == 1 && !string.IsNullOrEmpty(item.wocode))
                {
                    //var listWorkOrder = listrepair_bases.Where(x => x.wocode.Equals(item.wocode));
                    var modelWorkOrder = listrepair_bases.Where(x => x.wocode.Equals(item.wocode)).FirstOrDefault();
                    if (modelWorkOrder != null)
                    {
                        woid = modelWorkOrder.id;
                        content = "故障说明:" + modelWorkOrder.faultdescripe;
                    }
                }
                //保养工单
                if (item.channelcode == 2 && !string.IsNullOrEmpty(item.wocode))
                {
                    var listWorkOrder = listmaintain_bases.Where(x => x.wocode.Equals(item.wocode));
                    var modelWorkOrder = listWorkOrder.FirstOrDefault();
                    if (modelWorkOrder != null)
                    {
                        woid = modelWorkOrder.id;
                        content = modelWorkOrder.woname + (string.IsNullOrEmpty(modelWorkOrder.maintaincontent) ? "" : ",保养内容:" + modelWorkOrder.maintaincontent);
                    }
                }
                //设备巡检工单
                if (item.channelcode == 3 && !string.IsNullOrEmpty(item.wocode))
                {
                    var listWorkOrder = listequipmentrunnings.Where(x => x.wocode.Equals(item.wocode));
                    var modelWorkOrder = listWorkOrder.FirstOrDefault();
                    if (modelWorkOrder != null)
                    {
                        woid = modelWorkOrder.id;
                        content = modelWorkOrder.woname + (string.IsNullOrEmpty(modelWorkOrder.wocontent) ? "" : ",工单内容:" + modelWorkOrder.wocontent) + (string.IsNullOrEmpty(modelWorkOrder.checkcontent) ? "" : ",异常说明:" + modelWorkOrder.checkcontent);
                    }
                }
                //超时工单
                if (item.channelcode == 4 && !string.IsNullOrEmpty(item.wocode))
                {
                    var listWorkOrder = listetimeouts.Where(x => x.wocode.Equals(item.wocode));
                    var modelWorkOrder = listWorkOrder.FirstOrDefault();
                    if (modelWorkOrder != null)
                    {
                        woid = modelWorkOrder.id;
                        content = "超时原因:" + modelWorkOrder.timeoutreason;
                    }
                }
                #endregion
                if (!string.IsNullOrEmpty(woid))
                {
                    i += 1;
                    item.woid = woid;
                    item.note = content;
                    await _wo_order_user_maprepository.Update(item);
                }                
            }
            return Success("更新工单id,和内容,num:" + i);
        }

        /// <summary>
        /// 消息通知 - 设备维修（报修工单）
        /// 维修工单/保养工单/巡检工单/超时工单
        /// </summary>
        /// <param name="messagetype">消息类型 (1消息通知信息，2推送信息)</param>
        /// <returns></returns>
        [HttpGet("getmessagelist")]
        public async Task<IActionResult> GetMessagesList()
        {
            #region 不同地方
            //int messagetype = 1;    //消息通知
            //运维员工YWYG，运维主管YWZG
            string rolecode =  User.Claims.FirstOrDefault(c => c.Type == "RoleCode").Value;
            string usercode =  User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;//工单用户查看关系表 - 已查看订单
            string projectlist = "";
            //获取角色code
            var modelUser =  await _sys_user_accountRepository.GetSingle(x => x.usercode == usercode);
            if (modelUser != null)
            {
                projectlist = string.Join(",", modelUser.projectlist);
            }
            var listmap = await _wo_order_user_maprepository.Get(x => x.readby == usercode);    // && x.isread == 1
            listmap = listmap.Where(x => x.isnotice == 1 && x.isread == 1);
            #endregion

            int topNum = 0;
            int.TryParse(_configuration["PushMessage:MessageNoReadNum"], out topNum);

            //维修工单 - 未处理完成
            var listrepair_base = await _wo_repair_baseRepository.Get(x => x.wostate == 1 && x.isdelete == 0);
            //保养工单 - 未处理完成
            var listmaintain_base = await _wo_maintain_baserepository.Get(x => x.wostate == 1 && x.isdelete == false);
            //设备巡检工单 - 未处理完成
            var listequipmentrunning = await _wo_equipmentrunningrepository.Get(x => x.wostate==1  && x.isdelete == 0);
            //超时工单 - 所有
            var listetimeout = await _wo_timeoutrepository.Get(x => x.isdelete == false && x.istimeout == 1);
            //配送工单 - 新工单，派单(派单/强制派单)
            var listdistri = await _distri_workorderrepository.Get(x => x.wostate <= (int)EnumDistributionState.assign && x.isdelete == 0 && x.totype != (int)EnumDistributionTotype.robbery);  // && (x.totype == (int)EnumDistributionTotype.send || x.totype == (int)EnumDistributionTotype.assign)
            //班次
            var query_classgroup = await _sys_classgrouprepository.Get(x => x.isdelete == 0);
            //排班
            var query_usermap = await _sys_classgroup_user_maprepository.Get(x => x.isdelete == 0 && x.isstatus == 1);
            //计划工单
            var listwotask = await _distri_workorder_plantaskrepository.Get(x => x.isdelete == 0 && x.planwostate != (int)EnumDistriWorkOrderPlanWOstate.start);

            //设备信息
            var listequipment_info = await _eqp_equipment_inforepository.Get(x => x.isdelete == 0);
            //检查事项
            var listmatter = await _wo_mattersRepository.Get(x => x.isdelete == false);
            var list = new List<MessageListDto>();
            var list_noread = new List<MessageListDto>();
            var list_read = new List<MessageListDto>();

            #region 条件判断 - 工单消息提醒和推送流程
            //1、运维员工 YWYG < 2、运维主管 YWZG < 3、运营副经理 YWFJL < 4、运营经理 YWJL < 5、运营总监 YWZJ < 6、运营副总 YWFZ < 7、运营总经理 YWZJL
            //说明工单（延迟时间配置DelayPushTime）：
            //   1、新单出现 运维员工 抢单；（例如9:00）
            //   2、超过 1 * 几分钟 无人抢单行为推送给 运维主管；（例如9:05）
            //   3、超过 3 * 几分钟 无派单行为推送给 运营副经理；（例如9:15）
            //   4、超过 4 * 几分钟 无管理行为推送给 运营经理和运营总监；（例如9:20）
            //   5、超过 6 * 几分钟 无管理行为推送给 运营副总和运营总经理；（例如9:30）
            int timespan = 0;
            int.TryParse(_configuration["PushMessage:DelayPushTime"], out timespan);
            DateTime nowTime = DateTime.Now.ToLocalTime();

            var listrepair_base2 = await _wo_repair_baseRepository.GetAll();
            listrepair_base = listrepair_base.Where(x => projectlist.Contains(x.projectid));
            listmaintain_base = listmaintain_base.Where(x => projectlist.Contains(x.projectid));
            listequipmentrunning = listequipmentrunning.Where(x => projectlist.Contains(x.projectid));
            //listetimeout = listetimeout.Where(x => projectlist.Contains(x.projectid));
            listdistri = listdistri.Where(x => projectlist.Contains(x.projectid));

            #region 配送工单 参与 排班条件
            //随机工单
            DateTime dtnow = DateTime.Now;
            string nowDay = dtnow.ToString("yyyy-MM-dd");
            var listClassUser = query_usermap.Where(x => x.date == nowDay).ToList();     //.Where(x=>x.date == nowDay)
            //var query_result = new List<Distri_WorkorderDto>();
            //此法写的原因是要查询对应时间段的工单，需要或||拼接 ----------------------------------------------
             var list_distri = new List<Distri_Workorder>();
            if (!string.IsNullOrEmpty(rolecode))
            {
                //var query1 = new List<Distri_WorkorderDto>();
                ////条件拼接（时间段查询） -----------------
                //非值班 && x.roleList.Select(r => r.rolecode).Contains(rolecode) 以排班的选中角色为准   
                var listClass = query_classgroup.ToList();
                if (rolecode.Equals("SSY_DTG"))
                    listClass = query_classgroup.ToList().Where(x => x.iswork == false).ToList();

                if (listClass != null && listClass.Count > 0)
                {
                    #region 获取新工单 by 排班/班次  - 电梯岗 -----------------------------------------
                    //获取新工单
                    var query_zero = listdistri.Where(x => x.wostate == (int)EnumDistributionState.create).ToList();
                    listClassUser = listClassUser.Where(x => x.date == nowDay && x.usercode == usercode).ToList();
                    foreach (var item in listClassUser)
                    {
                        #region 调用条件 - 日期和班别code

                        //获取条件 - 日期和班别code                           
                        var list_code = new List<string> { };   //班别code
                        var dayone = item.date;
                        var list_r = item.classgroupList.ToList();
                        foreach (var item_r in list_r)
                        {
                            if (item_r.roleList != null && item_r.roleList.Count > 0)
                            {
                                //角色 - 班别
                                var mode_r = item_r.roleList.FirstOrDefault(x => x.ischeck == true);  //rolecode SSY_PSG   // && x.rolecode == rolecode
                                if (mode_r != null)
                                    list_code.Add(item_r.code);
                            }
                        }

                        if (list_code != null && list_code.Count > 0)
                        {
                            listClass = listClass.Where(x => list_code.Contains(x.code)).ToList();
                            var model_Class = listClass.FirstOrDefault(x => DateTime.Parse(nowDay + " " + x.starttime) <= dtnow && DateTime.Parse(nowDay + " " + x.endtime) >= dtnow);
                            if (model_Class != null)
                            {
                                list_distri = list_distri.Union(query_zero.Where(x => x.createtime >= DateTime.Parse(dayone + " " + model_Class.starttime) && x.createtime <= DateTime.Parse(dayone + " " + model_Class.endtime))).ToList();
                            }
                            //foreach (var item_Class in listClass)
                            //{
                            //    list_distri = list_distri.Union(query_zero.Where(x => x.createtime >= DateTime.Parse(dayone + " " + item_Class.starttime) && x.createtime <= DateTime.Parse(dayone + " " + item_Class.endtime))).ToList();
                            //}
                        }
                        #endregion
                    }
                    #endregion
                }
            }
            #endregion

            if (rolecode.Equals("YWYG"))
            {
                //1、已抢单 和 已转派 运维员工  <-->  新单 - 未抢单 和 未转派 运维员工  -- 合并两List
                listrepair_base = listrepair_base.Where(x => x.wostate == 1 && x.touser.Contains(usercode))
                    .Concat(listrepair_base.Where(x => x.wostate == 0));
                listmaintain_base = listmaintain_base.Where(x => x.wostate == 1 && x.maintainuser.Contains(usercode))
                    .Concat(listmaintain_base.Where(x => x.wostate == 0));
                listequipmentrunning = listequipmentrunning.Where(x => x.wostate == 1 && x.checkby.Equals(usercode))
                    .Concat(listequipmentrunning.Where(x => x.wostate == 0));
                listetimeout = listetimeout.Where(x => x.touser.Equals(usercode));
            }
            else if (rolecode.Equals("SSY_PSG"))
            {
                //rolecode.Equals("SSY_DTG") || 
                //20、配送岗   <-->  新单 、派单(派单/强制派单)  -- 合并两List
                //listdistri = listdistri.Where(x => x.wostate == (int)EnumDistributionState.assign && x.touser.Contains(usercode))
                //       .Concat(listdistri.Where(x => x.wostate == (int)EnumDistributionState.create));
                //var list_d = listdistri.Where(x => x.wostate == (int)EnumDistributionState.assign && x.touser.Contains(usercode)).ToList();
                listdistri = listdistri.Where(x => x.wostate == (int)EnumDistributionState.assign && x.touser.Contains(usercode))
                    .Concat(list_distri);    //合并新建工单，和接单工单
                listwotask = listwotask.Where(x => x.joinuserlist.Count > 0 && x.joinuserlist.Contains(usercode));
            }
            else if (rolecode.Equals("SSY_DTG"))
            {
                listwotask = listwotask.Where(x => x.joinuserlist.Count > 0 && x.joinuserlist.Contains(usercode));
            }
            else if (rolecode.Equals("SSY_ZG"))
            {
                DateTime dTime = nowTime.AddMinutes(timespan * 4);    //推迟4 * 几分钟
                //21、无人抢单 - 配送主管   <-->  新单 、派单(派单/强制派单)  -- 合并两List
                listdistri = listdistri.Where(x => x.wostate == (int)EnumDistributionState.create && x.createtime < dTime);
            }
            else if (rolecode.Equals("YWZG"))
            {
                DateTime dTime = nowTime.AddMinutes(timespan * 1);    //推迟1 * 几分钟
                //2、无人抢单 - 运维主管
                listrepair_base = listrepair_base.Where(x => x.wostate == 0 && x.createtime < dTime);
                listmaintain_base = listmaintain_base.Where(x => x.wostate == 0 && x.createtime < dTime);
                listequipmentrunning = listequipmentrunning.Where(x => (x.wostate == 0 && x.createtime < dTime) || x.wostate == 3); //包含完成工单(完成巡检后给对应的管理员发送信息)
                listetimeout = listetimeout.Where(x => x.createtime < dTime);
            }
            else if (rolecode.Equals("YWFJL"))
            {
                DateTime dTime = nowTime.AddMinutes(timespan * 3);    //推迟3 * 几分钟
                //3、无人派单 - 运营副经理
                listrepair_base = listrepair_base.Where(x => x.wostate == 0 && x.createtime < dTime);
                listmaintain_base = listmaintain_base.Where(x => x.wostate == 0 && x.createtime < dTime);
                listequipmentrunning = listequipmentrunning.Where(x => x.wostate == 0 && x.createtime < dTime);
                listetimeout = listetimeout.Where(x => x.createtime < dTime);
            }
            else if (rolecode.Equals("YWJL") || rolecode.Equals("YWZJ"))
            {
                DateTime dTime = nowTime.AddMinutes(timespan * 4);    //推迟4 * 几分钟
                //无人管理 - 运营经理 和 运营总监
                listrepair_base = listrepair_base.Where(x => x.wostate == 0 && x.createtime < dTime);
                listmaintain_base = listmaintain_base.Where(x => x.wostate == 0 && x.createtime < dTime);
                listequipmentrunning = listequipmentrunning.Where(x => x.wostate == 0 && x.createtime < dTime);
                listetimeout = listetimeout.Where(x => x.createtime < dTime);
            }
            else if (rolecode.Equals("YWFZ") || rolecode.Equals("YWZJL"))
            {
                DateTime dTime = nowTime.AddMinutes(timespan * 6);    //推迟6 * 几分钟
                //无人管理 - 运营副总 和 运营总经理
                listrepair_base = listrepair_base.Where(x => x.wostate == 0 && x.createtime < dTime);
                listmaintain_base = listmaintain_base.Where(x => x.wostate == 0 && x.createtime < dTime);
                listequipmentrunning = listequipmentrunning.Where(x => x.wostate == 0 && x.createtime < dTime);
                listetimeout = listetimeout.Where(x => x.createtime < dTime);
            }
            else
            {
                //其他角色或空是，不显示消息提醒
                return Success("角色（" + rolecode + "）不获取消息提醒", new { rows = new List<MessageListDto>(), total = -1 });
            }
            #endregion


            if (rolecode.Equals("SSY_PSG") || rolecode.Equals("SSY_DTG"))
            {
                #region 配送计划工单 - 配送
                foreach (var item in listwotask)
                {
                    string statename = string.Empty;
                    if (item.planwostate == (int)EnumDistriWorkOrderPlanWOstate.start)
                        statename = "新建计划工单";
                    var listmapwo = listmap.Where(x => x.wocode.Equals(item.wocode) && x.wostate.Equals(item.planwostate) && x.channelcode == (int)EnumOrderState.配送计划工单);
                    var modelmap = listmapwo.FirstOrDefault();
                    //未推送
                    if (modelmap == null)
                    {
                        string goodsDetail = (item.goodslist != null && item.goodslist.Count > 0) ? ",配送计划物品:" + item.goodslist.Select(x => x.goodsname).ToJson() : "";
                        list.Add(new MessageListDto
                        {
                            id = item.id,
                            woid = item.id,
                            channelcode = (int)EnumOrderState.配送计划工单,
                            wotype = (int)EnumWoType.配送计划,
                            wocode = item.wocode,
                            proname = "配送计划工单:" + item.wocode,
                            title = item.wocode,
                            content = "配送计划工单说明:" + item.content + goodsDetail,
                            wostate = item.planwostate,
                            statename = statename, //工单状态
                            checkby = string.Join(",", item.joinuserlist),    //接单人
                            createby = item.createtby,
                            createtime = item.createtime,
                            isread = 0,
                        });
                    }
                }
                #endregion

                #region 配送工单
                foreach (var item in listdistri)
                {
                    string statename = string.Empty;
                    if (item.wostate == (int)EnumDistributionState.create)
                        statename = "新建工单";
                    if (item.wostate == (int)EnumDistributionState.assign)
                        statename = "派单/强制派单";
                    var listmapwo = listmap.Where(x => x.wocode.Equals(item.wocode) && x.wostate.Equals(item.wostate) && x.channelcode == (int)EnumOrderState.配送工单);
                    var modelmap = listmapwo.FirstOrDefault();
                    if (modelmap == null)
                    {
                        string goodsDetail = (item.goodslist != null && item.goodslist.Count > 0) ? ",配送物品:" + item.goodslist.Select(x => x.goodsname).ToJson() : "";
                        //未读
                        list_noread.Add(new MessageListDto
                        {
                            id = item.id,
                            woid = item.id,
                            channelcode = (int)EnumOrderState.配送工单,
                            wotype = (int)EnumWoType.配送,
                            wocode = item.wocode,
                            proname = "配送工单:" + item.wocode,
                            title = item.wocode,
                            content = "配送说明:" + item.detail + goodsDetail,
                            wostate = item.wostate,
                            statename = statename, //工单状态
                            checkby = string.Join(",", item.touser),    //接单人
                            createby = item.createtby,
                            createtime = item.createtime,
                            isread = 0,
                        });
                    }
                }
                #endregion
            }
            else
            {
                #region 维修工单
                foreach (var item in listrepair_base)
                {
                    string statename = string.Empty;
                    if (item.wostate == (int)EnumWorkOrderState.create)
                        statename = "新建工单";
                    if (item.wostate == (int)EnumWorkOrderState.assign)
                        statename = "已转派/已抢单";
                    if (item.wostate >= (int)EnumWorkOrderState.deal)
                        statename = "已完成";
                    if (item.wostate == (int)EnumWorkOrderState.hangup)
                        statename = "已挂起";
                    var listmapwo = listmap.Where(x => x.wocode.Equals(item.wocode) && x.wostate.Equals(item.wostate) && x.channelcode == (int)EnumOrderState.维修工单);
                    var modelmap = listmapwo.FirstOrDefault();
                    if (modelmap == null)
                    {
                        //未读
                        list_noread.Add(new MessageListDto
                        {
                            id = item.id,
                            woid = item.id,
                            channelcode = (int)EnumOrderState.维修工单,
                            wotype = (int)EnumWoType.维修,
                            wocode = item.wocode,
                            proname = "维修工单:" + item.wocode, // + " " + item.proname,
                            title = item.wocode,
                            content = "故障说明:" + item.faultdescripe,
                            wostate = item.wostate,
                            statename = statename, //工单状态
                            checkby = string.Join(",", item.touser),    //接单人
                            createby = item.createuser,
                            createtime = item.createtime,
                            isread = 0,
                        });
                    }
                }
                #endregion

                #region 保养工单
                foreach (var item in listmaintain_base)
                {
                    string statename = string.Empty;
                    if (item.wostate == (int)EnumWorkOrderState.create)
                        statename = "新建工单";
                    if (item.wostate == (int)EnumWorkOrderState.assign)
                        statename = "已转派/已抢单";
                    if (item.wostate >= (int)EnumWorkOrderState.deal)
                        statename = "已完成";
                    if (item.wostate == (int)EnumWorkOrderState.hangup)
                        statename = "已挂起";
                    var listmapwo = listmap.Where(x => x.wocode.Equals(item.wocode) && x.wostate.Equals(item.wostate) && x.channelcode == (int)EnumOrderState.保养工单);
                    var modelmap = listmapwo.FirstOrDefault();
                    if (modelmap == null)
                    {
                        //未读
                        list_noread.Add(new MessageListDto
                        {
                            id = item.id,
                            woid = item.id,
                            channelcode = (int)EnumOrderState.保养工单,
                            wotype = (int)EnumWoType.保养,
                            wocode = item.wocode,
                            proname = "保养工单:" + item.wocode, // + " " + item.proname,
                            title = item.wocode,
                            content = item.woname + (string.IsNullOrEmpty(item.maintaincontent) ? "" : ",保养内容:" + item.maintaincontent), //保养内容
                            wostate = item.wostate,
                            statename = statename, //工单状态
                                                   //checkby = item.maintainman, //保修人
                            checkby = item.maintainuser.ToString(), //保修人
                            createby = item.createby,
                            createtime = item.createtime,
                            isread = 0,
                        });
                    }
                }
                #endregion

                #region 设备巡检工单
                foreach (var item in listequipmentrunning)
                {
                    #region 检查事项
                    var matternames = "";
                    if (item.matterids != null && item.matterids.Count() > 0)
                    {
                        var matterids = string.Join(",", item.matterids);
                        if (!string.IsNullOrEmpty(matterids))
                        {
                            var mattermodel = listmatter.FirstOrDefault(x => matterids.Contains(x.id));
                            matternames = mattermodel != null ? mattermodel.matter : "";
                        }
                    }
                    #endregion

                    string statename = string.Empty;
                    if (item.wostate == (int)EnumWorkOrderState.create)
                        statename = "新建工单";
                    if (item.wostate == (int)EnumWorkOrderState.assign)
                        statename = "已转派/已抢单";
                    if (item.wostate >= (int)EnumEquipmentRunningState.deal)
                        statename = "已完成";
                    if (item.wostate == (int)EnumEquipmentRunningState.hangup)
                        statename = "已挂起";

                    var listmapwo = listmap.Where(x => x.wocode.Equals(item.wocode) && x.wostate.Equals(item.wostate) && x.channelcode == (int)EnumOrderState.巡检工单);
                    #region 条件 - 工单需要提醒时
                    if (item.wostate == 0 || (item.wostate == 3 && item.isreturnmsg == 1))
                    {
                        listmapwo = listmapwo.Where(x => x.wostate == item.wostate);
                    }
                    #endregion

                    //未读
                    var modelmap = listmapwo.FirstOrDefault();
                    var orderStateTitle = item.wostate == 3 ? "已完成" : "";
                    //var contentStr = "运维设备:" + equipmentname;
                    var contentStr = "检查事项:" + matternames;
                    if (item.quipmenttype == 0)
                        contentStr += "异常说明:" + item.checkcontent;
                    if (modelmap == null)
                    {
                        //未读
                        list_noread.Add(new MessageListDto
                        {
                            id = item.id,
                            woid = item.id,
                            channelcode = (int)EnumOrderState.巡检工单,
                            wotype = (int)EnumWoType.巡检,
                            wocode = item.wocode,
                            //proname = "设备运行工单:" + item.wocode + orderStateTitle + " 设备名称:" + equipmentname,
                            proname = "设备运行工单:" + item.wocode + orderStateTitle + " 检查事项:" + matternames,
                            title = item.wocode,
                            content = item.woname + (string.IsNullOrEmpty(item.wocontent) ? "" : ",工单内容:" + item.wocontent) + (string.IsNullOrEmpty(item.checkcontent) ? "" : ",异常说明:" + item.checkcontent), //运维内容
                            wostate = item.wostate,
                            statename = statename, //工单状态
                            checkby = item.checkby, //巡检人
                            createby = item.createby,
                            createtime = item.createtime,
                            isread = 0,
                        });
                    }
                }
                #endregion

                #region 超时工单
                foreach (var item in listetimeout)
                {
                    string statename = string.Empty;
                    if (item.isover == true)
                        statename = "已完结";
                    else
                        statename = "否完结";
                    var listmapwo = listmap.Where(x => x.wocode.Equals(item.wocode) && x.channelcode == (int)EnumOrderState.超时工单);
                    var modelmap = listmapwo.FirstOrDefault();
                    if (modelmap == null)
                    {
                        //未读
                        list_noread.Add(new MessageListDto
                        {
                            id = item.id,
                            woid = item.id,
                            channelcode = (int)EnumOrderState.超时工单,
                            wotype = item.wotype,
                            wocode = item.wocode,
                            proname = "超时工单（" + Enum.GetName(typeof(EnumWoType), item.wotype) + "）:" + item.wocode + ",延迟时长：" + item.times,
                            title = item.wocode,
                            content = "超时原因:" + item.timeoutreason, //超时原因
                            wostate = 99,   //超时工单无需根据状态处理转派，故默认写个参数值99
                            statename = statename, //工单状态
                            createby = item.manager,
                            createtime = item.createtime,
                            isread = 0,
                        });
                    }
                }
                #endregion


                #region 已读 - 注释
                //自己看自己的
                var listmaps = listmap.Where(x => x.readby == usercode).OrderByDescending(x => x.readtime).Take(topNum);
                foreach (var item in listmaps)
                {
                    string statename = string.Empty;
                    var woid = string.Empty;
                    string content = string.Empty;
                    if (item.wostate == (int)EnumWorkOrderState.create)
                        statename = "新建工单";
                    if (item.wostate == (int)EnumWorkOrderState.assign)
                        statename = "已转派/已抢单";
                    if (item.wostate >= (int)EnumWorkOrderState.deal)
                        statename = "已完成";
                    if (item.wostate == (int)EnumWorkOrderState.hangup)
                        statename = "已挂起";
                    //已读
                    list_read.Add(new MessageListDto
                    {
                        id = item.woid,  //工单id
                        woid = item.woid,  //工单id
                        channelcode = item.channelcode,
                        wotype = item.channelcode,
                        wocode = item.wocode,
                        proname = Enum.GetName(typeof(EnumOrderState), item.channelcode) + ":" + item.wocode,
                        title = item.wocode,
                        content = item.note, //保养内容
                        wostate = item.wostate,
                        statename = statename, //工单状态
                        checkby = item.readby, //保修人
                        createby = "",
                        createtime = item.readtime,
                        isread = 1,
                    });
                }
                #endregion
            }

            //降序排序，获取前50条，合并未读列表 OrderByDescending(x => x.createtime).Take(topNum)
            list = list_read.Concat(list_noread).ToList();
            //降序排序
            list = list.OrderByDescending(x => x.createtime).ToList();
            var obj = new
            {
                rows = list,
                total_read = list_read.Count > topNum ? topNum : list_read.Count, //已读消息数
                total = list_noread.Count, //未读消息数
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 消息通知 - 设备维修（报修工单） - old通过时间（不用）
        /// </summary>
        /// <returns></returns>
        [HttpGet("getmessagelist2")]
        public async Task<IActionResult> GetMessagesList2(string stime)
        {
            if (string.IsNullOrEmpty(stime))
                stime = DateTime.Now.ToLocalTime().ToString();
            //服务器时间
            DateTime nowtime = DateTime.Now.ToLocalTime();
            var listrepair_base = await _wo_repair_baseRepository.Get(x => x.isdelete == 0 && x.createtime > Convert.ToDateTime(stime));   //x => x.isdelete == false && x.createtime >= Convert.ToDateTime(stime)
            var listmaintain_base = await _wo_maintain_baserepository.Get(x => x.isdelete == false && x.createtime > Convert.ToDateTime(stime));
            var listequipmentrunning = await _wo_equipmentrunningrepository.Get(x => x.isdelete == 0 && x.createtime > Convert.ToDateTime(stime));
            var listequipment_info = (await _eqp_equipment_inforepository.Get(x => x.isdelete == 0)).ToList();
            //检查事项
            var listmatter = await _wo_mattersRepository.Get(x => x.isdelete == false);
            var list = new List<MessageListDto>();
            //维修工单
            foreach (var item in listrepair_base)
            {
                string statename = string.Empty;
                if (item.wostate < (int)EnumWorkOrderState.deal)
                    statename = "未完成";
                if (item.wostate >= (int)EnumWorkOrderState.deal)
                    statename = "已完成";
                if (item.wostate == (int)EnumWorkOrderState.hangup)
                    statename = "已挂起";
                list.Add(new MessageListDto
                {
                    id = item.id,
                    channelcode = (int)EnumOrderState.维修工单,
                    wocode = item.wocode,
                    proname = "维修工单:" + item.wocode, // + " " + item.proname,
                    title = item.wocode,
                    content = item.faultdescripe,
                    statename = statename, //工单状态
                    checkby = item.touser.ToString(),
                    createby = item.createuser,
                    createtime = item.createtime,
                });
            }
            //保养工单
            foreach (var item in listmaintain_base)
            {
                string statename = string.Empty;
                if (item.wostate < (int)EnumWorkOrderState.deal)
                    statename = "未完成";
                if (item.wostate >= (int)EnumWorkOrderState.deal)
                    statename = "已完成";
                if (item.wostate == (int)EnumWorkOrderState.hangup)
                    statename = "已挂起";
                list.Add(new MessageListDto
                {
                    id = item.id,
                    channelcode = (int)EnumOrderState.保养工单,
                    wocode = item.wocode,
                    proname = "保养工单:" + item.wocode, // + " " + item.proname,
                    title = item.wocode,
                    content = item.maintaincontent, //保养内容
                    statename = statename, //工单状态
                    //checkby = item.dealby, //接单人（转派）
                    checkby = item.maintainuser.ToString(), //接单人（转派）
                    createby = item.createby,
                    createtime = item.createtime,
                });
            }
            //设备运行工单
            foreach (var item in listequipmentrunning)
            {
                #region 检查事项
                var matternames = "";
                if (item.matterids != null && item.matterids.Count() > 0)
                {
                    var matterids = string.Join(",", item.matterids);
                    if (!string.IsNullOrEmpty(matterids))
                    {
                        var mattermodel = listmatter.FirstOrDefault(x => matterids.Contains(x.id));
                        matternames = mattermodel != null ? mattermodel.matter : "";
                    }
                }
                #endregion
                #region
                //var modelequname = listequipment_info.FirstOrDefault(x => item.equipmentid.Contains(x.id));
                //string equipmentname = string.Empty;
                //equipmentname = modelequname != null ? modelequname.equipment_name : "";
                #endregion
                string statename = string.Empty;
                if (item.wostate < (int)EnumEquipmentRunningState.deal)
                    statename = "未完成";
                if (item.wostate >= (int)EnumEquipmentRunningState.deal)
                    statename = "已完成";
                if (item.wostate == (int)EnumEquipmentRunningState.hangup)
                    statename = "已挂起";
                list.Add(new MessageListDto
                {
                    id = item.id,
                    channelcode = (int)EnumOrderState.巡检工单,
                    wocode = item.wocode,
                    //proname = "设备运行工单:" + item.wocode + " " + equipmentname,
                    proname = "设备运行工单:" + item.wocode + " 检查事项:" + matternames,
                    title = item.wocode,
                    content = "上次运维内容:" + item.checkcontent, //运维内容
                    statename = statename, //工单状态
                    checkby = item.checkby, //接单人（转派）
                    createby = item.createby,
                    createtime = item.createtime,
                });
            }
            //降序排序
            list = list.OrderByDescending(x => x.createtime).ToList();
            var obj = new
            {
                rows = list,
                nowtime = nowtime,      //当前时间
                total = list.Count, //消息数
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 消息通知类型
        /// </summary>
        public enum EnumOrderState
        {
            维修工单 = 1,
            保养工单 = 2,
            巡检工单 = 3,
            超时工单 = 4,
            配送工单 = 5,
            配送计划工单 = 6
        }
        /// <summary>
        /// 工单类型：1报修，2保养，3巡检，5配送
        /// </summary>
        public enum EnumWoType
        {
            维修 = 1,
            保养 = 2,
            巡检 = 3,
            配送 = 5,
            配送计划 = 6
        }

    }
}