using DbCommon.BusinessCore.BaseCore;
using DbCommon.Enties.DbModels;
using Pms.DataLibrary.Models;
using Pms.DataLibrary.Order;
using Pms.Models;
using ProjectManagementSystem.Common.Config;
using ProjectManagementSystem.Common.Extenions;
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.Service;
using ProjectManagementSystem.Common.Core;

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

        public TaskBookBehavior_63010() : base(63010, "续接任务(回到起点)")
        {
        }

        public override bool TaskBookOperator(TaskData taskDetailInfo, StepData stepInfo)
        {
            try
            {
                string location1 = stepInfo.WareHouseID.GetLocationMember("续接任务取货点");
                if (string.IsNullOrEmpty(location1))
                {
                    Log(taskDetailInfo, stepInfo, $"未配置续接任务取货点");
                    return true;
                }

                string location2 = taskDetailInfo.StepList
                        .OrderBy(d => d.StepID)
                        .FirstOrDefault(d => !string.IsNullOrWhiteSpace(d.WareHouseID))
                        .WareHouseID;

                if (string.IsNullOrEmpty(location2))
                {
                    Log(taskDetailInfo, stepInfo, $"未找到任务放货点");
                    return true;
                }

                locationManager.UpdateStatus(location2, LocationStatus.Empty);

                PmsTaskInfoDto data = new PmsTaskInfoDto();
                data.LocationCode = location1;
                data.TargetLocationCode = location2;
                data.ParentTaskId = taskDetailInfo.TaskID;
                data.Carrier = taskDetailInfo.Carrier;

                var result = PmsTaskService.Instance.TaskAdd(data);
                if (result.code != 20000)
                {
                    Log(taskDetailInfo, stepInfo, $"续接任务失败 {result.message}");
                    return false;
                }

                //Log(taskDetailInfo, stepInfo, $"续接任务成功 {result.message}");
                System.Threading.Thread.Sleep(1000);
                return true;
            }
            catch (Exception ex)
            {
                LogException(ex);
            }
            return false;
        }
    }
}
