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

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

        public TaskBookBehavior_63004() : base(63004, "库位AGV扫码（LES标签校验）")
        {
        }
        public TaskBookBehavior_63004(int behavior, string remark) : base(behavior, remark)
        {
        }

        public override bool TaskBookOperator(TaskData taskDetailInfo, StepData stepInfo)
        {
            try
            {
                //可调用接口放行
                var dict = CacheStringToObject.ReleaseAgvDtoDict;
                if (dict.ContainsKey(stepInfo.WareHouseID))
                {
                    var releaseAgvData = dict[stepInfo.WareHouseID];
                    if (releaseAgvData.DataValid)
                    {
                        releaseAgvData.Status = 1;

                        PmsApi.SetCarrierLogicValues(taskDetailInfo.Carrier, 10, new int[] { 0 });
                        PmsApi.SetCarrierLogicValues(taskDetailInfo.Carrier, 8, new int[] { 0 });

                        Log(taskDetailInfo, stepInfo, $"已等待手动强制放行");
                        return true;
                    }
                }


                int id = taskDetailInfo.Carrier;
                if (!DeviceControl.Instance.Communication.InfoVcuDictionary.ContainsKey(id))
                {
                    Log(taskDetailInfo, stepInfo, "获取VCU扫码数据失败");
                    PmsApi.SetCarrierLogicValues(taskDetailInfo.Carrier, 10, new int[] { 1 });
                    return false;
                }

                var data = DeviceControl.Instance.Communication.InfoVcuDictionary[id];
                if (!data.DataValid)
                {
                    Log(taskDetailInfo, stepInfo, $"获取VCU扫码数据超时，最近更新时间：{data.LastUpdateTime.ToString("yyyy-MM-dd HH:mm:ss")} {data.ScanMessage}");
                    PmsApi.SetCarrierLogicValues(taskDetailInfo.Carrier, 10, new int[] { 1 });
                    return false;
                }


                if (string.IsNullOrEmpty(data.ScanMessage))
                {
                    Log(taskDetailInfo, stepInfo, "获取VCU扫码数据为空");
                    PmsApi.SetCarrierLogicValues(taskDetailInfo.Carrier, 10, new int[] { 1 });
                    return false;
                }

                if (data.ScanMessage.Length > 50)
                {
                    Log(taskDetailInfo, stepInfo, $"获取VCU扫码数据长度超限制 {data.ScanMessage}");
                    PmsApi.SetCarrierLogicValues(taskDetailInfo.Carrier, 10, new int[] { 1 });
                    return false;
                }

                PmsApi.SetCarrierLogicValues(taskDetailInfo.Carrier, 10, new int[] { 0 });

                var mData = materialBindingManager.GetById(taskDetailInfo.TaskID);
                if (mData != null)
                {
                    string targetBarcode = GetTargetBarcode(mData);

                    if (targetBarcode != data.ScanMessage)
                    {
                        var setResult = PmsApi.SetCarrierLogicValues(taskDetailInfo.Carrier, 8, new int[] { 1 });

                        Log(taskDetailInfo, stepInfo, $"校验物料扫码失败，设置扫码报警{setResult.ToChineseString()} 期望{targetBarcode} 实际{data.ScanMessage}");
                        return false;
                    }

                    var setResult2 = PmsApi.SetCarrierLogicValues(taskDetailInfo.Carrier, 8, new int[] { 0 });
                    Log(taskDetailInfo, stepInfo, $"校验物料扫码成功，取消扫码报警{setResult2.ToChineseString()} 期望{targetBarcode} 实际{data.ScanMessage}");
                }


                var locationData = locationManager.GetById(stepInfo.WareHouseID);
                if (locationData == null)
                {
                    Log(taskDetailInfo, stepInfo, $"查询库位数据失败 {stepInfo.WareHouseID}");
                    return false;
                }

                locationData.MaterialId = data.ScanMessage;
                bool result = locationManager.Update(locationData);

                Log(taskDetailInfo, stepInfo, $"更新库位AGV扫码{result.ToChineseString()} {data.ScanMessage}");
                return result;
            }
            catch (Exception ex)
            {
                LogException(ex);
            }
            return false;
        }

        public virtual string GetTargetBarcode(MaterialBinding materialBinding)
        {
            return materialBinding.MaterialBarcode;
        }
    }
}
