using ServiceCenter.SqlSugars;
using WCS.Entity;
using WCS.WorkEngineering.WebApi.Controllers;
using WCS.WorkEngineering.WebApi.Models.AGV.Response;
using WCS.WorkEngineering.Worlds.Logs;
using TaskStatus = WCS.Entity.TaskStatus;

namespace WCS.WorkEngineering.Extensions
{
    /// <summary>
    /// 任务扩展
    /// </summary>
    public static class TaskExtension
    {
        /// <summary>
        /// 更新任务执行记录
        /// </summary>
        /// <param name="task">任务信息</param>
        /// <param name="db">数据库上下文</param>
        /// <param name="curPoint">当前地址</param>
        /// <param name="desc">描述</param>
        public static void AddWCS_TASK_DTL(this WCS_TaskInfo task, SqlSugarHelper db, string curPoint, string desc) => task.AddWCS_TASK_DTL(db, curPoint, "", desc);

        /// <summary>
        /// 更新任务执行记录
        /// </summary>
        /// <param name="task">任务信息</param>
        /// <param name="db">数据库上下文</param>
        /// <param name="curPoint">当前地址</param>
        /// <param name="NextPoint">下一个地址</param>
        /// <param name="desc">描述</param>
        public static void AddWCS_TASK_DTL(this WCS_TaskInfo task, SqlSugarHelper db, string curPoint, string NextPoint, string desc)
        {
            db.Default.Insertable(new WCS_TaskDtl
            {
                ID = Guid.NewGuid(),
                ParentTaskCode = task.ID,
                CurPoint = curPoint,
                NextPoint = NextPoint,
                Desc = desc,
                AddWho = "WCS"
            }).SplitTable().ExecuteCommand();
        }

        /// <summary>
        /// 完成或取消任务
        /// </summary>
        /// <param name="taskInfo"></param>
        /// <param name="db"></param>
        /// <param name="world"></param>
        public static void CompleteOrCancelTasks(this WCS_TaskInfo taskInfo, SqlSugarHelper db)
        {
            if (taskInfo.Status is not Entity.TaskStatus.Finish and not Entity.TaskStatus.Cancel) throw new KnownException("任务未完成或取消，无法执行WCS_TaskInfo与WCS_TaskOld同步动作", LogLevelEnum.Mid);
            else // 任务完成或取消,进行相关同步动作
            {
                WCS_TaskOld taskOld = db.Default.Queryable<WCS_TaskOld>().SplitTable(tabs => tabs.Take(2)).Where(v => v.ID == taskInfo.ID).OrderByDescending(v => v.AddTime).First();
                if (taskOld is null) throw new KnownException($"WCS_TaskOld表中不存在任务:{taskInfo.ID}，无法执行WCS_TaskInfo与WCS_TaskOld同步动作", LogLevelEnum.Mid);
                else
                {
                    //状态
                    taskOld.Status = taskInfo.Status;
                    taskOld.Uploaded = taskInfo.Uploaded;
                    //任务号
                    taskOld.WmsTask = taskInfo.WmsTask;
                    taskOld.AgvTaskID = taskInfo.AgvTaskID;
                    taskOld.TaskGroupKey = taskInfo.TaskGroupKey;
                    taskOld.Priority = taskInfo.Priority;
                    //时间与用户
                    taskOld.AddTime = taskInfo.AddTime;
                    taskOld.AddWho = taskInfo.AddWho;
                    taskOld.StartTime = taskInfo.StartTime;
                    taskOld.EndTime = taskInfo.EedTime;
                    taskOld.EditWho = taskInfo.EditWho;
                    taskOld.EditTime = taskInfo.EditTime;
                    //条码与地址
                    taskOld.BarCode = taskInfo.BarCode;
                    taskOld.MaterialCode = taskInfo.MaterialCode;
                    taskOld.AddrFrom = taskInfo.AddrFrom;
                    taskOld.AddrTo = taskInfo.AddrTo;
                    taskOld.LastInteractionPoint = taskInfo.LastInteractionPoint;
                    taskOld.AddrNext = taskInfo.AddrNext;
                    taskOld.Tunnel = taskInfo.Tunnel;
                    taskOld.Floor = taskInfo.Floor;
                    taskOld.Device = taskInfo.Device;
                    taskOld.SrmStation = taskInfo.SrmStation;
                    //码垛信息
                    taskOld.DocID = taskInfo.DocID;
                    taskOld.PalletType = taskInfo.PalletType;
                    taskOld.ProdLine = taskInfo.ProdLine;
                    taskOld.FullQty = taskInfo.FullQty;
                    //外形信息
                    taskOld.Height = taskInfo.Height;
                    taskOld.Length = taskInfo.Length;
                    taskOld.Weight = taskInfo.Weight;
                    //手动处理备注
                    taskOld.ManualRemarks = taskInfo.ManualRemarks;

                    //更新任务历史表,删除任务当前表
                    db.Default.Updateable(taskOld).SplitTable().ExecuteCommand();
                    db.Default.Deleteable(taskInfo).ExecuteCommand();
                }
            }
        }

