using MaterialTraceability.Business;
using MaterialTraceability.Entity.DAO;
using MaterialTraceability.Entity.DTO;
using MaterialTraceability.Entity.Enum;
using MaterialTraceability.Entity.UpLoad;
using MaterialTraceability.SqlSugar;
using MaterialTraceability.SqlSugar.ServiceImpl;
using MaterialTraceability.WebService;
using MaterialTraceability.WebService.MachineIntegrationServiceService;
using MaterialTraceability.WebService.MiBatchCompleteSfcAndAdujustQtyServiceService;
using MaterialTraceability.WebService.Param;
using MaterialTraceabilityUI.Common;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MaterialTraceabilityUI
{
    /// <summary>
    /// SplitSfc.xaml 的交互逻辑
    /// </summary>
    public partial class SplitSfc : UserControl
    {
        private IniFileHelper inifile = new IniFileHelper(System.Environment.CurrentDirectory + "/MesConfig/App.InI");
        private IniFileHelper inifile2 = new IniFileHelper(System.Environment.CurrentDirectory + "/App.InI");
        private IMesWebServices MesWebServices = new MesWebServicesImpl();
        private UpLoadBusiness upLoadBusiness = UpLoadBusiness.Instance;
        private AppConfigDto appConfig = AppConfigDto.Instance;
        private MaterialFeatureBusiness materialFeatureBusiness = MaterialFeatureBusiness.Instance;
       
        public SplitSfc()
        {
            InitializeComponent();
        }

        private void Split(string rfidStr,string eaStr,string sfcStr,int positionId)
        {
            LogHelperBusiness.LogInfo(String.Format("进入手动拆分处理,RFID条码:{0};放卷位膜卷号:{1};ea值:{2};位置编号:{3}", rfidStr, sfcStr, eaStr, positionId));
            MaterialTraceability.WebService.MiBatchCompleteSfcAndAdujustQtyServiceService.ModeProcessSfc modeProcessSfc = MaterialTraceability.WebService.MiBatchCompleteSfcAndAdujustQtyServiceService.ModeProcessSfc.MODE_COMPLETE_SFC_POST_DC;

            if (upLoadBusiness.JudgeResourceIsUplpadData())
            { 
                modeProcessSfc = MaterialTraceability.WebService.MiBatchCompleteSfcAndAdujustQtyServiceService.ModeProcessSfc.MODE_NONE;
            }

            miBatchCompleteSfcAndAdujustQtySfcEntity[] miBatchCompleteSfcAndAdujustQtySfcEntities = new miBatchCompleteSfcAndAdujustQtySfcEntity[]
            {
                new miBatchCompleteSfcAndAdujustQtySfcEntity()
                {
                    processLot = rfidStr,
                    qty = eaStr,
                    unit = "EA",
                }
            };
            var requestParam = new MiBatchCompleteSfcAndAdujustQtyServiceServiceParam()
            {
                url = inifile.IniReadValue("SplitSfcParam", "url"),
                site = inifile.IniReadValue("SplitSfcParam", "site"),
                sfcPre = sfcStr,
                processLotPre = "",
                operation = appConfig.operation,
                operationRevision = inifile.IniReadValue("SplitSfcParam", "operationRevision"),
                resource = appConfig.resource,
                user = inifile.IniReadValue("HandSplitSfcParam", "user"),
                loginUser = inifile.IniReadValue("HandSplitSfcParam", "user"),
                password = inifile.IniReadValue("HandSplitSfcParam", "password"),
                activity = inifile.IniReadValue("SplitSfcParam", "activity"),
                modeProcessSfc = modeProcessSfc,
                sfcList = miBatchCompleteSfcAndAdujustQtySfcEntities,
            };
            //判断是否为模切工序,上传最后一卷标识
            if (appConfig.processId == "MQ_A")
            {
                ComboBoxItem endFlag = (ComboBoxItem)this.endFlagCombox.SelectedItem;
                if (endFlag.Content.ToString() != null && endFlag.Content.ToString() != "")
                {

                    if (endFlag.Content.ToString() == "是")
                    {
                        requestParam.tailmark = "X";
                    }
                }
                else
                {
                    MessageBox.Show("请选择是否为最后一卷");
                }
            }
            LogHelperBusiness.LogInfo("MES自动拆分接口请求参数:" + JsonChange.ModeToJson(requestParam));

            Console.WriteLine("MES自动拆分接口请求参数:" + JsonChange.ModeToJson(requestParam));

            MiBatchCompleteSfcAndAdujustQtyResponse batchCompleteSfcAndAdujustQtyResponse = MesWebServices.iMiBatchCompleteSfcAndAdujustQtyServiceService(requestParam);
            LogHelperBusiness.LogInfo("MES自动拆分接口返回参数:" + JsonChange.ModeToJson(batchCompleteSfcAndAdujustQtyResponse));
            var result = batchCompleteSfcAndAdujustQtyResponse.@return;

            if (result.code > 0)
            {
                LogHelperBusiness.LogInfo("MES自动拆分接口调用失败:" + result.message);
                MessageBox.Show("手动拆分失败:" + upLoadBusiness.GetMesMessage(result.code, result.message));
            }
            else
            {
                string splitSfc = GetSfcByRfid(rfidStr);
                if (upLoadBusiness.JudgeResourceIsUplpadData())
                {
                    MessageBox.Show("手动拆分成功,完工处理ea:" + eaStr);
                    //获取拆分后的膜卷号
                    Complete(sfcStr, splitSfc, rfidStr,positionId, eaStr);
                }
                else
                {
                    MessageBox.Show("手动拆分成功ea:"+ eaStr);
                    UpdateDownRecord(positionId, rfidStr, splitSfc, eaStr);
                }
                
            }
        }

        /// <summary>
        /// 手动完工
        /// </summary>
        /// <param name="sfcStr"></param>
        /// <param name="split_sfc"></param>
        /// <param name="positionId"></param>
        private void Complete(string sfcStr, string split_sfc, string rfidStr, int positionId,string eaStr)
        {
            LogHelperBusiness.LogInfo(String.Format("进入手动完工处理,放卷位膜卷号:{0};拆分后膜卷号:{1};RFID条码:{2};位置编号:{3}", sfcStr, split_sfc, rfidStr, positionId));
            try
            {
                MachineIntegrationServiceParam machineIntegrationServiceParam = new MachineIntegrationServiceParam();
                machineIntegrationParametricData[] data = null;
                if (appConfig.processId.Contains("MQ"))
                {
                    string ccdLableAmount = ccdTextBox.Text.ToString().Trim();
                    if (StringExtension.IsBlank(ccdLableAmount))
                    {
                        MessageBox.Show("请输入CCD打标数");
                        return;
                    }
                    data = GetMqMaterialFeature(sfcStr, positionId);
                    LogHelperBusiness.LogInfo("模切物料特征数据:" + JsonChange.ModeToJson(data));
                }
                else if (appConfig.processId.Contains("LY"))
                {
                    data = GetLyMaterialFeature(positionId, sfcStr, split_sfc);
                    LogHelperBusiness.LogInfo("冷压物料特征数据:" + JsonChange.ModeToJson(data));
                }
                if (data != null)
                {
                    machineIntegrationServiceParam = new MachineIntegrationServiceParam()
                    {
                        url = inifile.IniReadValue("MachineIntegrationServiceParam", "url"),
                        site = inifile.IniReadValue("MachineIntegrationServiceParam", "site"),
                        sfc = split_sfc, //将数据上传至拆分后的膜卷号
                        operation = appConfig.operation,
                        operationRevision = inifile.IniReadValue("MachineIntegrationServiceParam", "operationRevision"),
                        activityId = inifile.IniReadValue("MachineIntegrationServiceParam", "activityId"),
                        resource = appConfig.resource,
                        dcGroup = upLoadBusiness.GerDcGroupByResource(),
                        dcGroupRevision = inifile.IniReadValue("MachineIntegrationServiceParam", "dcGroupRevision"),
                        parametricArray = data,
                        user = inifile.IniReadValue("HandSplitSfcParam", "user"),
                        loginUser = inifile.IniReadValue("HandSplitSfcParam", "user"),
                        password = inifile.IniReadValue("HandSplitSfcParam", "password"),
                        modeProcessSfc = MaterialTraceability.WebService.MachineIntegrationServiceService.ModeProcessSfc.MODE_COMPLETE_SFC_POST_DC
                    };

                    LogHelperBusiness.LogInfo("上传物料特征数据MES参数:" + JsonChange.ModeToJson(machineIntegrationServiceParam));
                    var dataCollectForSfcExResponse = MesWebServices.machineIntegration(machineIntegrationServiceParam);
                    var dataCollectForSfcExResponseResult = dataCollectForSfcExResponse.@return;
                    if (dataCollectForSfcExResponseResult.code > 0)
                    {
                        MessageBox.Show("数据上传完工失败:" + upLoadBusiness.GetMesMessage(dataCollectForSfcExResponseResult.code, dataCollectForSfcExResponseResult.message));
                    }
                    else
                    {
                        MessageBox.Show("数据上传完工成功");
                        UpdateDownRecord(positionId, rfidStr, split_sfc, eaStr);
                    }
                }
                else
                {
                    LogHelperBusiness.LogInfo("物料特征数据为null");
                }

            }
            catch (Exception ex)
            {
                LogHelperBusiness.LogInfo("手动完工异常:" + ex.Message);
            }
        }

        /// <summary>
        /// 更新下料记录
        /// </summary>
        /// <param name="positionId"></param>
        /// <param name="rfidStr"></param>
        /// <param name="sfcStr"></param>
        /// <param name="eaStr"></param>
        private async void UpdateDownRecord(int positionId,string rfidStr,string sfcStr,string eaStr)
        {
            try
            {
                Expression<Func<ProDownRecord, bool>> exp = s1 => true;
                exp = exp.And(x => x.MachineId == appConfig.machineId && x.PositionId == positionId && x.Rfid == rfidStr && x.IsProduction == 0);
                Expression<Func<ProDownRecord, object>> order = x => x.beginTime;
                ProDownRecord downRecord = await baseServices.QueryFirst(exp, order, false);

                if (downRecord != null)
                {
                    downRecord.IsProduction = 1;
                    downRecord.Sfc = sfcStr;
                    if (Convert.ToInt32(eaStr) > 1)
                    {
                        downRecord.eaValue = Convert.ToInt32(eaStr);
                    }
                    downRecord.endTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    if (await baseServices.Update(downRecord))
                    {
                        LogHelperBusiness.LogInfo(rfidStr + "手动拆分完成,下料记录更新成功:"+JsonChange.ModeToJson(downRecord));
                        //更新下料记录
                        upLoadBusiness.UpdateDownRecord(downRecord);
                    }
                    else
                    {
                        LogHelperBusiness.LogInfo(rfidStr + "下料记录更新失败");
                    }
                    RefreshDataGrid();
                }
            }catch(Exception ex)
            {
                LogHelperBusiness.LogInfo("手动完工下料记录更新异常:"+ex.Message);
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            this.beginTime.Text = DateTime.Now.ToLongDateString();
            this.endTime.Text = DateTime.Now.AddDays(1).ToLongDateString();
            if (appConfig.processId == "MQ_A")
            {
                ccdLable.Visibility = Visibility.Visible;
                ccdTextBox.Visibility = Visibility.Visible;
            }/*else if (appConfig.processId == "LY_A")
            {
                endFlagLabel.Visibility = Visibility.Visible;
                endFlagCombox.Visibility = Visibility.Visible;
            }*/
            RefreshDataGrid();
        }

        /// <summary>
        /// 获取模切物料特征数据,通过服务器获取数据=》不存在重新调用mes获取=》出现异常全部上传0
        /// </summary>
        /// <param name="sfcStr">放卷位膜卷号</param>
        /// <param name="positionId">收卷位置</param>
        /// <returns></returns>
        private machineIntegrationParametricData[] GetMqMaterialFeature(string sfcStr, int positionId)
        {

            try
            {
                MqUpLoad mqUpLoad = null;
                SqlSugarClient _db = SqlGenerator.GetMySqlInstance();
                string ccdLableAmount = ccdTextBox.Text.ToString().Trim();  // ccd打标数
               
                if (StringExtension.IsNotBlank(sfcStr))
                {
                    DataTable info = _db.Queryable<MqUpLoad>().Where(x => x.sfcStr == sfcStr && x.positionId == positionId).ToDataTable();
                    if (info.Rows.Count > 0)
                    {
                        mqUpLoad = new MqUpLoad();
                        DataRow dataRow = info.Rows[0];
                        #region mqUpLoad实体赋值
                        mqUpLoad.id = Convert.ToInt32(dataRow["id"]);
                        mqUpLoad.clientId = dataRow["clientId"].ToString();
                        mqUpLoad.resource = dataRow["resource"].ToString();
                        mqUpLoad.sfcStr = dataRow["sfcStr"].ToString();
                        mqUpLoad.operation = dataRow["operation"].ToString();
                        mqUpLoad.dcGroup = dataRow["dcGroup"].ToString();
                        mqUpLoad.upDirection = dataRow["upDirection"].ToString();
                        mqUpLoad.downDirection = dataRow["downDirection"].ToString();

                        mqUpLoad.downPosition = dataRow["downPosition"].ToString();
                        mqUpLoad.firstArticle = dataRow["firstArticle"].ToString();
                        mqUpLoad.mqMaterialFace = dataRow["mqMaterialFace"].ToString();

                        mqUpLoad.jrDirection = dataRow["jrDirection"].ToString();
                        mqUpLoad.scw = dataRow["scw"].ToString();
                        mqUpLoad.bcw = dataRow["bcw"].ToString();

                        mqUpLoad.is_success = Convert.ToInt32(dataRow["is_success"]);
                        mqUpLoad.mesReturnInfo = dataRow["mesReturnInfo"].ToString();
                        mqUpLoad.recordTime = dataRow["recordTime"].ToString();
                        mqUpLoad.s_targetcw = dataRow["s_targetcw"].ToString();
                        #endregion
                    }
                }

                if (mqUpLoad != null)
                {
                    machineIntegrationParametricData[] data = {
                        new machineIntegrationParametricData() {name ="MQ_FJFX",dataType=ParameterDataType.TEXT, value= StringExtension.IsBlank(mqUpLoad.upDirection) ? "0" : mqUpLoad.upDirection},
                        new machineIntegrationParametricData() {name ="MQ_SJFX",dataType=ParameterDataType.TEXT, value= StringExtension.IsBlank(mqUpLoad.downDirection) ? "0" :mqUpLoad.downDirection},
                        new machineIntegrationParametricData() {name ="MQ_SJZ",dataType=ParameterDataType.TEXT, value= StringExtension.IsBlank(mqUpLoad.downPosition) ? "0" :mqUpLoad.downPosition},
                        new machineIntegrationParametricData() {name ="FIRST ARTICLE",dataType=ParameterDataType.TEXT, value= mqUpLoad.firstArticle},
                        new machineIntegrationParametricData() {name ="MQ_WLMX",dataType=ParameterDataType.TEXT, value= StringExtension.IsBlank(mqUpLoad.mqMaterialFace) ? "0" :mqUpLoad.mqMaterialFace},
                        new machineIntegrationParametricData() {name ="MQ_JRLLFX",dataType=ParameterDataType.TEXT, value= StringExtension.IsBlank(mqUpLoad.jrDirection) ? "0" :mqUpLoad.jrDirection},
                        new machineIntegrationParametricData() {name ="S_CW",dataType=ParameterDataType.TEXT, value=StringExtension.IsBlank(mqUpLoad.scw) ? "0" : mqUpLoad.scw},
                        new machineIntegrationParametricData() {name ="B_CW",dataType=ParameterDataType.TEXT, value=StringExtension.IsBlank(mqUpLoad.bcw) ? "0" : mqUpLoad.bcw},
                        new machineIntegrationParametricData() {name = "CCD",dataType=ParameterDataType.TEXT, value=StringExtension.IsBlank(ccdLableAmount) ? "0" : ccdLableAmount},
                        new machineIntegrationParametricData() {name = "S_TARGETCW",dataType=ParameterDataType.TEXT, value=StringExtension.IsBlank(mqUpLoad.s_targetcw) ? "0" : mqUpLoad.s_targetcw}
                    };
                    return data;
                }
                else
                {
                    LogHelperBusiness.LogInfo("通过服务器未获取到物料特征数据,重新调用MES获取物料特征数据");
                    var info = materialFeatureBusiness.GetMQMaterialWeight(sfcStr, positionId, ccdLableAmount).Result;
                    if (info == null)
                    {
                        machineIntegrationParametricData[] data = {
                        new machineIntegrationParametricData() {name ="MQ_FJFX",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="MQ_SJFX",dataType=ParameterDataType.TEXT, value= "0"},
                        new machineIntegrationParametricData() {name ="MQ_SJZ",dataType=ParameterDataType.TEXT, value= "0"},
                        new machineIntegrationParametricData() {name ="FIRST ARTICLE",dataType=ParameterDataType.TEXT, value= "0"},
                        new machineIntegrationParametricData() {name ="MQ_WLMX",dataType=ParameterDataType.TEXT, value= "0"},
                        new machineIntegrationParametricData() {name ="MQ_JRLLFX",dataType=ParameterDataType.TEXT, value= "0"},
                        new machineIntegrationParametricData() {name ="S_CW",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="B_CW",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name = "CCD",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name = "S_TARGETCW",dataType=ParameterDataType.TEXT, value="0"}
                    };
                        return data;
                    }
                    else
                    {
                        return info;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelperBusiness.LogInfo("获取模切重量特征数据异常:" + ex.Message);
                machineIntegrationParametricData[] data = {
                        new machineIntegrationParametricData() {name ="MQ_FJFX",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="MQ_SJFX",dataType=ParameterDataType.TEXT, value= "0"},
                        new machineIntegrationParametricData() {name ="MQ_SJZ",dataType=ParameterDataType.TEXT, value= "0"},
                        new machineIntegrationParametricData() {name ="FIRST ARTICLE",dataType=ParameterDataType.TEXT, value= "0"},
                        new machineIntegrationParametricData() {name ="MQ_WLMX",dataType=ParameterDataType.TEXT, value= "0"},
                        new machineIntegrationParametricData() {name ="MQ_JRLLFX",dataType=ParameterDataType.TEXT, value= "0"},
                        new machineIntegrationParametricData() {name ="S_CW",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="B_CW",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name = "CCD",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name = "S_TARGETCW",dataType=ParameterDataType.TEXT, value="0"}
                    };
                return data;
            }
        }

        /// <summary>
        /// 获取冷压物料特征数据,通过服务器获取数据=》不存在重新调用mes获取=》出现异常全部上传0
        /// </summary>
        /// <param name="positionId"></param>
        /// <param name="sfcStr"></param>
        /// <param name="splitSfc"></param>
        /// <returns></returns>
        private machineIntegrationParametricData[] GetLyMaterialFeature(int positionId, string sfcStr, string splitSfc)
        {
            string shaftName = GetLyShaftName(positionId);
            try
            {
                LyUpLoad lyUpLoad = null;
                SqlSugarClient _db = SqlGenerator.GetMySqlInstance();
                string ccdLableAmount = ccdTextBox.Text.ToString().Trim();  // ccd打标数

                if (StringExtension.IsNotBlank(sfcStr))
                {
                    DataTable info = _db.Queryable<LyUpLoad>().Where(x => x.sfcStr == sfcStr && x.positionId == positionId).ToDataTable();
                    if (info.Rows.Count > 0)
                    {
                        DataRow dataRow = info.Rows[0];
                        lyUpLoad.id = Convert.ToInt32(dataRow["id"]);
                        lyUpLoad.sfcStr = dataRow["sfcStr"].ToString();
                        lyUpLoad.clientId = dataRow["clientId"].ToString();
                        lyUpLoad.resource = dataRow["resource"].ToString();
                        lyUpLoad.operation = dataRow["operation"].ToString();
                        lyUpLoad.dcGroup = dataRow["dcGroup"].ToString();
                        lyUpLoad.upDirection = dataRow["upDirection"].ToString();
                        lyUpLoad.downDirection = dataRow["downDirection"].ToString();
                        lyUpLoad.downPosition = dataRow["downPosition"].ToString();
                        lyUpLoad.crosswiseArea = dataRow["crosswiseArea"].ToString();
                        lyUpLoad.erectArea = dataRow["erectArea"].ToString();
                        lyUpLoad.materialFace = dataRow["materialFace"].ToString();
                        lyUpLoad.sx01 = dataRow["sx01"].ToString();
                        lyUpLoad.sx02 = dataRow["sx02"].ToString();
                        lyUpLoad.bx01 = dataRow["bx01"].ToString();
                        lyUpLoad.bx02 = dataRow["bx02"].ToString();
                        lyUpLoad.is_success = Convert.ToInt32(dataRow["is_success"]);
                        lyUpLoad.mesReturnInfo = dataRow["mesReturnInfo"].ToString();
                        lyUpLoad.recordTime = dataRow["recordTime"].ToString();
                    }
                }

                if (lyUpLoad != null)
                {
                    machineIntegrationParametricData[] data = {
                        new machineIntegrationParametricData() {name ="LY_FJFX",dataType=ParameterDataType.TEXT, value=string.IsNullOrEmpty(lyUpLoad.upDirection)?"0":lyUpLoad.upDirection},
                        new machineIntegrationParametricData() {name ="LY_SJFX",dataType=ParameterDataType.TEXT, value=string.IsNullOrEmpty(lyUpLoad.downDirection)?"0":lyUpLoad.downDirection},
                        new machineIntegrationParametricData() {name ="LY_SJZ",dataType=ParameterDataType.TEXT, value=string.IsNullOrEmpty(lyUpLoad.downPosition)?"0":lyUpLoad.downPosition},
                        new machineIntegrationParametricData() {name ="LY_HXMQ",dataType=ParameterDataType.TEXT, value=string.IsNullOrEmpty(lyUpLoad.crosswiseArea)?"0":lyUpLoad.crosswiseArea},
                        new machineIntegrationParametricData() {name ="LY_ZXMQ",dataType=ParameterDataType.TEXT, value=string.IsNullOrEmpty(lyUpLoad.erectArea)?"0":lyUpLoad.erectArea},
                        new machineIntegrationParametricData() {name ="LY_WLMX",dataType=ParameterDataType.TEXT, value=string.IsNullOrEmpty(lyUpLoad.materialFace)?"0":lyUpLoad.materialFace},
                        new machineIntegrationParametricData() {name ="LY_S_X01",dataType=ParameterDataType.TEXT, value=string.IsNullOrEmpty(lyUpLoad.sx01)?"0":lyUpLoad.sx01},
                        new machineIntegrationParametricData() {name ="LY_S_X02",dataType=ParameterDataType.TEXT, value=string.IsNullOrEmpty(lyUpLoad.sx02)?"0":lyUpLoad.sx02},
                        new machineIntegrationParametricData() {name ="LY_B_X01",dataType=ParameterDataType.TEXT, value=string.IsNullOrEmpty(lyUpLoad.bx01)?"0":lyUpLoad.bx01},
                        new machineIntegrationParametricData() {name ="LY_B_X02",dataType=ParameterDataType.TEXT, value=string.IsNullOrEmpty(lyUpLoad.bx02)?"0":lyUpLoad.bx02},
                        new machineIntegrationParametricData() {name ="S_TARGETCW",dataType=ParameterDataType.TEXT, value=string.IsNullOrEmpty(lyUpLoad.s_targetcws)?"0":lyUpLoad.s_targetcws},
                    };
                    return data;
                }
                else
                {
                    LogHelperBusiness.LogInfo("通过服务器未获取到物料特征数据,重新调用MES获取物料特征数据");
                    var info = materialFeatureBusiness.GetLYMaterialWeight(shaftName, positionId.ToString(), sfcStr, splitSfc).Result;
                    if (info == null)
                    {
                        machineIntegrationParametricData[] data = {
                        new machineIntegrationParametricData() {name ="LY_FJFX",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="LY_SJFX",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="LY_SJZ",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="LY_HXMQ",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="LY_ZXMQ",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="LY_WLMX",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="LY_S_X01",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="LY_S_X02",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="LY_B_X01",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="LY_B_X02",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="S_TARGETCW",dataType=ParameterDataType.TEXT, value="0"},

                        };
                        
                        return data;
                    }
                    else
                    {
                        return info;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelperBusiness.LogInfo("获取冷压重量特征数据异常:" + ex.Message);
                machineIntegrationParametricData[] data = {
                        new machineIntegrationParametricData() {name ="LY_FJFX",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="LY_SJFX",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="LY_SJZ",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="LY_HXMQ",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="LY_ZXMQ",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="LY_WLMX",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="LY_S_X01",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="LY_S_X02",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="LY_B_X01",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="LY_B_X02",dataType=ParameterDataType.TEXT, value="0"},
                        new machineIntegrationParametricData() {name ="S_TARGETCW",dataType=ParameterDataType.TEXT, value="0"},
                        };
                return data;
            }
        }


        /// <summary>
        /// 通过RFID获取SFC
        /// </summary>
        /// <param name="rfidStr"></param>
        /// <returns></returns>
        private string GetSfcByRfid(string rfidStr)
        {
            string sfcStr = "";
            ProcessLotServiceWSServiceParam processLotServiceWSServiceParam = new ProcessLotServiceWSServiceParam()
            {
                //url = "http://lymesa.catlbattery.com:8103/manufacturing-papiservices/ProcessLotServiceWSService?wsdl",
                //site = "2100",
                url = inifile.IniReadValue("ProcessLotServiceWSServiceParam", "url"),
                site = inifile.IniReadValue("ProcessLotServiceWSServiceParam", "site"),
                processlotref = String.Format("ProcessLotBO:2100,{0}", rfidStr)
            };

            try
            {
                LogHelperBusiness.LogInfo("MES获取膜卷号接口请求参数:" + JsonChange.ModeToJson(processLotServiceWSServiceParam));
                if (appConfig.isMesFlag == 1)
                {
                    var readProcessLotResponse = MesWebServices.readProcessLot(processLotServiceWSServiceParam);
                    LogHelperBusiness.LogInfo("MES获取膜卷号接口返回参数:" + JsonChange.ModeToJson(readProcessLotResponse));
                    if (readProcessLotResponse.Response.processLotMemberList != null)
                    {
                        sfcStr = readProcessLotResponse.Response.processLotMemberList[0].memberContext.Substring(11);
                        LogHelperBusiness.LogInfo("RFID条码:" + rfidStr + "绑定的SFC条码为:" + sfcStr);
                        
                    }
                }
                else
                {
                    sfcStr = System.Guid.NewGuid().ToString("N").Substring(0, 14);
                }
            }
            catch (Exception ex)
            {
                LogHelperBusiness.LogInfo("MES获取膜卷号接口调用异常:" + ex.Message);
               
            }
            return sfcStr;
        }

        private IBaseServices<ProDownRecord> baseServices = new BaseServices<ProDownRecord>();

        private void Seach_Click(object sender, RoutedEventArgs e)
        {
            RefreshDataGrid();
        }

        private void RefreshDataGrid()
        {
            Expression<Func<ProDownRecord, bool>> exp = s1 => true;
            if (this.beginTime.Text.ToString() != "")
            {
                DateTime beginTime = Convert.ToDateTime(this.beginTime.Text.ToString());
                exp = exp.And(x => Convert.ToDateTime(x.RecordTime) >= beginTime);
            }

            if (this.endTime.Text.ToString() != "")
            {
                DateTime endTime = Convert.ToDateTime(this.endTime.Text.ToString());
                exp = exp.And(x => Convert.ToDateTime(x.RecordTime) <= endTime);
            }

            if (this.rfidText.Text.ToString() != "")
            {
                exp = exp.And(x => x.Rfid.Contains(this.rfidText.Text.ToString()));
            }

            if (this.sfcText.Text.ToString() != "")
            {
                exp = exp.And(x => x.Sfc.Contains(this.sfcText.Text.ToString()));
            }

            exp = exp.And(x => x.MachineId == appConfig.machineId);

            Expression<Func<ProDownRecord, object>> order = x => x.beginTime;

            List<ProDownRecord> downRecords = this.SelectDownRecords(exp).Result;

            var result = downRecords.Where(x => x.IsProduction == 0).ToList();

            if (result != null)
            {
                result.ForEach(x =>
                {
                    //x.DownMaterialId = x.IsProduction == 1 ? "已生产" : "未生产";
                    x.IsProduction = downRecords.IndexOf(x) + 1;
                    if (appConfig.machineId == 4)
                    {
                        if (x.Id.Contains("左"))
                        {
                            x.Id = x.Id.Replace("左", "右");
                        }
                        else if (x.Id.Contains("右"))
                        {
                            x.Id = x.Id.Replace("右", "左");
                        }
                    }
                });
                this.DownMaterialDataGrid.ItemsSource = result;
            }
        }

        private async Task<List<ProDownRecord>> SelectDownRecords(Expression<Func<ProDownRecord, bool>> exp)
        {
            try
            {
                Expression<Func<ProDownRecord, ProEquip, Object[]>> joinTable = (s1, s2) => new object[]
              {
                JoinType.Left,
                s2.machineId == appConfig.machineId && s2.positionId == s1.PositionId
              };

                Expression<Func<ProDownRecord, ProEquip, ProDownRecord>> selectWhere = (s1, s2) => new ProDownRecord
                {
                    Id = s2.equipName,
                    MachineId = s1.MachineId,
                    PositionId = s1.PositionId,
                    Rfid = s1.Rfid,
                    Sfc = s1.Sfc,
                    IsProduction = s1.IsProduction,
                    isFinish = s1.isFinish,
                    RecordTime = s1.RecordTime,
                    eaValue = s1.eaValue,
                    beginTime = s1.beginTime,
                    endTime = s1.endTime,
                };

                List<ProDownRecord> info = await baseServices.QueryMuch<ProDownRecord, ProEquip, ProDownRecord>(joinTable, selectWhere, exp);

                return info;
            }
            catch (Exception ex)
            {
                LogHelperBusiness.LogError("下料记录查询异常", ex);
                return null;
            }
        }

        private void Split_Click(object sender, RoutedEventArgs e)
        {
            string eaStr = "";

            if (!"1".Equals(ConfigHelper.GetConfig("roleId")) && !"2".Equals(ConfigHelper.GetConfig("roleId")))
            {
                System.Windows.MessageBox.Show("请登录系统管理账号进行操作");
                return;
            }

            ProDownRecord downRecord = (ProDownRecord)this.DownMaterialDataGrid.SelectedItem;

            if (downRecord == null)
            {
                MessageBox.Show("未选择异常记录");
                return;
            }

            if (StringExtension.IsBlank(sfcTextBox.Text))
            {
                MessageBox.Show("请输入放卷位SFC");
                return;
            }

            if (StringExtension.IsBlank(eaTextBox.Text))
            {
                MessageBox.Show("请输入ea值");
                return;
            }
            else
            {
                eaStr = sfcTextBox.Text;
            }

            //判断是否为冷压工序,是否为最后一卷,最后一卷按照MES EA进行拆分
            if (appConfig.processId == "LY_A")
            {
                if (Convert.ToString(this.endFlagCombox.SelectedItem) != "")
                {
                    ComboBoxItem endFlag = (ComboBoxItem)this.endFlagCombox.SelectedItem;
                    if (endFlag.Content.ToString() != null && endFlag.Content.ToString() != "")
                    {

                        if (endFlag.Content.ToString() == "是")
                        {
                            eaStr = GetUpMaterialQty(downRecord.PositionId, sfcTextBox.Text);
                        }
                    }
                }
            }
            

            Split(downRecord.Rfid,eaTextBox.Text, eaStr, downRecord.PositionId);
        }

        private void Complete_Click(object sender, RoutedEventArgs e)
        {

            if (!"1".Equals(ConfigHelper.GetConfig("roleId")) && !"2".Equals(ConfigHelper.GetConfig("roleId")))
            {
                System.Windows.MessageBox.Show("请登录系统管理账号进行操作");
                return;
            }

            ProDownRecord downRecord = (ProDownRecord)this.DownMaterialDataGrid.SelectedItem;

            if (downRecord == null)
            {
                MessageBox.Show("未选择异常记录");
                return;
            }

            if (StringExtension.IsBlank(sfcTextBox.Text))
            {
                MessageBox.Show("请输入放卷位SFC");
                return;
            }

            if (StringExtension.IsBlank(eaTextBox.Text))
            {
                MessageBox.Show("请输入ea值");
                return;
            }

            string splitSfc = GetSfcByRfid(downRecord.Rfid);
            if (StringExtension.IsBlank(splitSfc))
            {
                MessageBox.Show("RFID条码: " + downRecord.Rfid + "未绑定SFC");
            }
            Complete(sfcTextBox.Text, splitSfc, downRecord.Rfid,downRecord.PositionId, eaTextBox.Text);
        }

        private string GetLyShaftName(int positionId)
        {
            string shaftName = "";
            if (positionId == 1) shaftName = "1A轴";
            if (positionId == 2) shaftName = "1B轴";
            if (positionId == 3) shaftName = "2A轴";
            if (positionId == 4) shaftName = "2B轴";
            return shaftName;
        }

        /// <summary>
        /// 获取放卷位EA值
        /// </summary>
        /// <param name="bindSfc"></param>
        /// <returns></returns>
        private string GetUpMaterialQty(int position, string bindSfc)
        {
            MiSFCQueryQtyServiceServiceParam sFCQueryQtyServiceServiceParam = new MiSFCQueryQtyServiceServiceParam()
            {
                url = inifile.IniReadValue("MiSFCQueryQtyServiceServiceParam", "url"),
                site = inifile.IniReadValue("MiSFCQueryQtyServiceServiceParam", "site"),
                sfc = bindSfc
            };
            DateTime beginTime = DateTime.Now;
            try
            {
                if (appConfig.isMesFlag == 1)
                {
                    var sfcQueryQtyResponse = MesWebServices.iMiSFCQueryQtyServiceService(sFCQueryQtyServiceServiceParam);

                    if (sfcQueryQtyResponse.@return.code > 0)
                    {
                        LogHelperBusiness.LogInfo(String.Format("通过MES接口获取放卷物料{0}的SFC数量失败:{1}", bindSfc, upLoadBusiness.GetMesMessage(sfcQueryQtyResponse.@return.code, sfcQueryQtyResponse.@return.message)));
                        return "";
                    }
                    return sfcQueryQtyResponse.@return.qty;
                }
                else
                {
                    return "2600";
                }
            }
            catch (Exception ex)
            {
                LogHelperBusiness.LogInfo(String.Format("MES获取SFC数量接口异常:{0}", ex.Message));
                return "";
            }
        }
    }
}