using SqlSugar;
using WCS.BLL.Config;
using WCS.BLL.DbModels;
using WCS.BLL.HardWare;
using WCS.BLL.Tool;
using WCS.DAL;
using WCS.DAL.Db;
using WCS.DAL.Db.AuthDb;
using WCS.DAL.DbModels;
using WCS.Model;
using WCS.Model.ApiModel.InOutRecord;
using WCS.Model.ApiModel.MXBackgroundThread;

namespace WCS.BLL.Manager
{
    //盟讯公司后台方法
    public static class MXBackgroundThread
    {
        public static void InitBackgroundThread()
        {
            #region 定时任务:回传Mes入库出库
            Task.Run(() =>
            {
                while (true)
                {
                    //每5秒同步一次
                    Thread.Sleep(5000);
                    try
                    {
                        var records = DbHelp.db.Queryable<InOutRecord>()
                                                        .Where(t => t.OperateTime > DateTime.Now.AddDays(-3)) //只查询回传三天内数据
                                                        .Where(t => t.IsUpload == false)
                                                        .Includes(t => t.StoreInfo)
                                                        .OrderBy(t => t.Id)
                                                        .ToList();
                        //入库记录上传
                        var inventoryDetails = records.Where(t => t.Direction == DirectionEnum.入库)
                                                      .WhereIF(!string.IsNullOrEmpty(LocalFile.Config.GroupName), t => t.GroupName == LocalFile.Config.GroupName)
                                                      .ToList();
                        if (inventoryDetails != null && inventoryDetails.Count > 0)
                        {
                            for (int i = 0; i < inventoryDetails.Count; i++)
                            {
                                try
                                {
                                    //请求WMS上传入库记录
                                    var data = new InputStockInRequest
                                    {
                                        materialBar = inventoryDetails[i].MatSN,
                                        shelfCode = inventoryDetails[i].BigShelfCode,
                                        shelfX = "R" + inventoryDetails[i].R,
                                        shelfY = "C" + inventoryDetails[i].C,
                                        shelfZ = inventoryDetails[i].Wei,
                                        inUser = inventoryDetails[i].OperateUser,
                                        inTime = inventoryDetails[i].OperateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                    };
                                    Guid guid = Guid.NewGuid();
                                    var result = ApiHelp.GetDataFromHttp<ResponseCommon>(LocalFile.Config.InputStockInStr, data, "POST", true);
                                    if (result != null && (result.Code == 200))
                                    {
                                        //上传成功 更改上传状态
                                        inventoryDetails[i].IsUpload = true;
                                        DbHelp.db.Updateable(inventoryDetails[i]).ExecuteCommand();
                                    }

                                }
                                catch (Exception ex)
                                {

                                }
                                Thread.Sleep(200);
                            }
                        }

                        //出库记录上传
                        var outRecord = records.Where(t => t.Direction == DirectionEnum.出库)
                                                     .Where(t => !string.IsNullOrEmpty(t.OrderNumber))
                                                     .WhereIF(!string.IsNullOrEmpty(LocalFile.Config.GroupName), t => t.GroupName == LocalFile.Config.GroupName)
                                                     .ToList();
                        if (outRecord != null && outRecord.Count > 0)
                        {
                            for (int i = 0; i < outRecord.Count; i++)
                            {
                                try
                                {
                                    var retString = string.Empty;

                                    var data = new BunkerOutRequest()
                                    {
                                        materialBar = outRecord[i].MatSN,
                                        outType = 0,
                                        pickBillNumber = outRecord[i].OrderNumber,
                                        qty = outRecord[i].MatQty,
                                    };
                                    var result = ApiHelp.GetDataFromHttp<ResponseCommon>(LocalFile.Config.BunkerOutStr, data, "POST", true);
                                    //请求成功
                                    if (result != null && result.Code == 200)
                                    {
                                        //上传成功 更改上传状态
                                        outRecord[i].IsUpload = true;
                                        DbHelp.db.Updateable(outRecord[i]).ExecuteCommand();
                                    }

                                }
                                catch (Exception ex)
                                {

                                }
                                Thread.Sleep(200);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logs.Write("【定时任务】上传异常：" + ex.Message);
                    }
                }
            });
            #endregion

            #region 定时任务：超时退出 出库、入库、盘点模式
            Task.Run(() =>
            {
                while (true)
                {
                    //每10s一次
                    Thread.Sleep(10000);
                    try
                    {
                        #region 入库模式
                        var inStoreShelf = ShelfManager.Shelves.Where(t => t.CurrentMode == Mode.入库模式)
                                                   .Where(t => DateTime.Now - t.SetCurrentModeTime >= TimeSpan.FromMinutes(3))
                                                   .ToList();
                        foreach (var shelf in inStoreShelf)
                        {
                            shelf.GoOutInstore();
                            Logs.Write($"【定时任务：定时退出模式】货架【{shelf.ShelfCode}】超时（3min）未退出入库模式，系统后台自动退出！");
                        }
                        #endregion

                        #region 出库模式
                        //出库超过n分钟自动进入待机模式
                        var outStoreShelf = ShelfManager.Shelves.Where(t => t.CurrentMode == Mode.出库模式)
                                                  .Where(t => DateTime.Now - t.SetCurrentModeTime >= TimeSpan.FromMinutes(5))
                                                  .ToList();
                        foreach (var shelf in outStoreShelf)
                        {
                            Logs.Write($"【定时任务：定时退出模式】货架【{shelf.ShelfCode}】超时（5min）未退出出库模式，系统后台自动退出！出库单[{shelf.OrderNumber}]");
                            shelf.GoOutOutstore();
                        }
                        #endregion

                        #region 盘点模式
                        var stockTakingShelf = ShelfManager.Shelves.Where(t => t.CurrentMode == Mode.盘点模式)
                                                  .Where(t => DateTime.Now - t.SetCurrentModeTime >= TimeSpan.FromMinutes(5))
                                                  .ToList();
                        foreach (var shelf in stockTakingShelf)
                        {
                            Logs.Write($"【定时任务：定时退出模式】货架【{shelf.ShelfCode}】超时（5min）未退出盘点模式，系统后台自动退出！盘点单[{shelf.OrderNumber}]");
                            shelf.GoOutStocktaking();
                        }
                        #endregion
                    }
                    catch (Exception e)
                    {
                        Logs.Write("【定时任务：定时退出模式】" + e.Message, LogsType.Info);
                    }
                }
            });
            #endregion

            #region 定时任务：海康未扫物料码的物料更新数据
            Task.Run(() =>
            {
                while (true)
                {
                    //间隔20秒同步一次
                    Thread.Sleep(20000);
                    try
                    {
                        var inventoryDetails = DbHelp.db.Queryable<InventoryDetail>()
                                                        .Where(t => t.MatName == "暂时未知")
                                                        .Where(t => t.InstoreTime > DateTime.Now.AddDays(-3))
                                                        .ToList();
                        if (inventoryDetails != null && inventoryDetails.Count > 0)
                        {
                            for (int i = 0; i < inventoryDetails.Count; i++)
                            {
                                try
                                {
                                    //请求WMS获取物料的信息
                                    var request = new QueryBybarRequest()
                                    {
                                        materialBar = inventoryDetails[i].MatSN
                                    };
                                    var result = ApiHelp.GetDataFromHttp<QueryBybarResponse>(LocalFile.Config.QueryBybar, request, "POST", true);
                                    if (result != null && (result.code == 200) && result.data != null && result.data.Count() > 0)
                                    {
                                        //查询成功 更改数值
                                        var instoreDto = result.data.FirstOrDefault();
                                        inventoryDetails[i].MatCode = instoreDto.materialCode;
                                        inventoryDetails[i].MatName = instoreDto.materialName;
                                        inventoryDetails[i].MatBatch = instoreDto.batchNo;
                                        inventoryDetails[i].MatSpec = instoreDto.materialSpec;
                                        inventoryDetails[i].MatQty = (int)instoreDto.materialQty;
                                        DbHelp.db.Updateable(inventoryDetails[i]).ExecuteCommand();
                                    }

                                }
                                catch (Exception ex)
                                {

                                }
                                Thread.Sleep(500);
                            }
                        }



                    }
                    catch (Exception ex)
                    {
                        Logs.Write("【定时任务】更新海康物料信息异常：" + ex.Message);
                    }

                    Thread.Sleep(3000);
                    try
                    {
                        var inventoryDetails = DbHelp.db.Queryable<InventoryDetail>()
                                                       .Where(t => t.WarehouseCode == null)
                                                       .Where(t => t.InstoreTime > DateTime.Now.AddDays(-30))
                                                       .ToList();
                        if (inventoryDetails != null && inventoryDetails.Count > 0)
                        {
                            for (int i = 0; i < inventoryDetails.Count; i++)
                            {
                                try
                                {
                                    var url = $"http://192.168.2.23:9213/integrate/hkwsInventoryDetail/selectMaterialBar?materialBar={inventoryDetails[i].MatSN}";
                                    var result = ApiHelp.GetDataFromHttp<SelectMaterialBarResponse>(url, null, "POST", false);
                                    if (result != null && result.code == 200 && result.data != null && !string.IsNullOrEmpty(result.data.warehouseCode))
                                    {
                                        //查询成功 更改数值
                                        inventoryDetails[i].WarehouseCode = result.data.warehouseCode;
                                        DbHelp.db.Updateable(inventoryDetails[i]).ExecuteCommand();
                                    }

                                }
                                catch (Exception ex)
                                {
                                    Logs.Write("【定时任务】更新仓库代码异常：" + ex.Message);
                                }
                                Thread.Sleep(500);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            });
            #endregion

            #region 定时任务：监测警示灯关灯机制
            //判断灯颜色和模式是否对应
            Task.Run(() =>
            {
                while (true)
                {
                    //间隔5秒查询一次
                    Thread.Sleep(5000);
                    try
                    {
                        //待机模式未关灯
                        var shelves = ShelfManager.Shelves.Where(t => t.CurrentMode == Mode.待机模式 && t.LightColor != WarningLight.LightColorEnum.关闭)
                                                          .Where(t => t.SetCurrentModeTime < DateTime.Now.AddSeconds(-5))
                                                          .ToList();
                        foreach (var shelf in shelves)
                        {
                            try
                            {
                                if (shelf is SmartShelf)
                                {
                                    var smartShelf = (SmartShelf)shelf;
                                    if(smartShelf.IsWarning == false)
                                    {
                                        smartShelf?.WarningLight.CloseLight(smartShelf.TcpCleint);
                                        Logs.Write($"【定时任务】：监测警示灯关灯机制，关【{shelf.ShelfCode}】灯发送指令成功！");
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Logs.Write($"【定时任务】：监测警示灯关灯机制，关【{shelf.ShelfCode}】灯发生异常" + ex.Message);
                            }
                        }

                        //出库模式未亮灯
                        var outShelves = ShelfManager.Shelves.Where(t => t.CurrentMode == Mode.出库模式 && t.LightColor == WarningLight.LightColorEnum.关闭)
                                            .Where(t => t.SetCurrentModeTime < DateTime.Now.AddSeconds(-5))
                                            .ToList();
                        foreach (var shelf in outShelves)
                        {
                            try
                            {
                                if (shelf is SmartShelf)
                                {
                                    var smartShelf = (SmartShelf)shelf;
                                    smartShelf?.WarningLight.GreenLight(smartShelf.TcpCleint);
                                    Logs.Write($"【定时任务】：监测警示灯关灯机制，出库开灯【{shelf.ShelfCode}】发送指令成功！");
                                }
                            }
                            catch (Exception ex)
                            {
                                Logs.Write($"【定时任务】：监测警示灯关灯机制，出库开灯【{shelf.ShelfCode}】发生异常" + ex.Message);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logs.Write("【定时任务】：监测警示灯关灯机制发生异常" + ex.Message);
                    }
                }
            });
            #endregion
        }

        /// <summary>
        /// 发送钉钉消息
        /// </summary>
        /// <param name="msg">发送的消息内容</param>
        /// <param name="errMsg">错误信息</param>
        /// <param name="idList">工号列表</param>
        /// <returns></returns>
        public static bool SendDingDingMsg(string msg, List<string> idList, ref string errMsg)
        {
            try
            {
                #region 获取所有工程研发人员
                var list = AuthDbHelp.db.Queryable<UserBase>().Where(t => t.IsGCYF)
                                                              .Select(t => t.LoginName)
                                                              .ToList();
                #endregion
                string ids = string.Join(",", list);
                string url = "http://192.168.2.23:9213/integrate/cmccMonitor/rateAlertByCMCC?" + $"context={msg}&messageType=软件管理平台&username={ids}";
                #region 调用接口请求发送钉钉消息
                var Result = ApiHelp.GetDataFromHttp<MXMesResponseCommon>(url, null, "GET");
                if (Result != null && Result.code != 200)
                {
                    errMsg = Result.msg;
                    return false;
                }
                return true;
                #endregion

            }
            catch (Exception ex)
            {
                errMsg = "接口调用失败";
                return false;
            }
        }
    }
}
