using Microsoft.EntityFrameworkCore;
using Serilog;
using System.Drawing;
using WMS_GIRAF_Interface.Data;
using WMS_GIRAF_Interface.Entities;
using WMS_GIRAF_Interface.Helper;
using WMS_GIRAF_Interface.Models;
using WMS_GIRAF_Interface.Repositories.Implement;
using WMS_GIRAF_Interface.Repositories.Interface;
using static WMS_GIRAF_Interface.Helper.Enum;
using Enum = WMS_GIRAF_Interface.Helper.Enum;

namespace WMS_GIRAF_Interface.TaskServices;

public class ManageTaskService(
    MichelinDbContext context,
    IManageMainRepository mangeMainRepository,
    IIoControlRepository ioControlRepository,
    HelperService helperService,
    IWhCellRepository whCellRepository)
{
    /// <summary>
    /// 生成入库到line任务逻辑/一楼手工入库的任务逻辑
    /// </summary>
    /// <param name="inputRequest">产品信息</param>
    /// <param name="startPostNumber">起始post number</param>
    /// <param name="supportType">类型信息</param>
    /// <param name="isBlocked">block属性</param>
    /// <param name="trans">事务属性</param>
    /// <param name="IssendControl">是否生成控制任务</param>
    /// <param name="sResult">返回信息</param>
    public bool CreateInputTaskFromGiraf( InputRequest.Product inputRequest,string startPostNumber,int endLaneWay,string sku,string supportType,string requestNumber,bool isBlocked,bool trans,bool IssendControl ,out string sResult)
    {
        bool bResult = true;
        sResult = string.Empty;
        //判断当前胎号是否有任务
        var cellInfoStart = context.Wh_Cell.FirstOrDefault(x => x.CELL_CODE == startPostNumber);
        //获取起点信息
        if (cellInfoStart != null)
        {
           
            var manageMain = mangeMainRepository.GetManageMain("barcode", inputRequest.identifier);
            if (manageMain != null)
            {
                //更新当前任务信息
                manageMain.END_CELL_ID = endLaneWay;
                manageMain.requestNumber = requestNumber;
                manageMain.CELL_MODEL = supportType;
                manageMain.START_CELL_ID = cellInfoStart.CELL_ID;
                manageMain.LOTNUMBER = sku;
                manageMain.POPULATIONNUMBER = inputRequest.productClass;
                manageMain.keepRequestInMemoryEvenIfLackOfProductIssue = true;
                manageMain.keepRequestInMemoryEvenIfMechanicalIssue = true;
                bResult = mangeMainRepository.UpdateManageMain(manageMain);

            }
            else
            {
                //创建任务
                var transaction = context.Database.BeginTransaction();

                var newManageMain = new MANAGE_MAIN
                {
                    STOCK_BARCODE = inputRequest.identifier,
                    requestNumber = requestNumber,
                    MANAGE_TYPE_CODE = cellInfoStart.CELL_MODEL == "DP" ? "ManageLineMove" : "ManageInlocal",
                    MANAGE_STATUS = "WaitingSend",
                    MANAGE_OPERATOR = "AUTO",
                    MANAGE_BEGIN_TIME = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    CELL_MODEL = supportType,
                    START_CELL_ID = cellInfoStart.CELL_ID,
                    END_CELL_ID = endLaneWay,
                    LOTNUMBER = sku,
                    POPULATIONNUMBER = inputRequest.productClass,
                    keepRequestInMemoryEvenIfLackOfProductIssue = true,
                    keepRequestInMemoryEvenIfMechanicalIssue = true,

                };
                bResult = mangeMainRepository.AddManageMain(newManageMain, out int manageId);
                if (bResult)
                {
                    //TODO:添加日志
                    Log.Information($"Create input task success! Stock barcode :{inputRequest.identifier}");
                }
                else
                {
                    //TODO:添加错误信息
                }

            }
        }
        else
        {
            //起点信息出问题
        }

        return bResult;
    }

    public bool CreateOutputTaskFromGiraf(MANAGE_MAIN manageMain,int startCellId,bool trans,out string sResult)     
    {
        bool bResult = true;
        sResult = string.Empty;
        
            //验证当前出库任务信息是否正确
            if (manageMain.STOCK_BARCODE != null && mangeMainRepository.GetManageMain("barcode",manageMain.STOCK_BARCODE)!=null)
            {
                bResult = false;
                sResult = "This tire barcode already have task in WMS";
                return bResult;
            }

            if (whCellRepository.GetCell(startCellId)==null)
            {
                bResult = false;
                sResult = "The start position is not exist in WMS database";
                return bResult;
            }

            var startCellInfo = whCellRepository.GetCell(startCellId);

            if (whCellRepository.GetCell(manageMain.END_CELL_ID)==null)
            {
                bResult = false;
                sResult = "The end position is not exist in WMS database";
                return bResult;
            }
            var endCellInfo = whCellRepository.GetCell(manageMain.END_CELL_ID);


            helperService.BeginTransaction(trans);
            try
            {
                //更新货位状态

                if (whCellRepository.UpdateCellStatusAndRunStatus(manageMain.START_CELL_ID, string.Empty, Enum.RunStatus.Selected.ToString(), out  sResult)!=true)
                {
                    bResult = false;
                    sResult= "Update run status failed: "+sResult;
                    helperService.RollBackTransaction(trans);
                    return bResult;
                }

                mangeMainRepository.AddManageMain(manageMain,out int manageId);
                if (manageId!=0)
                {
                    Log.Information($"Add unloading task success! tire number :{manageMain.STOCK_BARCODE}");
                    //生成控制任务
                        
                        int controlTaskType =
                            $"{startCellInfo?.CELL_TYPE}-{endCellInfo?.CELL_TYPE}"
                                    .ToLower() switch
                                {
                                    "station-cell" => //站台-货位-入
                                        Convert.ToInt32(ControlType.Up.ToString("d")),
                                    "cell-station" => //货位-站台-出
                                        Convert.ToInt32(ControlType.Down.ToString("d")),
                                    "cell-cell" => //货位-货位-移
                                        Convert.ToInt32(ControlType.Move.ToString("d")),
                                    "station-station" => //站台-站台-移
                                        Convert.ToInt32(ControlType.MoveStation.ToString("d")),
                                    _ => 0
                                };
                        var ioControlTask = new IO_CONTROL()
                        {
                            MANAGE_ID = manageMain.MANAGE_ID,
                            STOCK_BARCODE = manageMain.STOCK_BARCODE,
                            //mIO_CONTROL.CELL_GROUP = mEND_CELL.CELL_GROUP;
                            CONTROL_TASK_LEVEL = string.IsNullOrEmpty(manageMain.MANAGE_LEVEL) ? "0" : manageMain.MANAGE_LEVEL,
                            PRE_CONTROL_STATUS = string.Empty,
                            CONTROL_TASK_TYPE = controlTaskType,
                            START_DEVICE_CODE = startCellInfo?.CELL_CODE,
                            END_DEVICE_CODE = endCellInfo?.CELL_CODE,
                            CONTROL_BEGIN_TIME = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                            POPULATION = manageMain.POPULATIONNUMBER,
                            //单叉状态25 双叉状态0 string.IsNullOrEmpty(mMANAGE_MAIN.MANAGE_FORK) || !mMANAGE_MAIN.MANAGE_FORK.Equals("1") ? 0 : 25;
                            CONTROL_STATUS = 0,
                            CONTROL_REMARK = manageMain.MANAGE_REMARK,
                            START_WAREHOUSE_CODE = "1",
                            END_WAREHOUSE_CODE = "1",
                            targetOutputDateInUtc = manageMain.TargetOutputDateInUtc.ToString(),
                            requestNumber = manageMain.requestNumber,
                            keepRequestInMemoryEvenIfLackOfProductIssue = manageMain.keepRequestInMemoryEvenIfLackOfProductIssue.ToString(),
                            keepRequestInMemoryEvenIfMechanicalIssue = manageMain.keepRequestInMemoryEvenIfMechanicalIssue.ToString(),
                            RELATIVE_CONTROL_ID = startCellInfo?.LOGIC_ID
                        };
                        bResult = ioControlRepository.AddIoControlTask(ioControlTask, out int? controlId);
                        if (bResult)
                        {
                            manageMain.MANAGE_STATUS = ManageStatus.WaitingExecute.ToString();
                            mangeMainRepository.UpdateManageMain(manageMain);
                            Log.Information($"Create unloading control task OK;update manage task status;tire barcode:{manageMain.STOCK_BARCODE}");
                        }
                        else
                        {
                            bResult = false;
                            sResult = $"WMS can not Create control task for tire barcode {manageMain.STOCK_BARCODE}";
                            return false;
                        }

                }
                else
                {
                    bResult = false;
                    sResult = $"Add unloading task failed!tire barcode is {manageMain.STOCK_BARCODE}";
                    helperService.RollBackTransaction(trans);   
                    return bResult;
                }

            }
            catch(Exception e)
            {
                Log.Fatal($"Create unloading task failed!Reason:{e.Message}");
                helperService.RollBackTransaction(trans);
            }
            finally
            {
                if (bResult)
                {
                    helperService.CommitTransaction(trans);
                }
                else
                {
                    helperService.RollBackTransaction(trans);
                }
                
            }

            return bResult;

    }
}