using MesServerWork;
using MisDataFunDll;
using System;
using System.Data;
using WebApi;

namespace MesServerFunctions
{
    partial class FunctionMES
    {
        /// <summary>
        /// 请求退料
        /// </summary>
        /// <param name="e"></param>
        private void RequestReturnMaterial(object e)
        {
            try
            {
                DeviceDriver_BasicData.CustomeEvetnArgs msgEvent = (DeviceDriver_BasicData.CustomeEvetnArgs)e;
                string OpName = Convert.ToString(msgEvent.OpName);
                int tagValue = Convert.ToInt32(msgEvent.TagValue);
                string msg;

                if (tagValue == 1)
                {
                    // 记录退料请求状态
                    MisDataFun.Location_MIS_MOBY_Insert(OpName, "RequestReturnMaterial", "1");
                    MisDataFun.Location_MIS_MOBY_Insert(OpName, "配送类型", "3");

                    // 调用退料接口
                    // deliveryType: 1退托盘，2叫料，3送料，4转序
                    DataTable outType = MisDataFun.GetRequestReturnMaterials_Type(OpName, "3");
                    string sendType = outType.Rows[0]["type"].ToString();
                    bool isOk;
                    if (sendType == "4")
                    {
                        // 调用转序接口 走转序流程
                        string EngineID = DateTime.Now.ToString("yyyyMMddHHmm");
                        string EngineType = "NONE";
                        DataTable nextDT = MisDataFun.Rrunning_GetNextStoreData(OpName, EngineID, EngineType);
                        string targetStoreCode = nextDT.Rows[0]["目标库位号"].ToString();
                        string targetProcessCode = nextDT.Rows[0]["目标工序号"].ToString();
                        string targetProcess = nextDT.Rows[0]["目标工序"].ToString();

                        // 1. 调用AGV转序接口
                        var agvResult = CALL_Inerface_DataHandle.CALL_Inerface_MaterialTransfer(OpName, targetStoreCode);
                        int agvCode = 500;
                        int.TryParse(agvResult["code"]?.ToString() ?? "500", out agvCode);

                        if (agvCode != 200)
                        {
                            // AGV调度失败
                            isOk = false;
                            msg = $"【{OpName}】AGV调度失败：{agvResult["message"]?.ToString() ?? "未知错误"}";
                        }
                        else
                        {
                            // 2. AGV调度成功，执行转序存储过程
                            var param = new System.Data.SqlClient.SqlParameter[] {
                                new System.Data.SqlClient.SqlParameter("@库位号", OpName),
                                new System.Data.SqlClient.SqlParameter("@产品编号", EngineID),
                                new System.Data.SqlClient.SqlParameter("@产品型号", EngineType),
                                new System.Data.SqlClient.SqlParameter("@目标库位号", targetStoreCode),
                                new System.Data.SqlClient.SqlParameter("@目标工序", targetProcess),
                                new System.Data.SqlClient.SqlParameter("@目标工序号", targetProcessCode)
                            };

                            DataLinkMesWork2.DataAccess2.ExecuteStoredProcedure("XD_磨合_开始下一序", ref param, out string errMessage);

                            if (!string.IsNullOrEmpty(errMessage))
                            {
                                isOk = false;
                                msg = $"【{OpName}】AGV调度成功，但XD_磨合_开始下一序存储过程执行失败：{errMessage}";
                            }
                            else
                            {
                                isOk = true;
                                msg = $"【{OpName}】转序操作成功";
                            }
                        }
                    }
                    else
                    {
                        isOk = CALL_Inerface_DataHandle.CALL_Inerface_CallMaterial(OpName, sendType);

                    }
                    if (isOk)
                    {
                        // 发送消息通知
                        msg = $"【{OpName}】请求退料成功";
                        MIS_BASE.WritePLC(306, OpName, 1); // 任务状态反馈
                    }
                    else
                    {
                        msg = $"【{OpName}】请求退料失败";
                        MIS_BASE.WritePLC(306, OpName, 2); // 任务状态反馈
                    }


                    SendMessage.AsyncSendMessage_Notice(OpName, msg);
                    MyLog4Net.MyLogHelper.Info("RequestReturnMaterial", msg);
                }
                else
                {
                    MisDataFun.Location_MIS_MOBY_Insert(OpName, "RequestReturnMaterial", "0");
                    MIS_BASE.WritePLC(301, OpName, false); // 请求进入
                    MIS_BASE.WritePLC(302, OpName, false); // 托盘到位 器具放置完毕
                    MIS_BASE.WritePLC(303, OpName, false); // AGV已离开
                    MIS_BASE.WritePLC(305, OpName, "0");   // 比对结果
                    MIS_BASE.WritePLC(304, OpName, false); // 比对完成
                    MIS_BASE.WritePLC(306, OpName, 0); // 任务状态反馈
                }
            }
            catch (Exception err)
            {
                MisDataSaveDate.FuntionMesRead.Alarm_SaveFileLog4Error(System.Reflection.MethodBase.GetCurrentMethod().Name, e, "Fun1054", err);
            }
        }
    }
}