using System;
using System.Data;
using System.Threading;
using System.Xml.Linq;

using MesServerWork;
using MisDataFunDll;

namespace MesServerFunctions
{
    partial class FunctionMES
    {
        /// <summary>
        /// PLC物料扫码校验
        /// 扫码内容格式：采购订单号|采购行号|物料代码|物料批次号|物料流水号|图号
        /// 示例：GDD030226032500001|10|123800510000065|20260326|00001|8KA.510.10074
        /// </summary>
        /// <param name="e"></param>
        public void MaterialsVerify(object e)
        {

            try
            {
                DeviceDriver_BasicData.CustomeEvetnArgs msgEvent = (DeviceDriver_BasicData.CustomeEvetnArgs)e;
                string OpName = Convert.ToString(msgEvent.OpName);
                int tagValue = Convert.ToInt32(msgEvent.TagValue);
                //判断PLC机型与MES机型是否一致
                if (tagValue == 1)
                {
                    int EngineTypeID = 0;//机型代码
                    int PartPallet_Code = 0;//托盘编号
                    string EngineType = "";//机型
                    string OrderForm = "";
                    MIS_BASE.Read_EngineID(OpName, out string PLCEngineID);
                    MIS_BASE.Read_EngineID_MES(OpName, out string MESEngineID);
                    string EngineID = string.IsNullOrEmpty(PLCEngineID) ? MESEngineID : PLCEngineID;

                    if (string.IsNullOrEmpty(EngineID))
                    {
                        string msg = $"【{OpName}】PLC与MES产品编号点位均为空，继续按空产品信息保存物料扫码记录！";
                        MisDataSaveDate.Helper.ApiLogHelper.SaveMesLog(OpName, "MaterialsVerify " + msg, MisDataSaveDate.Helper.MesLogType.ERROR);
                    }
                    else
                    {
                        DataTable planDt = MisDataFun.XD_GetPlanInfoByEngineID(EngineID);
                        if (planDt.Rows.Count > 0)
                        {
                            OrderForm = planDt.Rows[0]["订单号"].ToString();
                            EngineType = planDt.Rows[0]["产品型号"].ToString();
                        }
                        else
                        {
                            string msg = $"【{OpName}】产品:{EngineID} 未在生产计划_派工订单_执行计划中查询到记录，继续保存物料扫码记录！";
                            MisDataSaveDate.Helper.ApiLogHelper.SaveMesLog(OpName, "MaterialsVerify " + msg, MisDataSaveDate.Helper.MesLogType.ERROR);
                        }
                    }

                    int MaterialsTypeCode = Convert.ToInt32(MIS_BASE.ReadPLC(201, OpName));
                    string MaterialsCode = MIS_BASE.ReadPLC(40, OpName).ToString();

                    string purchaseOrderNo = "";
                    string purchaseLineNo = "";
                    string materialCode = "";
                    string materialBatchNo = "";
                    string materialSerialNo = "";
                    string drawingNo = "";
                    int segmentCount = ParseMaterialsCode(MaterialsCode, out purchaseOrderNo, out purchaseLineNo, out materialCode, out materialBatchNo, out materialSerialNo, out drawingNo);
                    if (segmentCount != 6)
                    {
                        string warnMsg = $"【{OpName}】产品:{EngineID} | 物料码:{MaterialsCode} | 物料类型:{MaterialsTypeCode.ToString()} 物料码段数异常({segmentCount})，预期6段(采购订单号|采购行号|物料代码|物料批次号|物料流水号|图号)！";
                        MisDataSaveDate.Helper.ApiLogHelper.SaveMesLog(OpName, "MaterialsVerify " + warnMsg, MisDataSaveDate.Helper.MesLogType.ERROR);
                    }

                    DataTable dt = MisDataFun.XD_MaterialsVerify(OpName, EngineID, MaterialsCode, MaterialsTypeCode,
                        purchaseOrderNo, purchaseLineNo, materialCode, materialBatchNo, materialSerialNo, drawingNo);
                    int result = Convert.ToInt32(dt.Rows[0]["result"]);
                    if (result == 1)
                    {
                        MIS_BASE.WritePLC(95, OpName, 1); // 物料校验成功
                    }
                    else
                    {
                        MIS_BASE.WritePLC(95, OpName, 2); // 物料校验失败
                        string msg = $"【{OpName}】产品:{EngineID} | 物料码:{MaterialsCode} | 物料类型:{MaterialsTypeCode.ToString()} 物料校验失败！";
                        MisDataSaveDate.Helper.ApiLogHelper.SaveMesLog(OpName, "MaterialsVerify " + msg, MisDataSaveDate.Helper.MesLogType.ERROR);
                    }
                }
                else
                {
                    MIS_BASE.WritePLC(95, OpName, 0); // 物料验证结果清空
                }
            }
            catch (Exception err)
            {
                ////ApplicationLog.WriteLog(err, "Function08:EngineTypeGetOver_PLC");
            }
        }

        /// <summary>
        /// 解析物料扫码内容
        /// 格式：采购订单号|采购行号|物料代码|物料批次号|物料流水号|图号
        /// 段数不足时，剩余字段保持为空字符串。
        /// </summary>
        /// <returns>实际拆分得到的段数</returns>
        private static int ParseMaterialsCode(string code,
            out string purchaseOrderNo, out string purchaseLineNo, out string materialCode,
            out string materialBatchNo, out string materialSerialNo, out string drawingNo)
        {
            purchaseOrderNo = "";
            purchaseLineNo = "";
            materialCode = "";
            materialBatchNo = "";
            materialSerialNo = "";
            drawingNo = "";

            if (string.IsNullOrEmpty(code)) return 0;

            string[] parts = code.Split('|');
            if (parts.Length > 0) purchaseOrderNo = parts[0].Trim();
            if (parts.Length > 1) purchaseLineNo = parts[1].Trim();
            if (parts.Length > 2) materialCode = parts[2].Trim();
            if (parts.Length > 3) materialBatchNo = parts[3].Trim();
            if (parts.Length > 4) materialSerialNo = parts[4].Trim();
            if (parts.Length > 5) drawingNo = parts[5].Trim();
            return parts.Length;
        }
    }
}
