using DbCommon.BusinessCore.BaseCore;
using DbCommon.Enties.DbModels;
using Pms.DataLibrary.Models;
using Pms.DataLibrary.Order;
using Pms.Models;
using ProjectManagementSystem.Common.Core;
using ProjectManagementSystem.Common.Logger;
using ProjectManagementSystem.Common.WebApi;
using ProjectManagementSystem.Common.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjectManagementSystem.Common.Extenions;
using ProjectManagementSystem.Common.Config;
using ProjectManagementSystem.Common.Service;

namespace ProjectManagementSystem.TaskBookEvent
{
    public class TaskBookBehavior_63031 : BaseTaskBookBehaviorV2
    {
        LocationPropertyManager locationManager = new LocationPropertyManager();

        public TaskBookBehavior_63031() : base(63031, "更改步骤库位（成品发动机）")
        {
        }

        public override bool TaskBookOperator(TaskData taskDetailInfo, StepData stepInfo)
        {
            try
            {
                string wHouse = locationManager.GetById(stepInfo.WareHouseID).WareHouseCode;
                string nextLocation = PmsTaskService.Instance.QueryLocationIn(taskDetailInfo.TaskID, wHouse);

                if (string.IsNullOrEmpty(nextLocation))
                {
                    Log(taskDetailInfo, stepInfo, $"{wHouse} 仓库未找到空位");
                    return false;
                }

                Log(taskDetailInfo, stepInfo, $"检测到可以分配的位置 {nextLocation}");

                //更改库位
                bool result = true;
                int startStepId = taskDetailInfo.CurrentStepID + 1;
                int endStepId = taskDetailInfo.StepList.Max(d => d.StepID);

                for (int i = startStepId; i <= endStepId; i++)
                {
                    result &= PmsApi.UpdateStepWarehouse(taskDetailInfo.TaskID, i, nextLocation);

                    if (!result)
                    {
                        Log(taskDetailInfo, stepInfo, $"更改库位失败");
                        return false;
                    }
                }

                Log(taskDetailInfo, stepInfo, $"已更改库位 {nextLocation}");
                return true;
            }
            catch (Exception ex)
            {
                LogException(ex);
            }
            return false;
        }
    }
}