        /// <summary>
        ///  获取出库任务
        /// </summary>
        /// <param name="taskInfo">任务</param>
        /// <param name="db">db</param>
        /// <param name="allOutCode">可用出库站台</param>
        /// <param name="floor">楼层</param>
        /// <param name="obj">堆垛机</param>
        /// <param name="index">递归次数</param>
        /// <returns></returns>
        /// <exception cref="KnownException"></exception>
        public static WCS_TaskInfo GetOutTask(this WCS_TaskInfo taskInfo, SqlSugarHelper db, List<string> allOutCode, int floor, SRM obj, int index = 1)
        {
            //按条件先后排序获取一条排序后第一条结果1.优先级2.所在楼层与本次优先执行楼层
            var tasks = db.Default.Queryable<WCS_TaskInfo>().Where(v => v.Type == TaskType.OutDepot && v.Status == TaskStatus.WaitingToExecute)
                                                           .Where(v => allOutCode.Contains(v.SrmStation))
                                                           .OrderByDescending(v => v.Priority)
                                                           .OrderByDescending(v => v.Floor == floor ? 1 : 0)
                                                           .Take(index).ToList();
            if (!tasks.Any()) throw new KnownException($"{obj.Entity.Code}未找到出库任务", LogLevelEnum.High);
            var task = tasks.ToArray()[tasks.Count - 1];

            //判断是否是二深位任务
            var addrFrom = task.AddrFrom.Split("-");
            if (addrFrom[4] == "02")
            {
                var res = WmsApi.AddWcsMoveTask(task.ID);
                switch (res.ResData.ResType)
                {
                    case WmsApiMoveTask.允许2升位执行:
                        break;

                    case WmsApiMoveTask.执行移库任务:
                        throw new KnownException($"堆垛机{obj.Entity.Code}需要先执行移库任务", LogLevelEnum.Mid);

                    case WmsApiMoveTask.一深位有出库任务:
                        task = db.Default.Queryable<WCS_TaskInfo>()
                                         .Where(v => v.Type == TaskType.OutDepot && v.Status == TaskStatus.WaitingToExecute)
                                         .Where(v => allOutCode.Contains(v.SrmStation) && v.AddrFrom == res.ResData.CellNo)
                                         .First();
                        if (task == null) task.GetOutTask(db, allOutCode, floor, obj, index + 1);
                        break;
                };
            }

            return task;
        }

        /// <summary>
        /// 获取AGV任务ID
        /// </summary>
        /// <param name="db">db</param>
        /// <returns></returns>
        public static int GetAGVTaskId(this SqlSugarHelper db)
        {
            var id = db.Default.Queryable<WCS_AgvTaskInfo>().SplitTable(v => v.Take(1)).Max(v => v.ID);
            return id + 1;
        }
    }
}
