using DbCommon.BusinessCore.BaseCore;
using DbCommon.Enties.DbModels;
using DbCommon.Extenions;
using DbCommon.Function;
using Pms.DataLibrary.Models;
using Pms.DataLibrary.Order;
using ProjectManagementSystem.Common.Log;
using ProjectManagementSystem.WebApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectManagementSystem.TaskEvent
{
    public class CTaskEvent : CTaskEventBase
    {
        public override void TaskStateChanged(TaskData currentTaskInfo, TaskData lastTaskInfo)
        {
        }
        public override void TaskFinished(TaskData taskInfo)
        {
            CLog.Instance.GetLog("Task").WriteInfo($"{taskInfo.TaskID} 任务完成");
        }

        public override void TaskCanceled(TaskData taskInfo)
        {
            CLog.Instance.GetLog("Task").WriteInfo($"{taskInfo.TaskID} 任务取消");

            RecoverLocationStatus(taskInfo);
        }

        public override void TaskExceptioned(TaskData taskInfo)
        {
            CLog.Instance.GetLog("Task").WriteInfo($"{taskInfo.TaskID} 任务异常");
        }

        private void RecoverLocationStatus(TaskData taskInfo)
        {
            string[] posArray = taskInfo.AllWarehouse.ToPosArray().Distinct().ToArray();
            for (int i = 0; i < posArray.Length; i++)
            {
                string location = posArray[i];

                var locationData = m_locationManager.QueryData(location);
                if (locationData.Status == LocationStatus.Locked)
                {
                    var statusBackup = Tools.ParseStatus(locationData.StatusBackup);
                    bool result = m_locationManager.UpdateStatus(location, statusBackup);

                    CLog.Instance.GetLog("Task").WriteInfo($"{taskInfo.TaskID} 库位恢复状态{result.ToChineseString()}：{location} {statusBackup}");
                }
            }
        }
    }
}

