using MaterialTraceability.Business;
using MaterialTraceability.Business.Impl;
using MaterialTraceability.Entity.DAO;
using MaterialTraceability.Entity.DTO;
using MaterialTraceability.SqlSugar;
using MaterialTraceability.SqlSugar.ServiceImpl;
using MaterialTraceability.WebService;
using MaterialTraceability.WebService.MiBatchCompleteSfcAndAdujustQtyServiceService;
using MaterialTraceability.WebService.MiFirstOperationForsfcServiceService;
using MaterialTraceability.WebService.MiSignOffSFCsServiceService;
using MaterialTraceability.WebService.Param;
using MaterialTraceabilityUI.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace MaterialTraceabilityUI
{
    /// <summary>
    /// UpMaterialRecord.xaml 的交互逻辑
    /// </summary>
    public partial class TBAlarmRecord : UserControl
    {
        private IMesWebServices MesWebServices = new MesWebServicesImpl();
        /// <summary>
        /// INIFile配置文件
        /// </summary>
        private IniFileHelper inifile = new IniFileHelper(System.Environment.CurrentDirectory + "/MesConfig/App.InI");
        private IBaseServices<ProDownRecord> downRecordServices = new BaseServices<ProDownRecord>();
        private ProDownRecordDto downRecordInfo = new ProDownRecordDto();

        private IBaseServices<SysClient> sysClientServices = new BaseServices<SysClient>();

        private UpLoadBusiness upLoadBusiness = UpLoadBusiness.Instance;
        private AppConfigDto appConfig = AppConfigDto.Instance;
        public TBAlarmRecord()
        {
            InitializeComponent();
            TBSignalReadBusiness.TBAlarmRecordRefreshEvent += refreshDataGrid;
            this.beginTime.Text = DateTime.Now.ToLongDateString();
            this.endTime.Text = DateTime.Now.AddDays(1).ToLongDateString();

            //List<String> isAlarm = new List<string>() { "正在生产", "异常下料", "" };
            //this.productionStatusComboBox.ItemsSource = isAlarm;

        }

        /// <summary>
        /// 刷新异常处理流程列表信息
        /// </summary>
        public void refreshDataGrid()
        {
            Action action;
            action = () =>
            {
                Expression<Func<ProDownRecord, bool>> exp = s1 => true;

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

                List<ProDownRecord> proUpRecords = downRecordServices.Query(exp, order, false).Result;
                List<ProDownRecordDto> proDownRecordDtos = new List<ProDownRecordDto>();
                proUpRecords.ForEach(x =>
                {
                    proDownRecordDtos.Add(new ProDownRecordDto()
                    {
                        Id = proUpRecords.IndexOf(x).ToString(),
                        MachineId = x.MachineId,
                        PositionId = x.PositionId,
                        Rfid = x.Rfid,
                        Sfc = x.Sfc,
                        eaValue = x.eaValue,
                        IsProduction = x.IsProduction,
                        ProductionFlag = productionStatus((int)x.IsProduction),
                        isFinish = x.isFinish,
                        RecordTime = x.RecordTime,
                        beginTime = x.beginTime,
                        endTime = x.endTime
                    });
                });
                this.AlarmInfoDataGrid.ItemsSource = proDownRecordDtos;
            };
            this.AlarmInfoDataGrid.Dispatcher.BeginInvoke(action);
        }

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

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            this.membraneLength.Text = GetSysConfigList("SysConfig").Where(x => x.paramKey == "membraneLength").FirstOrDefault().paramValue;
            this.volumesNumber.Text = GetSysConfigList("SysConfig").Where(x => x.paramKey == "volumesNumber").FirstOrDefault().paramValue;

            Refresh();
        }

        public void Refresh()
        {
            this.membraneLength.Text = GetSysConfigList("SysConfig").Where(x => x.paramKey == "membraneLength").FirstOrDefault().paramValue;
            this.volumesNumber.Text = GetSysConfigList("SysConfig").Where(x => x.paramKey == "volumesNumber").FirstOrDefault().paramValue;


            Expression<Func<ProDownRecord, bool>> exp = s1 => true;
            //exp = exp.And(x => x.IsProduction != 2);
            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 == this.rfidText.Text.ToString());
            }

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

            if (Convert.ToString(this.productionStatusComboBox.SelectedItem) != "")
            {
                ComboBoxItem proStr = (ComboBoxItem)this.productionStatusComboBox.SelectedItem;
                if (proStr.Content.ToString() != null && proStr.Content.ToString() != "")
                {
                    exp = exp.And(x => x.IsProduction == GetProductionStatus(proStr.Content.ToString()));
                }
            }

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

            List<ProDownRecord> proUpRecords = downRecordServices.Query(exp, order, false).Result;
            List<ProDownRecordDto> proDownRecordDtos = new List<ProDownRecordDto>();
            proUpRecords.ForEach(x =>
            {
                proDownRecordDtos.Add(new ProDownRecordDto()
                {
                    Id = proUpRecords.IndexOf(x).ToString(),
                    MachineId = x.MachineId,
                    PositionId = x.PositionId,
                    Rfid = x.Rfid,
                    Sfc = x.Sfc,
                    eaValue = x.eaValue,
                    IsProduction = x.IsProduction,
                    ProductionFlag = productionStatus((int)x.IsProduction),
                    isFinish = x.isFinish,
                    RecordTime = x.RecordTime,
                    beginTime = x.beginTime,
                    endTime = x.endTime
                });
            });
            this.AlarmInfoDataGrid.ItemsSource = proDownRecordDtos;
        }

        private int GetProductionStatus(string selectedItem)
        {
            int production = 0;
            switch (selectedItem)
            {
                case "正在生产":
                    production = 0;
                    break;
                case "正在完工":
                    production = 1;
                    break;
                case "已完工":
                    production = 2;
                    break;
                case "正在下料中":
                    production = 3;
                    break;
            }
            return production;
        }

        private string productionStatus(int production)
        {
            if (production == 0)
            {
                return "正在生产";
            }
            if (production == 1)
            {
                return "正在完工";
            }
            if (production == 2)
            {
                return "已完工";
            }
            if (production == 3)
            {
                return "正在下料中";
            }
            return production.ToString();
        }

        /// <summary>
        /// 注销SFC
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CancelSfc_MouseDown(object sender, MouseButtonEventArgs e)
        {
            ProDownRecordDto downRecord = (ProDownRecordDto)this.AlarmInfoDataGrid.SelectedItem;

            if (downRecord == null)
            {
                MessageBox.Show("请选择异常数据");
                return;
            }

            if (downRecord.isFinish >= 1)
            {
                MessageBox.Show("该结束流程已成功注销SFC");
                return;
            }
            LogHelperBusiness.LogInfo("调用MES注销SFC接口");
            MiSignOffSFCsServiceServiceParam miSignOffSFCsServiceServiceParam = new MiSignOffSFCsServiceServiceParam()
            {
                url = inifile.IniReadValue("MiSignOffSFCsServiceServiceParam", "url"),
                site = inifile.IniReadValue("MiSignOffSFCsServiceServiceParam", "site"),
                user = inifile.IniReadValue("MiSignOffSFCsServiceServiceParam", "user"),
                operation = appConfig.operationByA,
                operationRevision = inifile.IniReadValue("MiSignOffSFCsServiceServiceParam", "operationRevision"),
                activityId = inifile.IniReadValue("MiSignOffSFCsServiceServiceParam", "activityId"),
                Resource = appConfig.resource,
                amount = inifile.IniReadValue("MiSignOffSFCsServiceServiceParam", "amount"),
                sfcDataArray = null,
                sfc = downRecord.Sfc,
            };
            DateTime beginTime = DateTime.Now;
            try
            {
                LogHelperBusiness.LogInfo("调用MES注销SFC接口,请求参数:" + JsonChange.ModeToJson(miSignOffSFCsServiceServiceParam));

                if (appConfig.isMesFlag == 1)
                {
                    miSignOffSFCsResponse signOffSFCsResponse = MesWebServices.iMiSignOffSFCsServiceService(miSignOffSFCsServiceServiceParam);
                    LogHelperBusiness.LogInfo("调用MES注销SFC接口,返回参数:" + JsonChange.ModeToJson(signOffSFCsResponse));

                    if (signOffSFCsResponse.@return.code > 0)
                    {
                        if (signOffSFCsResponse.@return.code == 13900)
                        {
                            //更新完工步骤
                            this.UpdateDownRecord(downRecord.Rfid, downRecord.Sfc, 1, downRecord.eaValue);
                            ProcessStatus(1, true);
                            Refresh();
                            return;
                        }
                        else
                        {
                            MessageBox.Show("注销SFC接口调用失败:" + upLoadBusiness.GetMesMessage(signOffSFCsResponse.@return.code, signOffSFCsResponse.@return.message));
                            ProcessStatus(1, false);
                            Refresh();

                            return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ProcessStatus(1, false);
                Refresh();
                MessageBox.Show("注销SFC接口调用异常:" + ex.Message);
                return;
            }
            //更新完工步骤
            this.UpdateDownRecord(downRecord.Rfid, downRecord.Sfc, 1, downRecord.eaValue);
            ProcessStatus(1, true);
            Refresh();
            return;
        }

        private bool CancelSfcFunction(ProDownRecordDto downRecord)
        {
            LogHelperBusiness.LogInfo("调用MES注销SFC接口");
            MiSignOffSFCsServiceServiceParam miSignOffSFCsServiceServiceParam = new MiSignOffSFCsServiceServiceParam()
            {

                url = inifile.IniReadValue("MiSignOffSFCsServiceServiceParam", "url"),
                site = inifile.IniReadValue("MiSignOffSFCsServiceServiceParam", "site"),
                user = inifile.IniReadValue("MiSignOffSFCsServiceServiceParam", "user"),
                operation = appConfig.operationByA,
                operationRevision = inifile.IniReadValue("MiSignOffSFCsServiceServiceParam", "operationRevision"),
                activityId = inifile.IniReadValue("MiSignOffSFCsServiceServiceParam", "activityId"),
                Resource = appConfig.resource,
                amount = inifile.IniReadValue("MiSignOffSFCsServiceServiceParam", "amount"),
                sfcDataArray = null,
                sfc = downRecord.Sfc,
            };
            DateTime beginTime = DateTime.Now;
            try
            {
                LogHelperBusiness.LogInfo("调用MES注销SFC接口,请求参数:" + JsonChange.ModeToJson(miSignOffSFCsServiceServiceParam));

                if (appConfig.isMesFlag == 1)
                {
                    miSignOffSFCsResponse signOffSFCsResponse = MesWebServices.iMiSignOffSFCsServiceService(miSignOffSFCsServiceServiceParam);
                    LogHelperBusiness.LogInfo("调用MES注销SFC接口,返回参数:" + JsonChange.ModeToJson(signOffSFCsResponse));

                    if (signOffSFCsResponse.@return.code > 0)
                    {
                        if (signOffSFCsResponse.@return.code == 13900)
                        {
                            //更新完工步骤
                            this.UpdateDownRecord(downRecord.Rfid, downRecord.Sfc, 1, downRecord.eaValue);
                            ProcessStatus(1, true);
                            return true;
                        }
                        else
                        {
                            MessageBox.Show("注销SFC接口调用失败:" + upLoadBusiness.GetMesMessage(signOffSFCsResponse.@return.code, signOffSFCsResponse.@return.message));
                            ProcessStatus(1, false);
                            return false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("注销SFC接口调用异常:" + ex.Message);
                ProcessStatus(1, false);
                return false;
            }
            //更新完工步骤
            this.UpdateDownRecord(downRecord.Rfid, downRecord.Sfc, 1, downRecord.eaValue);
            ProcessStatus(1, true);
            return true;
        }

        /// <summary>
        /// 调整A面数量
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AdjustFaceA_MouseDown(object sender, MouseButtonEventArgs e)
        {
            ProDownRecordDto downRecord = (ProDownRecordDto)this.AlarmInfoDataGrid.SelectedItem;

            if (downRecord == null)
            {
                MessageBox.Show("请选择异常数据");
                return;
            }

            if (downRecord.isFinish >= 2)
            {
                MessageBox.Show("该结束流程已成功调整A面数量");
                return;
            }
            else
            {
                if (downRecord.isFinish < 1)
                {
                    MessageBox.Show("调整A面数量前还有流程未处理");
                    return;
                }
            }
            LogHelperBusiness.LogInfo("调用MES调整A面数量接口");
            MiBatchCompleteSfcAndAdujustQtyServiceServiceParam miBatchCompleteSfcAndAdujustQtyServiceServiceParam = new MiBatchCompleteSfcAndAdujustQtyServiceServiceParam()
            {

                url = inifile.IniReadValue("AdujustQtyParam", "url"),
                site = inifile.IniReadValue("AdujustQtyParam", "site"),
                sfcPre = downRecord.Sfc,
                processLotPre = "",
                operation = appConfig.operationByA,
                operationRevision = inifile.IniReadValue("AdujustQtyParam", "operationRevision"),
                resource = appConfig.resource,
                user = inifile.IniReadValue("AdujustQtyParam", "user"),
                activity = inifile.IniReadValue("AdujustQtyParam", "activity"),
                modeProcessSfc = ModeProcessSfc.MODE_NONE,
                sfcList = new miBatchCompleteSfcAndAdujustQtySfcEntity[]
                {
                    new miBatchCompleteSfcAndAdujustQtySfcEntity()
                    {
                        processLot = downRecord.Rfid,
                        sfc = "",
                        qty = downRecord.eaValue.ToString(),
                        unit = "EA"
                    }
                }
            };
            DateTime beginTime = DateTime.Now;
            try
            {
                LogHelperBusiness.LogInfo("调用MES调整A面数量接口,请求参数:" + JsonChange.ModeToJson(miBatchCompleteSfcAndAdujustQtyServiceServiceParam));

                if (appConfig.isMesFlag == 1)
                {
                    var requestResult = MesWebServices.iMiBatchCompleteSfcAndAdujustQtyServiceService(miBatchCompleteSfcAndAdujustQtyServiceServiceParam);
                    LogHelperBusiness.LogInfo("调用MES调整A面数量接口,返回参数:" + JsonChange.ModeToJson(requestResult));

                    if (requestResult.@return.code > 0)
                    {
                        MessageBox.Show("A面数量调整失败:" + upLoadBusiness.GetMesMessage(requestResult.@return.code, requestResult.@return.message));
                        ProcessStatus(2, false);
                        Refresh();

                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("A面数量调整异常:" + ex.Message);
                WebServiceLog.saveMiBatchCompleteSfcAndAdujustQtyServiceService(miBatchCompleteSfcAndAdujustQtyServiceServiceParam, null, beginTime, ex.Message);
                ProcessStatus(2, false);
                Refresh();
                return;
            }
            //更新完工步骤
            this.UpdateDownRecord(downRecord.Rfid, downRecord.Sfc, 2, downRecord.eaValue);
            ProcessStatus(2, true);
            Refresh();
        }

        private bool AdjustFaceAFunction(ProDownRecordDto downRecord)
        {
            LogHelperBusiness.LogInfo("调用MES调整A面数量接口");
            MiBatchCompleteSfcAndAdujustQtyServiceServiceParam miBatchCompleteSfcAndAdujustQtyServiceServiceParam = new MiBatchCompleteSfcAndAdujustQtyServiceServiceParam()
            {
                url = inifile.IniReadValue("AdujustQtyParam", "url"),
                site = inifile.IniReadValue("AdujustQtyParam", "site"),
                sfcPre = downRecord.Sfc,
                processLotPre = "",
                operation = appConfig.operationByA,
                operationRevision = inifile.IniReadValue("AdujustQtyParam", "operationRevision"),
                resource = appConfig.resource,
                user = inifile.IniReadValue("AdujustQtyParam", "user"),
                activity = inifile.IniReadValue("AdujustQtyParam", "activity"),
                modeProcessSfc = ModeProcessSfc.MODE_NONE,
                sfcList = new miBatchCompleteSfcAndAdujustQtySfcEntity[]
                {
                    new miBatchCompleteSfcAndAdujustQtySfcEntity()
                    {
                        processLot = downRecord.Rfid,
                        sfc = "",
                        qty = downRecord.eaValue.ToString(),
                        unit = "EA"
                    }
                }
            };
            DateTime beginTime = DateTime.Now;
            try
            {
                LogHelperBusiness.LogInfo("调用MES调整A面数量接口,请求参数:" + JsonChange.ModeToJson(miBatchCompleteSfcAndAdujustQtyServiceServiceParam));

                if (appConfig.isMesFlag == 1)
                {
                    var requestResult = MesWebServices.iMiBatchCompleteSfcAndAdujustQtyServiceService(miBatchCompleteSfcAndAdujustQtyServiceServiceParam);
                    LogHelperBusiness.LogInfo("调用MES调整A面数量接口,返回参数:" + JsonChange.ModeToJson(requestResult));

                    if (requestResult.@return.code > 0)
                    {
                        MessageBox.Show("A面数量调整失败:" + upLoadBusiness.GetMesMessage(requestResult.@return.code, requestResult.@return.message));
                        ProcessStatus(2, false);
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("A面数量调整异常:" + ex.Message);
                WebServiceLog.saveMiBatchCompleteSfcAndAdujustQtyServiceService(miBatchCompleteSfcAndAdujustQtyServiceServiceParam, null, beginTime, ex.Message);
                ProcessStatus(2, false);
                return false;
            }
            //更新完工步骤
            this.UpdateDownRecord(downRecord.Rfid, downRecord.Sfc, 2, downRecord.eaValue);
            ProcessStatus(2, true);
            return true;
        }

        /// <summary>
        /// A面开始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BeginFaceA_MouseDown(object sender, MouseButtonEventArgs e)
        {
            ProDownRecordDto downRecord = (ProDownRecordDto)this.AlarmInfoDataGrid.SelectedItem;

            if (downRecord == null)
            {
                MessageBox.Show("请选择异常数据");
                return;
            }

            if (downRecord.isFinish >= 3)
            {
                MessageBox.Show("该结束流程A面已成功入账开始");
                return;
            }
            else
            {
                if (downRecord.isFinish < 2)
                {
                    MessageBox.Show("A面入账开始前还有流程未处理");
                    return;
                }
            }
            LogHelperBusiness.LogInfo("调用MES A面入账开始接口");
            MiFirstOperationForsfcServiceServiceParam miFirstOperationForsfcServiceServiceParam = new MiFirstOperationForsfcServiceServiceParam()
            {

                url = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "url"),
                site = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "site"),
                sfc = downRecord.Sfc,
                processLot = "",
                operation = appConfig.operationByA,
                operationRevision = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "operationRevision"),
                resource = appConfig.resource,
                user = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "user"),
                activity = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "activity"),
                modeProcessSfc = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "modeProcessSfc"),
            };
            try
            {
                LogHelperBusiness.LogInfo("调用MES A面入账开始接口,请求参数:" + JsonChange.ModeToJson(miFirstOperationForsfcServiceServiceParam));

                if (appConfig.isMesFlag == 1)
                {
                    miFirstOperationForsfcResponse firstOperationForsfcResponse = MesWebServices.iMiFirstOperationForsfcServiceService(miFirstOperationForsfcServiceServiceParam);
                    LogHelperBusiness.LogInfo("调用MES A面入账开始接口,返回参数:" + JsonChange.ModeToJson(firstOperationForsfcResponse));
                    if (firstOperationForsfcResponse.@return.code > 0)
                    {
                        ProcessStatus(3, false);
                        Refresh();
                        MessageBox.Show("调用A面入账接口失败:" + upLoadBusiness.GetMesMessage(firstOperationForsfcResponse.@return.code, firstOperationForsfcResponse.@return.message));
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("调用A面入账接口异常:" + ex.Message);
                ProcessStatus(3, false);
                Refresh();

                return;
            }
            //更新完工步骤
            this.UpdateDownRecord(downRecord.Rfid, downRecord.Sfc, 3, downRecord.eaValue);
            ProcessStatus(3, true);
            Refresh();
            return;
        }

        private bool BeginFaceAFunction(ProDownRecordDto downRecord)
        {
            LogHelperBusiness.LogInfo("调用MES A面入账开始接口");

            MiFirstOperationForsfcServiceServiceParam miFirstOperationForsfcServiceServiceParam = new MiFirstOperationForsfcServiceServiceParam()
            {
                url = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "url"),
                site = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "site"),
                sfc = downRecord.Sfc,
                processLot = "",
                operation = appConfig.operationByA,
                operationRevision = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "operationRevision"),
                resource = appConfig.resource,
                user = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "user"),
                activity = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "activity"),
                modeProcessSfc = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "modeProcessSfc"),
            };
            try
            {
                LogHelperBusiness.LogInfo("调用MES A面入账开始接口,请求参数:" + JsonChange.ModeToJson(miFirstOperationForsfcServiceServiceParam));

                if (appConfig.isMesFlag == 1)
                {
                    miFirstOperationForsfcResponse firstOperationForsfcResponse = MesWebServices.iMiFirstOperationForsfcServiceService(miFirstOperationForsfcServiceServiceParam);
                    LogHelperBusiness.LogInfo("调用MES A面入账开始接口,返回参数:" + JsonChange.ModeToJson(firstOperationForsfcResponse));

                    if (firstOperationForsfcResponse.@return.code > 0)
                    {
                        MessageBox.Show("调用A面入账接口失败:" + upLoadBusiness.GetMesMessage(firstOperationForsfcResponse.@return.code, firstOperationForsfcResponse.@return.message));
                        ProcessStatus(3, false);
                        Refresh();

                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("调用A面入账接口异常:" + ex.Message);

                ProcessStatus(3, false);
                Refresh();

                return false;
            }
            //更新完工步骤
            this.UpdateDownRecord(downRecord.Rfid, downRecord.Sfc, 3, downRecord.eaValue);
            ProcessStatus(3, true);
            return true;
        }

        /// <summary>
        /// A面收集数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CollectFaceA_MouseDown(object sender, MouseButtonEventArgs e)
        {
            LogHelperBusiness.LogInfo("A面收集数据物料消耗");
            if (this.downRecordInfo != null)
            {
                if (FinishFaceAFunction(this.downRecordInfo))
                {
                    ProcessStatus(4, true);
                }
                else
                {
                    ProcessStatus(4, false);
                    return;
                }

                //B面自动入账开始
                if (BeginFaceBFunction(this.downRecordInfo))
                {
                    ProcessStatus(5, true);
                }
                else
                {
                    ProcessStatus(5, false);
                    return;
                }
            }
            else
            {
                MessageBox.Show("获取数据为空");
            }
        }

        /// <summary>
        /// A面完工
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FinishFaceA_MouseDown(object sender, MouseButtonEventArgs e)
        {
            ProDownRecordDto downRecord = (ProDownRecordDto)this.AlarmInfoDataGrid.SelectedItem;

            if (downRecord == null)
            {
                MessageBox.Show("请选择异常数据");
                return;
            }

            if (downRecord.isFinish >= 3)
            {
                MessageBox.Show("该结束流程A面已完工");
                return;
            }
            else
            {
                if (downRecord.isFinish < 3)
                {
                    MessageBox.Show("A面完工前还有流程未处理");
                    return;
                }
            }
            FinishFaceAFunction(downRecord);
        }

        private bool FinishFaceAFunction(ProDownRecordDto downRecord)
        {
            LogHelperBusiness.LogInfo("调用A面完工接口");
            MiBatchCompleteSfcAndAdujustQtyServiceServiceParam miBatchCompleteSfcAndAdujustQtyServiceServiceParam = new MiBatchCompleteSfcAndAdujustQtyServiceServiceParam()
            {
                url = inifile.IniReadValue("AdujustQtyParam", "url"),
                site = inifile.IniReadValue("AdujustQtyParam", "site"),
                sfcPre = "",
                processLotPre = downRecord.Rfid,
                operation = appConfig.operationByA,
                operationRevision = inifile.IniReadValue("AdujustQtyParam", "operationRevision"),
                resource = appConfig.resource,
                user = inifile.IniReadValue("AdujustQtyParam", "user"),
                activity = inifile.IniReadValue("AdujustQtyParam", "activity"),
                modeProcessSfc = ModeProcessSfc.MODE_COMPLETE_SFC_POST_DC, //冷压MODE_COMPLETE_SFC_POST_DC、模切MODE_COMPLETE_SFC_POST_DC
                sfcList = new miBatchCompleteSfcAndAdujustQtySfcEntity[]
                {
                    new miBatchCompleteSfcAndAdujustQtySfcEntity()
                    {
                        processLot = downRecord.Rfid,
                        sfc = "",
                        qty = downRecord.eaValue.ToString(),
                        unit = "EA"
                    }
                }
            };
            DateTime beginTime = DateTime.Now;
            try
            {
                LogHelperBusiness.LogInfo("调用A面完工接口,请求参数:" + JsonChange.ModeToJson(miBatchCompleteSfcAndAdujustQtyServiceServiceParam));

                if (appConfig.isMesFlag == 1)
                {
                    var requestResult = MesWebServices.iMiBatchCompleteSfcAndAdujustQtyServiceService(miBatchCompleteSfcAndAdujustQtyServiceServiceParam);
                    LogHelperBusiness.LogInfo("调用A面完工接口,返回参数:" + JsonChange.ModeToJson(requestResult));

                    if (requestResult.@return.code > 0)
                    {
                        MessageBox.Show("调用A面完工接口失败:" + upLoadBusiness.GetMesMessage(requestResult.@return.code, requestResult.@return.message));
                        ProcessStatus(4, false);
                        return false;
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("调用A面完工接口异常:" + ex.Message);
                ProcessStatus(4, false);
                return false;
            }

            //更新完工步骤
            this.UpdateDownRecord(downRecord.Rfid, downRecord.Sfc, 4, downRecord.eaValue);
            ProcessStatus(4, true);
            return true;
        }

        /// <summary>
        /// B面开始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BeginFaceB_MouseDown(object sender, MouseButtonEventArgs e)
        {
            ProDownRecordDto downRecord = (ProDownRecordDto)this.AlarmInfoDataGrid.SelectedItem;

            if (downRecord == null)
            {
                MessageBox.Show("请选择异常数据");
                return;
            }

            if (downRecord.isFinish >= 5)
            {
                MessageBox.Show("该结束流程B面已入账开始");
                return;
            }
            else
            {
                if (downRecord.isFinish < 3)
                {
                    MessageBox.Show("B面入账开始前还有流程未处理");
                    return;
                }
            }
            MiFirstOperationForsfcServiceServiceParam miFirstOperationForsfcServiceServiceParam = new MiFirstOperationForsfcServiceServiceParam()
            {
                url = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "url"),
                site = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "site"),
                sfc = downRecord.Sfc,
                processLot = "",
                operation = appConfig.operationByB,
                operationRevision = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "operationRevision"),
                resource = appConfig.resource,
                user = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "user"),
                activity = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "activity"),
                modeProcessSfc = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "modeProcessSfc"),
            };
            DateTime beginTime = DateTime.Now;
            try
            {
                if (appConfig.isMesFlag == 1)
                {
                    miFirstOperationForsfcResponse firstOperationForsfcResponse = MesWebServices.iMiFirstOperationForsfcServiceService(miFirstOperationForsfcServiceServiceParam);
                    WebServiceLog.saveMiFirstOperationForsfcServiceService(miFirstOperationForsfcServiceServiceParam, firstOperationForsfcResponse, beginTime, "");
                    if (firstOperationForsfcResponse.@return.code > 0)
                    {
                        ProcessStatus(5, false);
                        Refresh();

                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                WebServiceLog.saveMiFirstOperationForsfcServiceService(miFirstOperationForsfcServiceServiceParam, null, beginTime, ex.Message);
                ProcessStatus(5, false);
                Refresh();

                return;
            }
            //更新完工步骤
            this.UpdateDownRecord(downRecord.Rfid, downRecord.Sfc, 5, downRecord.eaValue);
            ProcessStatus(5, true);
            Refresh();

            return;
        }

        private bool BeginFaceBFunction(ProDownRecordDto downRecord)
        {
            LogHelperBusiness.LogInfo("调用MES B面开始接口");
            MiFirstOperationForsfcServiceServiceParam miFirstOperationForsfcServiceServiceParam = new MiFirstOperationForsfcServiceServiceParam()
            {
                url = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "url"),
                site = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "site"),
                sfc = downRecord.Sfc,
                processLot = "",
                operation = appConfig.operationByB,
                operationRevision = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "operationRevision"),
                resource = appConfig.resource,
                user = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "user"),
                activity = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "activity"),
                modeProcessSfc = inifile.IniReadValue("MiFirstOperationForsfcServiceServiceParam", "modeProcessSfc"),
            };
            DateTime beginTime = DateTime.Now;
            try
            {
                LogHelperBusiness.LogInfo("调用MES B面开始接口请求参数:" + JsonChange.ModeToJson(miFirstOperationForsfcServiceServiceParam));

                if (appConfig.isMesFlag == 1)
                {
                    miFirstOperationForsfcResponse firstOperationForsfcResponse = MesWebServices.iMiFirstOperationForsfcServiceService(miFirstOperationForsfcServiceServiceParam);
                    LogHelperBusiness.LogInfo("调用MES B面开始接口返回参数:" + JsonChange.ModeToJson(firstOperationForsfcResponse));

                    WebServiceLog.saveMiFirstOperationForsfcServiceService(miFirstOperationForsfcServiceServiceParam, firstOperationForsfcResponse, beginTime, "");
                    if (firstOperationForsfcResponse.@return.code > 0)
                    {
                        MessageBox.Show("调用MES B面开始接口失败:" + upLoadBusiness.GetMesMessage(firstOperationForsfcResponse.@return.code, firstOperationForsfcResponse.@return.message));
                        ProcessStatus(5, false);
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("调用MES B面开始接口异常:" + ex.Message);

                WebServiceLog.saveMiFirstOperationForsfcServiceService(miFirstOperationForsfcServiceServiceParam, null, beginTime, ex.Message);
                ProcessStatus(5, false);
                return false;
            }
            //更新完工步骤
            this.UpdateDownRecord(downRecord.Rfid, downRecord.Sfc, 5, downRecord.eaValue);
            ProcessStatus(5, true);
            return true;
        }

        /// <summary>
        /// B面收集数据物料消耗
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CollectFaceB_MouseDown(object sender, MouseButtonEventArgs e)
        {
            LogHelperBusiness.LogInfo("B面收集数据物料消耗");
            if (this.downRecordInfo != null)
            {
                if (FinishFaceBFunction(downRecordInfo))
                {
                    ProcessStatus(6, true);
                }
                else
                {
                    ProcessStatus(6, false);
                    return;
                }
            }
            else
            {
                MessageBox.Show("获取数据为空");
            }
        }

        /// <summary>
        /// B面完工
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FinishFaceB_MouseDown(object sender, MouseButtonEventArgs e)
        {
            ProDownRecordDto downRecord = (ProDownRecordDto)this.AlarmInfoDataGrid.SelectedItem;

            if (downRecord == null)
            {
                MessageBox.Show("请选择异常数据");
                return;
            }

            if (downRecord.isFinish == 6)
            {
                MessageBox.Show("该完工流程已结束");
                return;
            }
            else
            {
                if (downRecord.isFinish < 5)
                {
                    MessageBox.Show("B面完工前还有流程未处理");
                    return;
                }
            }
            MiBatchCompleteSfcAndAdujustQtyServiceServiceParam miBatchCompleteSfcAndAdujustQtyServiceServiceParam = new MiBatchCompleteSfcAndAdujustQtyServiceServiceParam()
            {
                url = inifile.IniReadValue("AdujustQtyParam", "url"),
                site = inifile.IniReadValue("AdujustQtyParam", "site"),
                sfcPre = "",
                processLotPre = downRecord.Rfid,
                operation = appConfig.operationByB,
                operationRevision = inifile.IniReadValue("AdujustQtyParam", "operationRevision"),
                resource = appConfig.resource,
                user = inifile.IniReadValue("AdujustQtyParam", "user"),
                activity = inifile.IniReadValue("AdujustQtyParam", "activity"),
                modeProcessSfc = ModeProcessSfc.MODE_COMPLETE_SFC_POST_DC, //冷压MODE_COMPLETE_SFC_POST_DC、模切MODE_COMPLETE_SFC_POST_DC
                sfcList = new miBatchCompleteSfcAndAdujustQtySfcEntity[]
                {
                    new miBatchCompleteSfcAndAdujustQtySfcEntity()
                    {
                        processLot = downRecord.Rfid,
                        sfc = downRecord.Sfc,
                        qty = downRecord.eaValue.ToString(),
                        unit = "EA"
                    }
                }
            };
            DateTime beginTime = DateTime.Now;
            try
            {
                if (appConfig.isMesFlag == 1)
                {
                    var requestResult = MesWebServices.iMiBatchCompleteSfcAndAdujustQtyServiceService(miBatchCompleteSfcAndAdujustQtyServiceServiceParam);
                    WebServiceLog.saveMiBatchCompleteSfcAndAdujustQtyServiceService(miBatchCompleteSfcAndAdujustQtyServiceServiceParam, requestResult, beginTime, "");

                    if (requestResult.@return.code > 0)
                    {
                        ProcessStatus(6, false);
                        Refresh();

                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                WebServiceLog.saveMiBatchCompleteSfcAndAdujustQtyServiceService(miBatchCompleteSfcAndAdujustQtyServiceServiceParam, null, beginTime, ex.Message);
                ProcessStatus(6, false);
                Refresh();

                return;
            }
            //更新完工步骤
            this.UpdateDownRecord(downRecord.Rfid, downRecord.Sfc, 6, downRecord.eaValue);
            ProcessStatus(6, false);
            Refresh();

            return;
        }

        private bool FinishFaceBFunction(ProDownRecordDto downRecord)
        {
            LogHelperBusiness.LogInfo("调用MES B面完工接口");
            MiBatchCompleteSfcAndAdujustQtyServiceServiceParam miBatchCompleteSfcAndAdujustQtyServiceServiceParam = new MiBatchCompleteSfcAndAdujustQtyServiceServiceParam()
            {
                url = inifile.IniReadValue("AdujustQtyParam", "url"),
                site = inifile.IniReadValue("AdujustQtyParam", "site"),
                sfcPre = "",
                processLotPre = downRecord.Rfid,
                operation = appConfig.operationByB,
                operationRevision = inifile.IniReadValue("AdujustQtyParam", "operationRevision"),
                resource = appConfig.resource,
                user = inifile.IniReadValue("AdujustQtyParam", "user"),
                activity = inifile.IniReadValue("AdujustQtyParam", "activity"),
                modeProcessSfc = ModeProcessSfc.MODE_COMPLETE_SFC_POST_DC, //冷压MODE_COMPLETE_SFC_POST_DC、模切MODE_COMPLETE_SFC_POST_DC
                sfcList = new miBatchCompleteSfcAndAdujustQtySfcEntity[]
                {
                    new miBatchCompleteSfcAndAdujustQtySfcEntity()
                    {
                        processLot = downRecord.Rfid,
                        sfc = downRecord.Sfc,
                        qty = downRecord.eaValue.ToString(),
                        unit = "EA"
                    }
                }
            };
            DateTime beginTime = DateTime.Now;
            try
            {
                LogHelperBusiness.LogInfo("调用MES B面完工接口,请求参数:" + JsonChange.ModeToJson(miBatchCompleteSfcAndAdujustQtyServiceServiceParam));

                if (appConfig.isMesFlag == 1)
                {
                    var requestResult = MesWebServices.iMiBatchCompleteSfcAndAdujustQtyServiceService(miBatchCompleteSfcAndAdujustQtyServiceServiceParam);
                    WebServiceLog.saveMiBatchCompleteSfcAndAdujustQtyServiceService(miBatchCompleteSfcAndAdujustQtyServiceServiceParam, requestResult, beginTime, "");
                    LogHelperBusiness.LogInfo("调用MES B面完工接口,返回参数:" + JsonChange.ModeToJson(requestResult));

                    if (requestResult.@return.code > 0)
                    {
                        MessageBox.Show("调用MES B面完工接口失败:" + upLoadBusiness.GetMesMessage(requestResult.@return.code, requestResult.@return.message));
                        ProcessStatus(6, false);
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("调用MES B面完工接口异常:" + ex.Message);
                WebServiceLog.saveMiBatchCompleteSfcAndAdujustQtyServiceService(miBatchCompleteSfcAndAdujustQtyServiceServiceParam, null, beginTime, ex.Message);
                ProcessStatus(6, false);
                return false;
            }
            //更新完工步骤
            this.UpdateDownRecord(downRecord.Rfid, downRecord.Sfc, 6, downRecord.eaValue);
            ProcessStatus(6, false);
            return true;
        }


        /// <summary>
        /// 继续完工
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExceptionHand_Click(object sender, RoutedEventArgs e)
        {
            Init();

            ProDownRecordDto downRecord = (ProDownRecordDto)this.AlarmInfoDataGrid.SelectedItem;

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

            if (downRecord.IsProduction != 3 && downRecord.IsProduction != 1)
            {
                MessageBox.Show(downRecord.ProductionFlag + "不允许异常处理");
                return;
            }
            this.downRecordInfo = downRecord;
            bool[] mes = new bool[6];
            for (int i = 1; i <= downRecord.isFinish; i++)
            {
                ProcessStatus(i, true);
                mes[i - 1] = true;
            }
            ExceptionHandFunction(downRecord, mes);
        }

        public void ExceptionHandFunction(ProDownRecordDto downRecord, bool[] mesResult)
        {
            if (!mesResult[0])
            {
                if (CancelSfcFunction(downRecord))
                {
                    ProcessStatus(1, true);
                }
                else
                {
                    ProcessStatus(1, false);
                    return;
                }
            }

            if (!mesResult[1])
            {
                if (CancelSfcFunction(downRecord))
                {
                    ProcessStatus(1, true);
                }
                else
                {
                    ProcessStatus(1, false);
                    return;
                }
                //A面开始调整数量事件
                if (AdjustFaceAFunction(downRecord))
                {
                    ProcessStatus(2, true);
                }
                else
                {
                    ProcessStatus(2, false);
                    return;
                }
            }

            if (!mesResult[2])
            {
                //A面自动开始
                if (BeginFaceAFunction(downRecord))
                {
                    ProcessStatus(3, true);
                }
                else
                {
                    ProcessStatus(3, false);
                    return;
                }
                return;
            }

            if (!mesResult[3])
            {
                if (FinishFaceAFunction(downRecord))
                {
                    ProcessStatus(4, true);
                }
                else
                {
                    ProcessStatus(4, false);
                    return;
                }
            }

            if (!mesResult[4])
            {
                //B面自动入账开始
                if (BeginFaceBFunction(downRecord))
                {
                    ProcessStatus(5, true);
                }
                else
                {
                    ProcessStatus(5, false);
                    return;
                }
                return;
            }

            if (!mesResult[5])
            {
                if (FinishFaceBFunction(downRecord))
                {
                    ProcessStatus(6, true);
                }
                else
                {
                    ProcessStatus(6, false);
                    return;
                }
            }
        }

        /// <summary>
        /// 强制下料
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ForceDown_Click(object sender, RoutedEventArgs e)
        {

        }

        private void ProcessStatus(int processNumber, bool isSucess)
        {
            Action action;
            switch (processNumber)
            {
                case 1:
                    //注销SFC
                    if (isSucess)
                    {
                        action = () =>
                        {
                            this.CancelSfc.Background = Brushes.Green;
                        };
                        this.CancelSfc.Dispatcher.BeginInvoke(action);

                        action = () =>
                        {
                            this.CancelSfcText.Foreground = Brushes.White;
                        };
                        this.CancelSfcText.Dispatcher.BeginInvoke(action);
                    }
                    else
                    {
                        action = () =>
                        {
                            this.CancelSfc.Background = Brushes.Red;
                        };
                        this.CancelSfc.Dispatcher.BeginInvoke(action);

                        action = () =>
                        {
                            this.CancelSfcText.Foreground = Brushes.White;
                        };
                        this.CancelSfcText.Dispatcher.BeginInvoke(action);
                    }
                    break;
                case 2:
                    //调整A面数量
                    if (isSucess)
                    {
                        action = () =>
                        {
                            this.AdjustFaceA.Background = Brushes.Green;
                        };
                        this.AdjustFaceA.Dispatcher.BeginInvoke(action);

                        action = () =>
                        {
                            this.AdjustFaceAText.Foreground = Brushes.White;
                        };
                        this.AdjustFaceAText.Dispatcher.BeginInvoke(action);
                    }
                    else
                    {
                        action = () =>
                        {
                            this.AdjustFaceA.Background = Brushes.Red;
                        };
                        this.AdjustFaceA.Dispatcher.BeginInvoke(action);

                        action = () =>
                        {
                            this.AdjustFaceAText.Foreground = Brushes.White;
                        };
                        this.AdjustFaceAText.Dispatcher.BeginInvoke(action);
                    }
                    break;
                case 3:
                    //A面开始
                    if (isSucess)
                    {
                        action = () =>
                        {
                            this.BeginFaceA.Background = Brushes.Green;
                        };
                        this.BeginFaceA.Dispatcher.BeginInvoke(action);

                        action = () =>
                        {
                            this.BeginFaceAText.Foreground = Brushes.White;
                        };
                        this.BeginFaceA.Dispatcher.BeginInvoke(action);

                        action = () =>
                        {
                            this.CollectFaceA.Background = Brushes.Yellow;
                        };
                        this.CollectFaceA.Dispatcher.BeginInvoke(action);
                    }
                    else
                    {
                        action = () =>
                        {
                            this.BeginFaceA.Background = Brushes.Red;
                        };
                        this.BeginFaceA.Dispatcher.BeginInvoke(action);

                        action = () =>
                        {
                            this.BeginFaceAText.Foreground = Brushes.White;
                        };
                        this.BeginFaceA.Dispatcher.BeginInvoke(action);
                    }

                    break;
                case 4:
                    //A面完工
                    if (isSucess)
                    {
                        action = () =>
                        {
                            this.CollectFaceA.Background = Brushes.Green;
                        };
                        this.CollectFaceA.Dispatcher.BeginInvoke(action);

                        action = () =>
                        {
                            this.CollectFaceAText1.Foreground = Brushes.White;
                        };
                        this.CollectFaceAText1.Dispatcher.BeginInvoke(action);

                        action = () =>
                        {
                            this.CollectFaceAText2.Foreground = Brushes.White;
                        };
                        this.CollectFaceAText2.Dispatcher.BeginInvoke(action);

                        action = () =>
                        {
                            this.FinishFaceA.Background = Brushes.Green;
                        };
                        this.FinishFaceA.Dispatcher.BeginInvoke(action);

                        action = () =>
                        {
                            this.FinishFaceAText.Foreground = Brushes.White;
                        };
                        this.FinishFaceAText.Dispatcher.BeginInvoke(action);
                    }
                    else
                    {
                        action = () =>
                        {
                            this.FinishFaceA.Background = Brushes.Red;
                        };
                        this.FinishFaceA.Dispatcher.BeginInvoke(action);
                        action = () =>
                        {
                            this.FinishFaceAText.Foreground = Brushes.White;
                        };
                        this.FinishFaceAText.Dispatcher.BeginInvoke(action);
                    }
                    break;
                case 5:
                    //B面开始
                    if (isSucess)
                    {
                        action = () =>
                        {
                            this.BeginFaceB.Background = Brushes.Green;
                        };
                        this.BeginFaceB.Dispatcher.BeginInvoke(action);

                        action = () =>
                        {
                            this.CollectFaceB.Background = Brushes.Yellow;
                        };
                        this.CollectFaceB.Dispatcher.BeginInvoke(action);

                        action = () =>
                        {
                            this.CollectFaceBText1.Foreground = Brushes.White;
                        };
                        this.CollectFaceBText1.Dispatcher.BeginInvoke(action);

                        action = () =>
                        {
                            this.CollectFaceBText2.Foreground = Brushes.White;
                        };
                        this.CollectFaceBText2.Dispatcher.BeginInvoke(action);

                        action = () =>
                        {
                            this.BeginFaceBText.Foreground = Brushes.White;
                        };
                        this.BeginFaceBText.Dispatcher.BeginInvoke(action);
                    }
                    else
                    {
                        action = () =>
                        {
                            this.BeginFaceB.Background = Brushes.Red;
                        };
                        this.BeginFaceB.Dispatcher.BeginInvoke(action);
                        action = () =>
                        {
                            this.BeginFaceBText.Foreground = Brushes.White;
                        };
                        this.BeginFaceBText.Dispatcher.BeginInvoke(action);
                    }
                    break;
                case 6:
                    //B面完工
                    if (isSucess)
                    {

                        action = () =>
                        {
                            this.CollectFaceB.Background = Brushes.Green;
                        };
                        this.CollectFaceB.Dispatcher.BeginInvoke(action);

                        action = () =>
                        {
                            this.CollectFaceBText1.Foreground = Brushes.White;
                        };
                        this.CollectFaceBText1.Dispatcher.BeginInvoke(action);

                        action = () =>
                        {
                            this.CollectFaceBText2.Foreground = Brushes.White;
                        };
                        this.CollectFaceBText2.Dispatcher.BeginInvoke(action);

                        action = () =>
                        {
                            this.FinishFaceB.Background = Brushes.Green;
                        };
                        this.FinishFaceB.Dispatcher.BeginInvoke(action);

                        action = () =>
                        {
                            this.FinishFaceBText.Foreground = Brushes.White;
                        };
                        this.FinishFaceBText.Dispatcher.BeginInvoke(action);
                    }
                    else
                    {
                        action = () =>
                        {
                            this.FinishFaceB.Background = Brushes.Red;
                        };
                        this.FinishFaceB.Dispatcher.BeginInvoke(action);
                        action = () =>
                        {
                            this.FinishFaceBText.Foreground = Brushes.White;
                        };
                        this.FinishFaceBText.Dispatcher.BeginInvoke(action);
                    }
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 初始化界面
        /// </summary>
        private void Init()
        {
            Action action;
            action = () =>
            {
                this.CancelSfc.Background = Brushes.White;
            };
            this.CancelSfc.Dispatcher.BeginInvoke(action);

            action = () =>
            {
                this.CancelSfcText.Foreground = Brushes.Gray;
            };
            this.CancelSfcText.Dispatcher.BeginInvoke(action);

            action = () =>
            {
                this.AdjustFaceA.Background = Brushes.White;
            };
            this.AdjustFaceA.Dispatcher.BeginInvoke(action);

            action = () =>
            {
                this.AdjustFaceAText.Foreground = Brushes.Gray;
            };
            this.AdjustFaceAText.Dispatcher.BeginInvoke(action);

            action = () =>
            {
                this.BeginFaceA.Background = Brushes.White;
            };
            this.BeginFaceA.Dispatcher.BeginInvoke(action);

            action = () =>
            {
                this.BeginFaceAText.Foreground = Brushes.Gray;
            };
            this.BeginFaceAText.Dispatcher.BeginInvoke(action);

            action = () =>
            {
                this.CollectFaceA.Background = Brushes.White;
            };
            this.CollectFaceA.Dispatcher.BeginInvoke(action);

            action = () =>
            {
                this.CollectFaceAText1.Foreground = Brushes.Gray;
            };
            this.CollectFaceAText1.Dispatcher.BeginInvoke(action);

            action = () =>
            {
                this.CollectFaceAText2.Foreground = Brushes.Gray;
            };
            this.CollectFaceAText2.Dispatcher.BeginInvoke(action);

            action = () =>
            {
                this.FinishFaceA.Background = Brushes.White;
            };
            this.FinishFaceA.Dispatcher.BeginInvoke(action);

            action = () =>
            {
                this.FinishFaceAText.Foreground = Brushes.Gray;
            };
            this.FinishFaceAText.Dispatcher.BeginInvoke(action);

            action = () =>
            {
                this.BeginFaceB.Background = Brushes.White;
            };
            this.BeginFaceB.Dispatcher.BeginInvoke(action);

            action = () =>
            {
                this.BeginFaceBText.Foreground = Brushes.Gray;
            };
            this.BeginFaceBText.Dispatcher.BeginInvoke(action);

            action = () =>
            {
                this.CollectFaceB.Background = Brushes.White;
            };
            this.CollectFaceB.Dispatcher.BeginInvoke(action);

            action = () =>
            {
                this.CollectFaceBText1.Foreground = Brushes.Gray;
            };
            this.CollectFaceBText1.Dispatcher.BeginInvoke(action);

            action = () =>
            {
                this.CollectFaceBText2.Foreground = Brushes.Gray;
            };
            this.CollectFaceBText2.Dispatcher.BeginInvoke(action);

            action = () =>
            {
                this.FinishFaceB.Background = Brushes.White;
            };
            this.FinishFaceB.Dispatcher.BeginInvoke(action);

            action = () =>
            {
                this.FinishFaceBText.Foreground = Brushes.Gray;
            };
            this.FinishFaceBText.Dispatcher.BeginInvoke(action);
        }

        private async void UpdateDownRecord(string rfid, string sfc, int finish, int eaValue)
        {
            Expression<Func<ProDownRecord, bool>> downExp = s1 => true;
            downExp = downExp.And(x => x.Rfid == rfid && x.Sfc == sfc);
            Expression<Func<ProDownRecord, object>> downOrder = (s) => s.RecordTime;
            ProDownRecord downRecord = await downRecordServices.QueryFirst(downExp, downOrder, false);
            if (downRecord != null)
            {
                downRecord.eaValue = eaValue;
                downRecord.IsProduction = finish == 6 ? 2 : 3;
                downRecord.isFinish = finish;
                downRecord.endTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                await downRecordServices.Update(downRecord);

                upLoadBusiness.UpdateDownRecord(downRecord);
            }

            Refresh();

            List<ProDownRecordDto> info = this.AlarmInfoDataGrid.ItemsSource as List<ProDownRecordDto>;

            ProDownRecordDto recordDto = info.Where(x => x.Sfc == sfc).FirstOrDefault();

            this.AlarmInfoDataGrid.SelectedItem = recordDto;

        }

        /// <summary>
        /// 获取MESEA值更新数据记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetMesEaValue_Click(object sender, RoutedEventArgs e)
        {
            ProDownRecordDto downRecord = (ProDownRecordDto)this.AlarmInfoDataGrid.SelectedItem;

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

            //获取物料信息
            Expression<Func<ProDownRecord, bool>> exp = s1 => true;
            exp = exp.And(x => x.Sfc == downRecord.Sfc);
            Expression<Func<ProDownRecord, object>> order = s1 => s1.endTime;
            ProDownRecord downRecordInfo = downRecordServices.QueryFirst(exp, order, false).Result;

            if (downRecordInfo == null)
            {
                MessageBox.Show("获取下料数据为空");
                return;
            }

            LogHelperBusiness.LogInfo(String.Format("通过MES接口获取{0}物料的EA值", downRecord.Sfc));
            MiSFCQueryQtyServiceServiceParam sFCQueryQtyServiceServiceParam = new MiSFCQueryQtyServiceServiceParam()
            {
                url = inifile.IniReadValue("MiSFCQueryQtyServiceServiceParam", "url"),
                site = inifile.IniReadValue("MiSFCQueryQtyServiceServiceParam", "site"),
                sfc = downRecord.Sfc
            };
            LogHelperBusiness.LogInfo("MES获取物料EA值接口请求参数:" + JsonChange.ModeToJson(sFCQueryQtyServiceServiceParam));
            DateTime beginTime = DateTime.Now;
            try
            {
                if (appConfig.isMesFlag == 1)
                {
                    var sfcQueryQtyResponse = MesWebServices.iMiSFCQueryQtyServiceService(sFCQueryQtyServiceServiceParam);
                    LogHelperBusiness.LogInfo("MES获取物料EA值接口返回参数:" + JsonChange.ModeToJson(sfcQueryQtyResponse));
                    if (sfcQueryQtyResponse.@return.code > 0)
                    {
                        LogHelperBusiness.LogInfo("MES获取物料EA值接口请求失败:" + sfcQueryQtyResponse.@return.message);
                        MessageBox.Show(String.Format("通过MES接口获取放卷物料{0}的SFC数量失败:{1}", downRecord.Sfc, upLoadBusiness.GetMesMessage(sfcQueryQtyResponse.@return.code, sfcQueryQtyResponse.@return.message)));
                        return;
                    }

                    if (Convert.ToInt32(sfcQueryQtyResponse.@return.qty) > 1)
                    {
                        downRecordInfo.eaValue = Convert.ToInt32(sfcQueryQtyResponse.@return.qty);
                    }
                    else
                    {
                        MessageBox.Show("MES物料EA为:" + Convert.ToInt32(sfcQueryQtyResponse.@return.qty + "不进行同步"));
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelperBusiness.LogInfo(String.Format("MES获取SFC数量接口异常:{1}", ex.Message));
                WebServiceLog.saveMiSFCQueryQtyServiceService(sFCQueryQtyServiceServiceParam, null, beginTime, ex.Message);
                MessageBox.Show(String.Format("MES获取SFC数量接口异常:{1}", ex.Message));
                return;
            }

            bool updateResult = downRecordServices.Update(downRecordInfo).Result;

            if (updateResult)
            {
                MessageBox.Show("数量调整成功");
            }
            else
            {
                MessageBox.Show("数量调整失败");
            }

            upLoadBusiness.UpdateDownRecord(downRecordInfo);

            refreshDataGrid();
        }

        private void EaParamSet_Click(object sender, RoutedEventArgs e)
        {
            string membraneLength = this.membraneLength.Text.ToString();

            string volumesNumber = this.volumesNumber.Text.ToString();

            if (StringExtension.IsBlank(membraneLength))
            {
                MessageBox.Show("请输入模长");
                return;
            }

            if (StringExtension.IsBlank(volumesNumber))
            {
                volumesNumber = "6";
            }

            if (EaParamSetFunction(membraneLength, volumesNumber).Result)
            {
                MessageBox.Show("EA参数设置成功");
                this.membraneLength.Text = GetSysConfigList("SysConfig").Where(x => x.paramKey == "membraneLength").FirstOrDefault().paramValue;
                this.volumesNumber.Text = GetSysConfigList("SysConfig").Where(x => x.paramKey == "volumesNumber").FirstOrDefault().paramValue;
            }
            else
            {
                MessageBox.Show("EA参数设置失败");
            }

        }

        public async Task<bool> EaParamSetFunction(string membraneLength, string volumesNumber)
        {
            try
            {
                var membraneLengthInfo = GetSysConfigList("SysConfig").Where(x => x.paramKey == "membraneLength").FirstOrDefault();
                var volumesNumberInfo = GetSysConfigList("SysConfig").Where(x => x.paramKey == "volumesNumber").FirstOrDefault();

                if (membraneLengthInfo == null)
                {
                    SysClient client = new SysClient()
                    {
                        processId = appConfig.processId,
                        paramKey = "membraneLength",
                        paramValue = membraneLength,
                        paramType = "SysConfig",
                        remark = "EA系数:膜长"
                    };
                    await sysClientServices.Add(client);
                }
                else
                {
                    membraneLengthInfo.paramValue = membraneLength;
                    await sysClientServices.Update(membraneLengthInfo);
                }

                if (volumesNumberInfo == null)
                {
                    SysClient client = new SysClient()
                    {
                        processId = appConfig.processId,
                        paramKey = "volumesNumber",
                        paramValue = volumesNumber,
                        paramType = "SysConfig",
                        remark = "EA系数:系数"
                    };
                    await sysClientServices.Add(client);
                }
                else
                {
                    volumesNumberInfo.paramValue = volumesNumber;
                    await sysClientServices.Update(volumesNumberInfo);
                }
                return true;
            }
            catch (Exception ex)
            {
                LogHelperBusiness.LogError("EA参数设置异常", ex);
                return false;
            }

        }

        /// <summary>
        /// 获取配置列表
        /// </summary>
        /// <returns></returns>
        private List<SysClient> GetSysConfigList(string paramType)
        {
            try
            {
                Expression<Func<SysClient, bool>> exp = s1 => true;

                if (StringExtension.IsNotBlank(paramType))
                {
                    exp = exp.And(x => x.paramType == paramType);
                }

                exp = exp.And(x => x.processId == appConfig.processId);

                List<SysClient> info = sysClientServices.Query(exp).Result;

                return info;
            }
            catch (Exception ex)
            {
                LogHelperBusiness.LogError("获取配置列表异常", ex);
                return null;
            }
        }
    }
}