using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Xsl;
using TouchSocket.Core;
using WCS.BLL.DbModels;
using WCS.BLL.Manager;
using WCS.BLL.Services.IService;
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;
using WCS.Model.ApiModel.MXL4;
using WCS.Model.ApiModel.SingleLight;
using WCS.Model.ApiModel.User;
using WCS.Model.WebSocketModel;
using static System.Formats.Asn1.AsnWriter;
using static WCS.BLL.Tool.Helper;

namespace WCS.BLL.Services.Service
{
    public class MXL4Service : IMXL4Service
    {
        public async Task<ResponseCommon<object>> sysOrderMXL4(SysOrderMXL4Request request)
        {
            try
            {
                //第一步：获取所有库位码 校验库位在数据库中是否都存在
                var storeCodeList = request.List.Select(t => t.StoreCode)
                                                .Distinct()
                                                .ToList();
                var stores = DbHelp.db.Queryable<StoreInfo>()
                                      .LeftJoin<ShelfTypeInfo>((si, sti) => si.ShelfTypeId == sti.Id)
                                      .Where((si, sti) => sti.ShelfTypeName == "液晶货架")
                                      .Where((si, sti) => storeCodeList.Contains(si.StoreCode))
                                      .Select((st, sti) => st)
                                      .ToList();
                if (stores.Count < storeCodeList.Count)
                {
                    var storeCodesInDB = stores.Select(t => t.StoreCode).ToList();
                    storeCodeList.RemoveAll(t => storeCodesInDB.Contains(t));
                    return new ResponseCommon<object>
                    {
                        Code = 200,
                        Message = $"操作失败：库位【{string.Join(",", storeCodeList)}】不存在！",
                    };
                }

                //第二步 获取库位正在进行的任务
                //模式相同视为可以继续发送任务
                var currenTasks = DbHelp.db.Queryable<CurrentTask>()
                                          .Where(t => storeCodeList.Contains(t.StoreCode))
                                          .ToList();
                var currenTasksNotThisMode = currenTasks.Where(t => t.TaskMode != request.OrderType).ToList(); ;
                if (currenTasksNotThisMode.Any())
                {
                    var task = currenTasksNotThisMode.First();
                    return new ResponseCommon<object>
                    {
                        Code = 200,
                        Message = $"操作失败：库位【{task.StoreCode}】当前在{task.TaskMode}！",
                    };
                }
                var tasks = new List<CurrentTask>();
                //生成任务数据
                foreach (var orderDetail in request.List)
                {
                    var store = stores.Where(t => t.StoreCode == orderDetail.StoreCode).First();
                    var task = new CurrentTask()
                    {
                        StoreId = store.Id,
                        StoreCode = store.StoreCode,

                        Guid = orderDetail.Guid,
                        TaskMode = request.OrderType,
                        OrderNumber = request.OrderNumber,
                        ButtonColor = request.Corlor,
                        MatCode = orderDetail.MatCode,
                        MatName = orderDetail.MatName,
                        MatSpec = orderDetail.MatSpec,
                        MatBatch = orderDetail.MatBatch,
                        Qty = orderDetail.Qty
                    };
                    tasks.Add(task);
                }
                try
                {
                    DbHelp.db.BeginTran();
                    DbHelp.db.Insertable(tasks).ExecuteCommand();
                    DbHelp.db.CommitTran();
                }
                catch (Exception ex)
                {
                    DbHelp.db.RollbackTran();
                    return new ResponseCommon<object>
                    {
                        Code = 300,
                        Message = $"操作失败：{ex.Message}"
                    };
                }
                //发送任务至各个标签
                return new ResponseCommon<object>
                {
                    Code = 200,
                    Message = "success"
                };
            }
            catch (Exception ex)
            {
                return new ResponseCommon<object>
                {
                    Code = 200,
                    Message = "操作失败：" + ex.Message,

                };
            }
        }
    }
}
