using HighWayIot.Log4net;
using HighWayIot.Plc;
using HighWayIot.Plc.PlcHelper;
using HighWayIot.Repository.domain;
using HighWayIot.Repository.service;
using HighWayIot.Winform.Business;
using HighWayIot.Winform.MainForm;
using HighWayIot.Winform.UserControlPages.RecipeConfigPages;
using HighWayIot.Winform.UserControlPages.SysConfigPages;
using HslCommunication.Profinet.Siemens.S7PlusHelper;
using Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Schema;

namespace HighWayIot.Winform.UserControlPages
{
    public partial class RecipeConfigPage : UserControl
    {
        /// <summary>
        /// 配方服务类实例
        /// </summary>
        private ZxRecipeService zxRecipeService = ZxRecipeService.Instance;

        /// <summary>
        /// 称重服务类实例
        /// </summary>
        private ZxWeightService zxWeightService = ZxWeightService.Instance;

        /// <summary>
        /// 配方服务类实例
        /// </summary>
        private ZxMaterialService zxMaterialService = ZxMaterialService.Instance;

        /// <summary>
        /// 配方字段服务类实例
        /// </summary>
        private ZxRecipeParaService zxRecipeParaService = ZxRecipeParaService.Instance;

        /// <summary>
        /// 工位配方字段服务类实例
        /// </summary>
        private ZxRecipePositionParaService zxRecipePositionParaService = ZxRecipePositionParaService.Instance;

        /// <summary>
        /// 配方同步服务类实例
        /// </summary>
        private ZxMesPlanTransferService zxMesPlanTransferService = ZxMesPlanTransferService.Instance;

        /// <summary>
        /// 开炼机胶料配置
        /// </summary>
        private ZxOpenMixMaterialService zxOpenMixMaterialService = ZxOpenMixMaterialService.Instance;

        /// <summary>
        /// 开炼机胶料配置列表
        /// </summary>
        private List<ZxOpenMixMaterialEntity> openMixConfig;

        /// <summary>
        /// 配方字段实例
        /// </summary>
        private ZxRecipeParaEntity zxRecipeParaEntity = new ZxRecipeParaEntity();

        /// <summary>
        /// 工位配方字段实例
        /// </summary>
        private List<ZxRecipePositionParaEntity> zxRecipePositionParaEntity = new List<ZxRecipePositionParaEntity>();

        /// <summary>
        /// 称重DataGridView数据源
        /// </summary>
        private List<WeightDataSourceEntity> weightDataSourceEntities;

        /// <summary>
        /// 配方列表
        /// </summary>
        private List<ZxRecipeEntity> RecipeLists;

        /// <summary>
        /// 称量列表
        /// </summary>
        private List<ZxWeightEntity> WeightLists;

        /// <summary>
        /// 现所选配方号
        /// </summary>
        private string NowRecipeCode;

        /// <summary>
        /// 配方字段剪切板
        /// </summary>
        private ZxRecipeParaEntity ParaCopyBoard = new ZxRecipeParaEntity();

        /// <summary>
        /// 工位全部配方字段剪切板
        /// </summary>
        private List<ZxRecipePositionParaEntity> PositionParaCopyBoard = new List<ZxRecipePositionParaEntity>();

        /// <summary>
        /// 工位单个配方字段剪切板
        /// </summary>
        private ZxRecipePositionParaEntity SingalPositionParaCopyBoard;

        /// <summary>
        /// PLC实例
        /// </summary>
        private RecipeParaHelper recipeParaHelper = new RecipeParaHelper();

        public RecipeConfigPage()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            RecipeDataGridView.AutoGenerateColumns = false;
            WeightDataGridView.AutoGenerateColumns = false;

            RecipeLists = zxRecipeService.GetRecipeInfos();

            RecipeDataGridView.DataSource = null;
            RecipeDataGridView.DataSource = RecipeLists;

            NowRecipeCode = RecipeDataGridView.Rows[0].Cells["RecipeCode"].Value.ToString();
            InitPositionEntities();

            try
            {
                var res = PlcConnect.MelsecInstance2.Read("D200", 1);
                if (res.IsSuccess)
                {
                    //读取SPEC编号
                    PlcSpecNoLabel.Text = PlcConnect.MelsecInstance2.ReadUInt32("D206").ToString();
                    //读取SPEC名称
                    PlcSpecNameLabel.Text = PlcConnect.MelsecInstance2.ReadString("D290", 10).ToString();
                }
                else
                {

                }
            }
            catch
            {
                PlcSpecNoLabel.Text = "PLC连接失败";
                PlcSpecNameLabel.Text = "PLC连接失败";
            }

            openMixConfig = zxOpenMixMaterialService.GetInfos();
            Station1MaterialName.Text = openMixConfig.Single(x => x.StationNo == 1).MaterialName;
            Station2MaterialName.Text = openMixConfig.Single(x => x.StationNo == 2).MaterialName;
            Station3MaterialName.Text = openMixConfig.Single(x => x.StationNo == 3).MaterialName;
            Station4MaterialName.Text = openMixConfig.Single(x => x.StationNo == 4).MaterialName;
            Station5MaterialName.Text = openMixConfig.Single(x => x.StationNo == 5).MaterialName;

        }

        #region 配方信息

        /// <summary>
        /// 所选配方内容更改事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RecipeDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            int a = RecipeDataGridView.CurrentRow.Index;
            NowRecipeCode = RecipeDataGridView.Rows[a].Cells["RecipeCode"].Value.ToString();
            SpecNoLabel.Text = RecipeDataGridView.Rows[a].Cells["RecipeSpecCode"].Value.ToString();
            SpecNameLabel.Text = RecipeDataGridView.Rows[a].Cells["RecipeSpecName"].Value.ToString();

            WeightLists = zxWeightService.GetWeightInfos(NowRecipeCode);

            //WeightToDataSource();

            WeightDataGridView.DataSource = null;
            WeightDataGridView.DataSource = WeightLists;

            ParaRefresh();
        }

        /// <summary>
        /// 添加配方信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddRecipeButton_Click(object sender, EventArgs e)
        {
            AddRecipeForm form = new AddRecipeForm();
            if (form.ShowDialog() == DialogResult.OK)
            {   
                if(form.CloseValue == null)
                {
                    return;
                }
                //PLC字段更新
                ZxRecipeParaEntity paraEntity = new ZxRecipeParaEntity()
                {
                    SpecCode = form.CloseValue.RecipeSpecCode,
                    SpecName = form.CloseValue.RecipeSpecName,
                    RecipeCode = form.CloseValue.RecipeCode,
                    LightWidth = (int)form.CloseValue.FixedWidth,
                    RimInch = (int)form.CloseValue.SizeKind,
                };
                zxRecipeParaService.InsertRecipeParaInfo(paraEntity);

                RecipeLists = zxRecipeService.GetRecipeInfos();
                RecipeDataGridView.DataSource = null;
                RecipeDataGridView.DataSource = RecipeLists;
            }

        }

        /// <summary>
        /// 删除配方信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeleteRecipeButton_Click(object sender, EventArgs e)
        {
            int a = RecipeDataGridView.CurrentRow.Index;

            //string s = RecipeDataGridView.Rows[a].Cells["RecipeCode"].Value.ToString();
            int id;
            try
            {
                id = int.Parse(RecipeDataGridView.Rows[a].Cells["RId"].Value.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show("ID转换发生错误" + ex.Message);
                return;
            }

            if (MessageBox.Show($"确定要删除编号为 [{NowRecipeCode}] 的配方信息?", "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }

            if (zxWeightService.GetWeightInfos(NowRecipeCode).Count > 0)
            {
                if (MessageBox.Show("是否要删除其关联的所有称量信息？", "确认", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    if (zxWeightService.DeleteWeightInfoByRecipeCode(NowRecipeCode))
                    {
                        MessageBox.Show("称量信息删除成功");
                    }
                    else
                    {
                        MessageBox.Show("称量信息删除失败！请检查数据库连接情况");
                    }
                }
            }

            //删除硫化配方防止报错
            List<ZxSchedulingEntity> schedulingEntity = ZxSchedulingService.Instance.GetSchedulingInfo();
            var updateInfos = schedulingEntity.Where(x => x.RecipeCode1 == NowRecipeCode || x.RecipeCode2 == NowRecipeCode).ToList();
            foreach (var entity in updateInfos)
            {
                if (entity.RecipeCode1 == NowRecipeCode)
                {
                    entity.RecipeCode1 = string.Empty;
                    entity.RecipeName1 = string.Empty;
                }

                if (entity.RecipeCode2 == NowRecipeCode)
                {
                    entity.RecipeCode2 = string.Empty;
                    entity.RecipeName2 = string.Empty;
                }
            }
            ZxSchedulingService.Instance.UpdateSchedulingInfo(updateInfos);

            if (zxRecipeService.DeleteRecipeInfoById(id))
            {
                MessageBox.Show("配方信息删除成功！");
            }
            else
            {
                MessageBox.Show("配方信息删除失败！请检查数据库连接情况");
            }

            RecipeLists = zxRecipeService.GetRecipeInfos();

            RecipeDataGridView.DataSource = null;
            RecipeDataGridView.DataSource = RecipeLists;
        }

        /// <summary>
        /// 修改配方信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateRecipeButton_Click(object sender, EventArgs e)
        {
            DataGridViewRow nowRow = RecipeDataGridView.CurrentRow;

            if (MessageBox.Show($"确认要更改编号为 [{nowRow.Cells["RecipeCode"].Value.ToString()}] 配方的数据吗", "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }

            ZxRecipeEntity entity = new ZxRecipeEntity();

            try
            {
                entity.Id = int.Parse(nowRow.Cells["RId"].Value.ToString().Trim());
                entity.RecipeCode = nowRow.Cells["RecipeCode"].Value.ToString().Trim();
                entity.RecipeName = nowRow.Cells["RecipeName"].Value.ToString().Trim();
                entity.RecipeSpecCode = nowRow.Cells["RecipeSpecCode"].Value.ToString().Trim();
                entity.RecipeSpecName = nowRow.Cells["RecipeSpecName"].Value.ToString().Trim();
                entity.SizeKind = int.Parse(Convert.ToString(nowRow.Cells["SizeKind"].Value) ?? "0");
                entity.FixedWidth = decimal.Parse(Convert.ToString(nowRow.Cells["FixedWidth"].Value) ?? "0");
                entity.WeightError = int.Parse(Convert.ToString(nowRow.Cells["WeightError"].Value) ?? "0");
                entity.IsUse = bool.Parse(Convert.ToString(nowRow.Cells["IsUse"].Value) ?? "0");
                entity.IsDeleted = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据格式错误！" + ex.Message);
                return;
            }

            if (zxRecipeService.UpdateRecipeInfo(entity))
            {
                //PLC字段更新
                ZxRecipeParaEntity paraentity = zxRecipeParaService.GetRecipeParaInfoByRecipeCode(entity.RecipeCode).FirstOrDefault();
                paraentity.RimInch = entity.SizeKind;
                paraentity.LightWidth = (int)entity.FixedWidth;
                zxRecipeParaService.UpdateRecipeParaInfo(paraentity);
                MessageBox.Show("配方更新成功！");
            }
            else
            {
                MessageBox.Show("配方更新失败！");
            }

            RecipeLists = zxRecipeService.GetRecipeInfos();

            RecipeDataGridView.DataSource = null;
            RecipeDataGridView.DataSource = RecipeLists;
        }

        /// <summary>
        /// 刷新配方信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RefreshRecipeButton_Click(object sender, EventArgs e)
        {
            RecipeLists = zxRecipeService.GetRecipeInfos();
            RecipeDataGridView.DataSource = null;
            RecipeDataGridView.DataSource = RecipeLists;
        }

        #endregion

        #region 称量信息

        /// <summary>
        /// 添加称量信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddWeightButton_Click(object sender, EventArgs e)
        {
            if (RecipeDataGridView.CurrentRow == null)
            {
                MessageBox.Show("请先选择一条配方！");
                return;
            }

            AddWeightForm form = new AddWeightForm(NowRecipeCode);
            if (form.ShowDialog() == DialogResult.OK)
            {
                if (form.OutValue == null)
                {
                    return;
                }
                //连同更新PLC字段信息
                var config = openMixConfig.Where(x => x.MaterialName == form.OutValue.MaterialName).FirstOrDefault();
                if (config != null)
                {
                    //更新公众参数
                    ZxRecipeParaEntity recipePara = zxRecipeParaService.GetRecipeParaInfoByRecipeCode(form.OutValue.RecipeCode).FirstOrDefault();
                    var prop = recipePara.GetType().GetProperty($"S{config.StationNo + 1}");
                    prop.SetValue(recipePara, true);
                    zxRecipeParaService.UpdateRecipeParaInfo(recipePara);
                    //更新字段
                    var positionInfo = zxRecipePositionParaService.GetRecipePositionParaInfos(x => x.Position == config.StationNo && x.RecipeCode == NowRecipeCode);
                    if(positionInfo.Count == 0)
                    {
                        ZxRecipePositionParaEntity zxRecipePositionParaEntity = new ZxRecipePositionParaEntity()
                        {
                            RecipeCode = NowRecipeCode,
                            Position = config.StationNo,
                            E5 = form.OutValue.SetLayer,
                            E9 = (int)form.OutValue.SetWidth,
                            E6 = form.OutValue.SetLayer2,
                            E7 = (int)form.OutValue.SetWidth2,
                        };
                        zxRecipePositionParaService.InsertRecipePositionParaInfo(zxRecipePositionParaEntity);
                    }
                    else
                    {
                        var entity = positionInfo.FirstOrDefault();
                        entity.E5 = form.OutValue.SetLayer;
                        entity.E9 = (int)form.OutValue.SetWidth;
                        entity.E6 = form.OutValue.SetLayer2;
                        entity.E7 = (int)form.OutValue.SetWidth2;
                        zxRecipePositionParaService.UpdateRecipePositionParaInfo(entity);
                    }
                }
            }

            ParaRefresh();

            WeightLists = zxWeightService.GetWeightInfos(NowRecipeCode);

            //WeightToDataSource();

            WeightDataGridView.DataSource = null;
            WeightDataGridView.DataSource = WeightLists;
        }

        /// <summary>
        /// 删除称量信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeleteWeightButton_Click(object sender, EventArgs e)
        {
            int a = WeightDataGridView.CurrentRow.Index;
            string s2 = WeightDataGridView.Rows[a].Cells["MaterialCode"].Value.ToString();
            int id;
            try
            {
                id = int.Parse(WeightDataGridView.Rows[a].Cells["Id"].Value.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show("ID转换发生错误" + ex.Message);
                return;
            }

            if (MessageBox.Show($"确定要删除配方编号为 [{NowRecipeCode}] 物料编码为 [{s2}] 的称重信息?", "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }

            if (zxWeightService.DeleteWeightInfoById(id))
            {
                MessageBox.Show("配方信息删除成功！");
            }
            else
            {
                MessageBox.Show("配方信息删除失败！请检查数据库连接情况");
            }

            WeightLists = zxWeightService.GetWeightInfos(NowRecipeCode);

            //WeightToDataSource();

            WeightDataGridView.DataSource = null;
            WeightDataGridView.DataSource = WeightLists;
        }

        /// <summary>
        /// 修改称量信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateWeightButton_Click(object sender, EventArgs e)
        {
            DataGridViewRow nowRow = WeightDataGridView.CurrentRow;

            if (MessageBox.Show($"确认要更改配方编号为 [{NowRecipeCode}] 物料编号为 [{nowRow.Cells["MaterialCode"].Value.ToString()}] 的数据吗"
                , "确认"
                , MessageBoxButtons.OKCancel)
                == DialogResult.Cancel)
            {
                return;
            }

            ZxWeightEntity entity = new ZxWeightEntity();

            try
            {
                entity.Id = int.Parse(nowRow.Cells["Id"].Value.ToString().Trim());
                entity.RecipeCode = NowRecipeCode;
                entity.MaterialCode = nowRow.Cells["MaterialCode"].Value.ToString().Trim();
                entity.MaterialName = nowRow.Cells["MaterialName"].Value.ToString().Trim();
                entity.MaterialType = nowRow.Cells["MaterialType"].Value.ToString().Trim();
                entity.SetThickness = decimal.Parse(Convert.ToString(nowRow.Cells["SetThickness"].Value ?? "0"));
                entity.SetWidth = decimal.Parse(Convert.ToString(nowRow.Cells["SetWidth1"].Value ?? "0"));
                entity.SetWidth2 = decimal.Parse(Convert.ToString(nowRow.Cells["SetWidth2"].Value ?? "0"));
                entity.SetLayer = int.Parse(Convert.ToString(nowRow.Cells["SetLayer1"].Value ?? "0"));
                entity.SetLayer2 = int.Parse(Convert.ToString(nowRow.Cells["SetLayer2"].Value ?? "0"));
                entity.SetWeight = decimal.Parse(Convert.ToString(nowRow.Cells["SetWeight"].Value ?? "0"));
                entity.SetError = decimal.Parse(Convert.ToString(nowRow.Cells["SetError"].Value ?? "0"));
                entity.IsUse = bool.Parse(Convert.ToString(nowRow.Cells["WeightIsUse"].Value));
                entity.IsDeleted = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据格式错误！" + ex.Message);
                return;
            }

            if (zxWeightService.UpdateWeightInfo(entity))
            {
                //连同更新PLC字段信息
                var config = openMixConfig.Where(x => x.MaterialName == entity.MaterialName).FirstOrDefault();
                if (config != null)
                {
                    var positionInfo = zxRecipePositionParaService.GetRecipePositionParaInfos(x => x.Position == config.StationNo && x.RecipeCode == NowRecipeCode);
                    if (positionInfo.Count == 0)
                    {
                        ZxRecipePositionParaEntity zxRecipePositionParaEntity = new ZxRecipePositionParaEntity()
                        {
                            RecipeCode = NowRecipeCode,
                            Position = config.StationNo,
                            E5 = entity.SetLayer,
                            E9 = (int)entity.SetWidth,
                            E6 = entity.SetLayer2,
                            E7 = (int)entity.SetWidth2,
                        };
                        zxRecipePositionParaService.InsertRecipePositionParaInfo(zxRecipePositionParaEntity);
                    }
                    else
                    {
                        var positionEntity = positionInfo.FirstOrDefault();
                        positionEntity.E5 = entity.SetLayer;
                        positionEntity.E9 = (int)entity.SetWidth;
                        positionEntity.E6 = entity.SetLayer2;
                        positionEntity.E7 = (int)entity.SetWidth2;
                        zxRecipePositionParaService.UpdateRecipePositionParaInfo(positionEntity);
                    }
                }
                MessageBox.Show("成型信息更新成功！");
            }
            else
            {
                MessageBox.Show("成型信息更新失败！");
            }

            ParaRefresh();

            WeightLists = zxWeightService.GetWeightInfos(NowRecipeCode);

            //WeightToDataSource();

            WeightDataGridView.DataSource = null;
            WeightDataGridView.DataSource = WeightLists;
        }

        /// <summary>
        /// 刷新称量信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RefreshWeightButton_Click(object sender, EventArgs e)
        {
            WeightLists = zxWeightService.GetWeightInfos(NowRecipeCode);

            //WeightToDataSource();

            WeightDataGridView.DataSource = null;
            WeightDataGridView.DataSource = WeightLists;
        }

        /// <summary>
        /// 称重数据关联物料数据
        /// </summary>
        private void WeightToDataSource()
        {
            weightDataSourceEntities = new List<WeightDataSourceEntity>();
            foreach (var item in WeightLists)
            {
                var entitys = zxMaterialService.GetEntityByMaterialCode(item.MaterialCode);

                if (entitys == null && entitys.Count == 0)
                {
                    return;
                }

                if (entitys.Count > 1)
                {
                    MessageBox.Show("请检查是否有多条物料编号相同的可用物料");
                    return;
                }

                ZxMaterialEntity material = new ZxMaterialEntity();
                if (entitys.Count > 0)
                {
                    material = entitys[0];
                }

                weightDataSourceEntities.Add(new WeightDataSourceEntity()
                {
                    Id = item.Id,
                    RecipeCode = item.RecipeCode,
                    MaterialCode = item.MaterialCode,
                    MaterialName = material.MaterialName,
                    MaterialType = material.MaterialType,
                    MaterialChildType = material.ChildType,
                    SetThickness = item.SetThickness,
                    SetWidth = item.SetWidth,
                    SetLayer = item.SetLayer,
                    SetWeight = item.SetWeight,
                    SetError = item.SetError,
                    IsUse = item.IsUse,
                });
            }
        }

        #endregion

        #region 参数设置

        /// <summary>
        /// 参数刷新
        /// </summary>
        private void ParaRefresh()
        {
            //初始化工位参数类
            InitPositionEntities();

            //设置参数
            var paraData = zxRecipeParaService.GetRecipeParaInfoByRecipeCode(NowRecipeCode);
            int flag = GetSelectIndex();
            var positionParaData = zxRecipePositionParaService.GetRecipePositionParaInfos(x => x.RecipeCode == NowRecipeCode);

            //没有就全0
            if (paraData.Count == 0)
            {
                SetPublicParaValue(new ZxRecipeParaEntity());
                zxRecipeParaEntity = new ZxRecipeParaEntity();
            }
            //有就显示
            else if (paraData.Count == 1)
            {
                SetPublicParaValue(paraData[0]);
                zxRecipeParaEntity = paraData[0];
            }
            //有多条设为第一条
            else
            {
                MessageBox.Show("存在多条未删除的相同公共配方字段信息！将设置为第一条。点击清除脏数据");
                SetPublicParaValue(paraData[0]);
                zxRecipeParaEntity = paraData[0];
            }

            //没有就全0
            if (positionParaData.Count == 0)
            {
                SetPrivateParaValue(new ZxRecipePositionParaEntity());
            }
            else
            {
                foreach (var item in positionParaData)
                {
                    ChangePositionEntities(item);
                }
                SetPrivateParaValue(zxRecipePositionParaEntity.Where(x => x.Position == flag).FirstOrDefault());
            }
        }

        /// <summary>
        /// 参数保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveParaButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show($"确定要保存配方编号为 [{NowRecipeCode}] 的配方的参数？", "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }

            var index = GetSelectIndex();
            //从前端更新值
            GetPublicParaValue();
            GetPrivateParaValue(index);

            //查重
            var paraEntity = zxRecipeParaService.GetRecipeParaInfoByRecipeCode(NowRecipeCode);
            var positionParaEntity = zxRecipePositionParaService.GetRecipePositionParaInfoByRecipeCode(NowRecipeCode);

            zxRecipeParaEntity.RecipeCode = NowRecipeCode;
            //保存公共参数
            var flag1 = true;
            if (paraEntity.Count == 0) //没有就插入
            {
                flag1 = zxRecipeParaService.InsertRecipeParaInfo(zxRecipeParaEntity);
            }
            else if (paraEntity.Count == 1) //有就更新
            {
                zxRecipeParaEntity.Id = paraEntity[0].Id;
                flag1 = zxRecipeParaService.UpdateRecipeParaInfo(zxRecipeParaEntity);
            }
            else //多条更新第一条
            {
                zxRecipeParaEntity.Id = paraEntity[0].Id;
                flag1 = zxRecipeParaService.UpdateRecipeParaInfo(zxRecipeParaEntity);
                MessageBox.Show("存在多条未删除的相同公共配方字段信息！将设置为第一条。点击清除脏数据");
            }


            //保存贴合参数
            var flag2 = true;
            foreach (var item in zxRecipePositionParaEntity)
            {
                item.RecipeCode = NowRecipeCode;
                var count = positionParaEntity.Count(x => x.Position == item.Position);
                //如果没有
                if (count == 0)
                {
                    flag2 = zxRecipePositionParaService.InsertRecipePositionParaInfo(item);
                }
                else //有 多条存第一条
                {
                    item.Id = positionParaEntity.FirstOrDefault(x => x.Position == item.Position).Id;
                    flag2 = zxRecipePositionParaService.UpdateRecipePositionParaInfo(item);

                    if (count != 1) //多条提示
                    {
                        MessageBox.Show("存在多条未删除的相同公共配方字段信息！将设置为第一条。点击清除脏数据");
                    }
                }
                if (!flag2) break;
            }

            if (flag1 && flag2)
            {
                BaseForm.LogRefreshAction.Invoke("更新成功");
            }
            else
            {
                BaseForm.LogRefreshAction.Invoke("更新失败");
            }
            //保存贴合参数
        }

        /// <summary>
        /// 初始化工位参数
        /// </summary>
        private void InitPositionEntities()
        {
            zxRecipePositionParaEntity.Clear();

            zxRecipePositionParaEntity.Add(new ZxRecipePositionParaEntity()
            {
                Position = 1
            });

            zxRecipePositionParaEntity.Add(new ZxRecipePositionParaEntity()
            {
                Position = 2
            });

            zxRecipePositionParaEntity.Add(new ZxRecipePositionParaEntity()
            {
                Position = 3
            });

            zxRecipePositionParaEntity.Add(new ZxRecipePositionParaEntity()
            {
                Position = 4
            });

            zxRecipePositionParaEntity.Add(new ZxRecipePositionParaEntity()
            {
                Position = 5
            });
        }

        /// <summary>
        /// 替换工位信息中的元素
        /// </summary>
        /// <param name="entity"></param>
        private void ChangePositionEntities(ZxRecipePositionParaEntity entity)
        {
            int index = zxRecipePositionParaEntity.FindIndex(x => x.Position == entity.Position);
            if (index == -1)
            {
                BaseForm.LogRefreshAction.Invoke($"[{entity.RecipeCode}]工位信息数据未找到");
                return;
            }
            zxRecipePositionParaEntity[index] = entity;
        }


        /// <summary>
        /// 设置显示的贴合参数字段值
        /// </summary>
        /// <param name="entity"></param>
        private void SetPrivateParaValue(ZxRecipePositionParaEntity entity)
        {
            E1TextBox.Text = GeneralUtils.IntEmptyOrToString(entity.E1);
            E2TextBox.Text = GeneralUtils.IntEmptyOrToString(entity.E2);
            E3TextBox.Text = GeneralUtils.IntEmptyOrToString(entity.E3);
            E4TextBox.Text = GeneralUtils.IntEmptyOrToString(entity.E4);
            E5TextBox.Text = GeneralUtils.IntEmptyOrToString(entity.E5);
            E6TextBox.Text = GeneralUtils.IntEmptyOrToString(entity.E6);
            E7TextBox.Text = GeneralUtils.IntEmptyOrToString(entity.E7);
            E8TextBox.Text = GeneralUtils.IntEmptyOrToString(entity.E8);
            E9TextBox.Text = GeneralUtils.IntEmptyOrToString(entity.E9);
            E10TextBox.Text = GeneralUtils.IntEmptyOrToString(entity.E10);
        }

        /// <summary>
        /// 设置公共参数
        /// </summary>
        /// <param name="paraEntity"></param>
        private void SetPublicParaValue(ZxRecipeParaEntity paraEntity)
        {
            S2Check.Checked = paraEntity.S2 ?? false;
            S3Check.Checked = paraEntity.S3 ?? false;
            S4Check.Checked = paraEntity.S4 ?? false;
            S5Check.Checked = paraEntity.S5 ?? false;
            S6Check.Checked = paraEntity.S6 ?? false;
            S7Check.Checked = paraEntity.S7 ?? false;
            S8Check.Checked = paraEntity.S8 ?? false;
            S9Check.Checked = paraEntity.S9 ?? false;

            RimInchTextBox.Text = GeneralUtils.IntEmptyOrToString(paraEntity.RimInch);
            LightWidthTextBox.Text = GeneralUtils.IntEmptyOrToString(paraEntity.LightWidth);
            SlowDistanceTextBox.Text = GeneralUtils.IntEmptyOrToString(paraEntity.SlowDistance);
            StopDistanceTextBox.Text = GeneralUtils.IntEmptyOrToString(paraEntity.StopDistance);
            TireWeightTextBox.Text = paraEntity.TireWeight == null ? "0" : paraEntity.TireWeight.ToString();
            //SpecNoLabel.Text = GeneralUtils.IntEmptyOrToString(paraEntity.SpecCode);
            //SpecNameLabel.Text = paraEntity.SpecName;
        }

        /// <summary>
        /// 贴合参数获取值 存到实体
        /// </summary>
        /// <returns></returns>
        private void GetPrivateParaValue(int flag)
        {
            var e = zxRecipePositionParaEntity.FirstOrDefault(x => x.Position == flag);

            e.E1 = GeneralUtils.StringNullOrToInt(E1TextBox.Text);
            e.E2 = GeneralUtils.StringNullOrToInt(E2TextBox.Text);
            e.E3 = GeneralUtils.StringNullOrToInt(E3TextBox.Text);
            e.E4 = GeneralUtils.StringNullOrToInt(E4TextBox.Text);
            e.E5 = GeneralUtils.StringNullOrToInt(E5TextBox.Text);
            e.E6 = GeneralUtils.StringNullOrToInt(E6TextBox.Text);
            e.E7 = GeneralUtils.StringNullOrToInt(E7TextBox.Text);
            e.E8 = GeneralUtils.StringNullOrToInt(E8TextBox.Text);
            e.E9 = GeneralUtils.StringNullOrToInt(E9TextBox.Text);
            e.E10 = GeneralUtils.StringNullOrToInt(E10TextBox.Text);
            e.Position = GetSelectIndex();
            e.RecipeCode = NowRecipeCode;

            ChangePositionEntities(e);
        }

        /// <summary>
        /// 公共参数获取值 存到实体
        /// </summary>
        /// <returns></returns>
        private void GetPublicParaValue()
        {
            zxRecipeParaEntity.S2 = S2Check.Checked;
            zxRecipeParaEntity.S3 = S3Check.Checked;
            zxRecipeParaEntity.S4 = S4Check.Checked;
            zxRecipeParaEntity.S5 = S5Check.Checked;
            zxRecipeParaEntity.S6 = S6Check.Checked;
            zxRecipeParaEntity.S7 = S7Check.Checked;
            zxRecipeParaEntity.S8 = S8Check.Checked;
            zxRecipeParaEntity.S9 = S9Check.Checked;
            zxRecipeParaEntity.RimInch = GeneralUtils.StringNullOrToInt(RimInchTextBox.Text);
            zxRecipeParaEntity.LightWidth = GeneralUtils.StringNullOrToInt(LightWidthTextBox.Text);
            zxRecipeParaEntity.SlowDistance = GeneralUtils.StringNullOrToInt(SlowDistanceTextBox.Text);
            zxRecipeParaEntity.StopDistance = GeneralUtils.StringNullOrToInt(StopDistanceTextBox.Text);
            try
            {
                zxRecipeParaEntity.TireWeight = float.Parse(TireWeightTextBox.Text == string.Empty ? "0" : TireWeightTextBox.Text);
            }
            catch
            {
                MessageBox.Show("胎体重量请输入整数或小数");
            }
            zxRecipeParaEntity.SpecCode = SpecNoLabel.Text;
            zxRecipeParaEntity.SpecName = SpecNameLabel.Text;
        }

        /// <summary>
        /// 工位改变 保存现在的，显示换的
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PositionRadioBoxChange(object sender, EventArgs e)
        {
            RadioButton s = sender as RadioButton;

            if (s.Checked)
            {
                int flag = GetSelectIndex();

                SetPrivateParaValue(zxRecipePositionParaEntity.Where(x => x.Position == flag).FirstOrDefault());
            }
        }

        /// <summary>
        /// 获取选择的工位包边
        /// </summary>
        /// <returns>选的不对劲就返回0</returns>
        private int GetSelectIndex()
        {
            if (Position1RadioButton.Checked)
            {
                return 1;
            }

            if (Position2RadioButton.Checked)
            {
                return 2;
            }

            if (Position3RadioButton.Checked)
            {
                return 3;
            }

            if (Position4RadioButton.Checked)
            {
                return 4;
            }

            if (Position5RadioButton.Checked)
            {
                return 5;
            }

            return 0;
        }

        /// <summary>
        /// 暂存工位参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PositionRadioButton_MouseDown(object sender, MouseEventArgs e)
        {
            int index = GetSelectIndex();

            GetPrivateParaValue(index);

            BaseForm.LogRefreshAction.Invoke($"[{index.ToString()}] 工位参数已暂存");
        }

        /// <summary>
        /// 公共参数复制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CopyParaButton_Click(object sender, EventArgs e)
        {
            ParaCopyBoard = zxRecipeParaEntity;
            NowCopyLabel.Text = NowRecipeCode;
        }

        /// <summary>
        /// 公共参数粘贴
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PasteParaButton_Click(object sender, EventArgs e)
        {
            if (ParaCopyBoard == null)
            {
                MessageBox.Show("剪切板为空！");
                return;
            }
            SetPublicParaValue(ParaCopyBoard);
        }

        /// <summary>
        /// 贴合参数复制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CopyPositionButton_Click(object sender, EventArgs e)
        {
            var index = GetSelectIndex();
            GetPrivateParaValue(index);
            SingalPositionParaCopyBoard = zxRecipePositionParaEntity.FirstOrDefault(x => x.Position == index);
            PositionCopyBoardLabel.Text = index.ToString() + "|" + NowRecipeCode;
        }

        /// <summary>
        /// 贴合参数粘贴
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PastePositionButton_Click(object sender, EventArgs e)
        {
            if (SingalPositionParaCopyBoard == null)
            {
                MessageBox.Show("剪切板为空！");
                return;
            }
            SetPrivateParaValue(SingalPositionParaCopyBoard);
        }

        /// <summary>
        /// 整体复制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CopyAllButton_Click(object sender, EventArgs e)
        {
            int index = GetSelectIndex();
            GetPrivateParaValue(index);
            ParaCopyBoard = new ZxRecipeParaEntity()
            {
                S2 = zxRecipeParaEntity.S2 ?? false,
                S3 = zxRecipeParaEntity.S3 ?? false,
                S4 = zxRecipeParaEntity.S4 ?? false,
                S5 = zxRecipeParaEntity.S5 ?? false,
                S6 = zxRecipeParaEntity.S6 ?? false,
                S7 = zxRecipeParaEntity.S7 ?? false,
                S8 = zxRecipeParaEntity.S8 ?? false,
                S9 = zxRecipeParaEntity.S9 ?? false,

                RimInch = zxRecipeParaEntity.RimInch,
                LightWidth = zxRecipeParaEntity.LightWidth,
                SlowDistance = zxRecipeParaEntity.SlowDistance,
                StopDistance = zxRecipeParaEntity.StopDistance,
                TireWeight = zxRecipeParaEntity.TireWeight,
            };
            PositionParaCopyBoard.Clear();
            foreach (var entity in zxRecipePositionParaEntity)
            {
                var clone = new ZxRecipePositionParaEntity()
                {
                    E1 = entity.E1,
                    E2 = entity.E2,
                    E3 = entity.E3,
                    E4 = entity.E4,
                    E5 = entity.E5,
                    E6 = entity.E6,
                    E7 = entity.E7,
                    E8 = entity.E8,
                    E9 = entity.E9,
                    E10 = entity.E10,
                    Position = entity.Position,
                };
                PositionParaCopyBoard.Add(clone);
            }
            //PositionParaCopyBoard = zxRecipePositionParaEntity;
            NowCopyLabel.Text = NowRecipeCode + " 全复制";
            PositionCopyBoardLabel.Text = "全复制";
        }

        /// <summary>
        /// 整体粘贴
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PasteAllButton_Click(object sender, EventArgs e)
        {
            if (zxRecipeParaEntity != null && (zxRecipePositionParaEntity != null || zxRecipePositionParaEntity.Count != 8))
            {
                zxRecipePositionParaEntity = PositionParaCopyBoard;
                zxRecipeParaEntity = ParaCopyBoard;
            }
            else
            {
                MessageBox.Show("粘贴失败，请重新复制数据");
            }

            SetPublicParaValue(zxRecipeParaEntity);
            SetPrivateParaValue(zxRecipePositionParaEntity.First(x => x.Position == GetSelectIndex()));
        }

        /// <summary>
        /// 清除脏数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ClearDirtyData_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show($"确定要清除脏数据？", "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }

            if (zxRecipeParaService.DeleteDirtyData() &&
                zxRecipePositionParaService.DeleteDirtyData())
            {
                MessageBox.Show("清除成功");
            }
            else
            {
                MessageBox.Show("清除失败");
            }
        }

        /// <summary>
        /// 上载到plc
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UploadToPlc_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show($"是否要将此配方下传到PLC？", "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }
            if (!PlcConnect.MelsecInstance2.Read("D200", 1).IsSuccess)
            {
                MessageBox.Show("PLC未连接");
                return;
            }
            GetPublicParaValue();
            GetPrivateParaValue(GetSelectIndex());
            if (recipeParaHelper.UploadToPLC(zxRecipeParaEntity, zxRecipePositionParaEntity))
            {
                MessageBox.Show("下发到PLC成功");
            }
            else
            {
                MessageBox.Show("下发到PLC失败");
            }
            PlcSpecNameLabel.Text = zxRecipeParaEntity.SpecName.Trim();
            PlcSpecNoLabel.Text = zxRecipeParaEntity.SpecCode.Trim();
        }

        /// <summary>
        /// 从plc读取
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DownloadFromPlc_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show($"是否要从PLC读取配方？", "确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }
            if (!PlcConnect.MelsecInstance2.Read("D200", 1).IsSuccess)
            {
                MessageBox.Show("PLC未连接");
                return;
            }
            zxRecipePositionParaEntity = recipeParaHelper.DownLoadFormPlc(ref zxRecipeParaEntity);
            SetPublicParaValue(zxRecipeParaEntity);
            SetPrivateParaValue(zxRecipePositionParaEntity.First(x => x.Position == GetSelectIndex()));
            PlcSpecNameLabel.Text = zxRecipeParaEntity.SpecName.Trim();
            PlcSpecNoLabel.Text = zxRecipeParaEntity.SpecCode.Trim();
        }

        #endregion

        #region 配方数据同步

        /// <summary>
        /// 同步数据按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SyncDataButton_Click(object sender, EventArgs e)
        {
            // RecipeDataSync(zxMesPlanTransferService.GetRecipeInfos(x => x.Uuid != "syncsignal"));
            zxMesPlanTransferService.SetFlagTrue();
            //if (zxMesPlanTransferService.GetFlagState())
            //{
            //    MessageBox.Show("正在同步数据，请稍后");
            //    return;
            //}
            //if (zxMesPlanTransferService.SetFlagTrue())
            //{
            //    Task.Run(() =>
            //    {
            //        while (true)
            //        {
            //            if (!zxMesPlanTransferService.GetFlagState())
            //            {
            //                RecipeDataSync(zxMesPlanTransferService.GetRecipeInfos(x => x.Uuid != "syncsignal"));
            //                MessageBox.Show("同步完成");
            //                return;
            //            }
            //            Task.Delay(1000);
            //        }
            //    });
            //}
        }

        /// <summary>
        /// 配方数据同步方法
        /// </summary>
        private void RecipeDataSync(List<ZxMesPlanTransferEntity> sourceEntity)
        {
            foreach (var newRecipes in sourceEntity)
            {
                //////////////////////////////更新配方表/////////////////////////////////
                var newEneitys = RecipeLists.Where(x => x.RecipeCode == newRecipes.RecipeCode).ToList();
                if (newEneitys.Count > 0)   //有就更新
                {
                    //配方
                    newEneitys[0].RecipeSpecCode = newRecipes.SpecCode;
                    newEneitys[0].RecipeSpecName = newRecipes.SpecName;
                    newEneitys[0].SizeKind = newRecipes.RimInch;
                    newEneitys[0].FixedWidth = newRecipes.FixRubWidth;
                    if (!zxRecipeService.UpdateRecipeInfo(newEneitys[0]))
                    {
                        return;
                    }
                }
                else  //没有就插入
                {
                    ZxRecipeEntity entity = new ZxRecipeEntity()
                    {
                        RecipeName = newRecipes.RecipeName,
                        RecipeCode = newRecipes.RecipeCode,
                        RecipeSpecCode = newRecipes.SpecCode,
                        RecipeSpecName = newRecipes.SpecName,
                        SizeKind = newRecipes.RimInch,
                        FixedWidth = newRecipes.FixRubWidth,
                        IsUse = true,
                        IsDeleted = false,
                    };
                    zxRecipeService.InsertRecipeInfo(entity);
                }

                /////////////////////////////更新称量信息表////////////////////////////////
                string recipeCode = newRecipes.RecipeCode;
                var material1 = zxMaterialService.GetMaterialInfoByMaterialName(newRecipes.MaterialName1);
                var material2 = zxMaterialService.GetMaterialInfoByMaterialName(newRecipes.MaterialName2);
                var material3 = zxMaterialService.GetMaterialInfoByMaterialName(newRecipes.MaterialName3);
                //物料1
                if (!string.IsNullOrEmpty(newRecipes.MaterialName1))
                {
                    if (material1 != null) //有这个物料
                    {
                        //查询是否有这个配方这个物料的称量 有更改 没有添加
                        var weightInfo = zxWeightService.GetWeightInfos(recipeCode, material1.MaterialCode, "基部胶");
                        if (weightInfo == null)
                        {
                            bool a = zxWeightService.InsertWeightInfo(new ZxWeightEntity()
                            {
                                RecipeCode = recipeCode,
                                MaterialCode = material1.MaterialCode,
                                MaterialName = material1.MaterialName,
                                MaterialType = "基部胶",
                                SetWidth = (decimal?)newRecipes.MaterialWidth1,
                                SetWeight = (decimal?)newRecipes.MaterialWeight1,
                                SetLayer = newRecipes.MaterialLayers1,
                                IsDeleted = false,
                                IsUse = true
                            });
                        }
                        else
                        {
                            weightInfo.SetWidth = (decimal?)newRecipes.MaterialWidth1;
                            weightInfo.SetWeight = (decimal?)newRecipes.MaterialWeight1;
                            weightInfo.SetLayer = newRecipes.MaterialLayers1;
                            zxWeightService.UpdateWeightInfo(weightInfo);
                        }
                    }
                    else //没这个物料
                    {
                        //先添加物料
                        material1 = new ZxMaterialEntity()
                        {
                            MaterialCode = DateTime.Now.ToString("yyyyMMddHHmmssffff"),
                            MaterialName = newRecipes.MaterialName1,
                            MaterialType = "胶料",
                            IsDeleted = false,
                            IsUse = true
                        };
                        zxMaterialService.InsertMaterialInfo(material1);
                        //查询是否有这个配方这个物料的称量 有更改 没有添加
                        var weightInfo = zxWeightService.GetWeightInfos(recipeCode, material1.MaterialCode, "基部胶");
                        if (weightInfo == null) //没有配方数据
                        {
                            zxWeightService.InsertWeightInfo(new ZxWeightEntity()
                            {
                                RecipeCode = recipeCode,
                                MaterialCode = material1.MaterialCode,
                                MaterialName = material1.MaterialName,
                                MaterialType = "基部胶",
                                SetWidth = (decimal?)newRecipes.MaterialWidth1,
                                SetWeight = (decimal?)newRecipes.MaterialWeight1,
                                SetLayer = newRecipes.MaterialLayers1,
                                IsDeleted = false,
                                IsUse = true
                            });
                        }
                        else //有配方数据
                        {
                            weightInfo.SetWidth = (decimal?)newRecipes.MaterialWidth1;
                            weightInfo.SetWeight = (decimal?)newRecipes.MaterialWeight1;
                            weightInfo.SetLayer = newRecipes.MaterialLayers1;
                            zxWeightService.UpdateWeightInfo(weightInfo);
                        }
                    }
                }
                //物料2
                if (!string.IsNullOrEmpty(newRecipes.MaterialName2))
                {
                    if (material2 != null) //有这个物料
                    {
                        //查询是否有这个配方这个物料的称量 有更改 没有添加
                        var weightInfo = zxWeightService.GetWeightInfos(recipeCode, material2.MaterialCode, "缓冲胶");
                        if (weightInfo == null)
                        {
                            bool a = zxWeightService.InsertWeightInfo(new ZxWeightEntity()
                            {
                                RecipeCode = recipeCode,
                                MaterialCode = material1.MaterialCode,
                                MaterialName = material1.MaterialName,
                                MaterialType = "缓冲胶",
                                SetWidth = (decimal?)newRecipes.MaterialWidth2,
                                SetWeight = (decimal?)newRecipes.MaterialWeight2,
                                SetLayer = newRecipes.MaterialLayers2,
                                IsDeleted = false,
                                IsUse = true
                            });
                        }
                        else
                        {
                            weightInfo.SetWidth = (decimal?)newRecipes.MaterialWidth2;
                            weightInfo.SetWeight = (decimal?)newRecipes.MaterialWeight2;
                            weightInfo.SetLayer = newRecipes.MaterialLayers2;
                            zxWeightService.UpdateWeightInfo(weightInfo);
                        }
                    }
                    else //没这个物料
                    {
                        //先添加物料
                        material2 = new ZxMaterialEntity()
                        {
                            MaterialCode = DateTime.Now.ToString("yyyyMMddHHmmssffff"),
                            MaterialName = newRecipes.MaterialName2,
                            MaterialType = "胶料",
                            IsDeleted = false,
                            IsUse = true
                        };
                        zxMaterialService.InsertMaterialInfo(material2);
                        //查询是否有这个配方这个物料的称量 有更改 没有添加
                        var weightInfo = zxWeightService.GetWeightInfos(recipeCode, material2.MaterialCode, "缓冲胶");
                        if (weightInfo == null) //没有配方数据
                        {
                            zxWeightService.InsertWeightInfo(new ZxWeightEntity()
                            {
                                RecipeCode = recipeCode,
                                MaterialCode = material2.MaterialCode,
                                MaterialName = material2.MaterialName,
                                MaterialType = "缓冲胶",
                                SetWidth = (decimal?)newRecipes.MaterialWidth2,
                                SetWeight = (decimal?)newRecipes.MaterialWeight2,
                                SetLayer = newRecipes.MaterialLayers2,
                                IsDeleted = false,
                                IsUse = true
                            });
                        }
                        else //有配方数据
                        {
                            weightInfo.SetWidth = (decimal?)newRecipes.MaterialWidth2;
                            weightInfo.SetWeight = (decimal?)newRecipes.MaterialWeight2;
                            weightInfo.SetLayer = newRecipes.MaterialLayers2;
                            zxWeightService.UpdateWeightInfo(weightInfo);
                        }
                    }
                }

                //物料3
                if (!string.IsNullOrEmpty(newRecipes.MaterialName3))
                {
                    if (material3 != null) //有这个物料
                    {
                        //查询是否有这个配方这个物料的称量 有更改 没有添加
                        var weightInfo = zxWeightService.GetWeightInfos(recipeCode, material3.MaterialCode, "胎面胶");
                        if (weightInfo == null)
                        {
                            bool a = zxWeightService.InsertWeightInfo(new ZxWeightEntity()
                            {
                                RecipeCode = recipeCode,
                                MaterialCode = material3.MaterialCode,
                                MaterialName = material3.MaterialName,
                                MaterialType = "胎面胶",
                                SetWidth = (decimal?)newRecipes.MaterialWidth3,
                                SetWeight = (decimal?)newRecipes.MaterialWeight3,
                                SetLayer = newRecipes.MaterialLayers3,
                                IsDeleted = false,
                                IsUse = true
                            });
                        }
                        else
                        {
                            weightInfo.SetWidth = (decimal?)newRecipes.MaterialWidth3;
                            weightInfo.SetWeight = (decimal?)newRecipes.MaterialWeight3;
                            weightInfo.SetLayer = newRecipes.MaterialLayers3;
                            zxWeightService.UpdateWeightInfo(weightInfo);
                        }
                    }
                    else //没这个物料
                    {
                        //先添加物料
                        material3 = new ZxMaterialEntity()
                        {
                            MaterialCode = DateTime.Now.ToString("yyyyMMddHHmmssffff"),
                            MaterialName = newRecipes.MaterialName3,
                            MaterialType = "胶料",
                            IsDeleted = false,
                            IsUse = true
                        };
                        zxMaterialService.InsertMaterialInfo(material3);
                        //查询是否有这个配方这个物料的称量 有更改 没有添加
                        var weightInfo = zxWeightService.GetWeightInfos(recipeCode, material3.MaterialCode, "胎面胶");
                        if (weightInfo == null) //没有配方数据
                        {
                            zxWeightService.InsertWeightInfo(new ZxWeightEntity()
                            {
                                RecipeCode = recipeCode,
                                MaterialCode = material3.MaterialCode,
                                MaterialName = material3.MaterialName,
                                MaterialType = "胎面胶",
                                SetWidth = (decimal?)newRecipes.MaterialWidth3,
                                SetWeight = (decimal?)newRecipes.MaterialWeight3,
                                SetLayer = newRecipes.MaterialLayers3,
                                IsDeleted = false,
                                IsUse = true
                            });
                        }
                        else //有配方数据
                        {
                            weightInfo.SetWidth = (decimal?)newRecipes.MaterialWidth3;
                            weightInfo.SetWeight = (decimal?)newRecipes.MaterialWeight3;
                            weightInfo.SetLayer = newRecipes.MaterialLayers3;
                            zxWeightService.UpdateWeightInfo(weightInfo);
                        }
                    }
                }

                /////////////////////////////////////更新配方参数//////////////////////////////////////
                ZxRecipeParaEntity recipePara = zxRecipeParaService.GetRecipeParaInfoByRecipeCode(recipeCode).FirstOrDefault();
                if (recipePara == null) //不存早
                {
                    recipePara = new ZxRecipeParaEntity()
                    {
                        SpecName = newRecipes.SpecName,
                        SpecCode = newRecipes.SpecCode,
                        RimInch = newRecipes.RimInch,
                        LightWidth = newRecipes.FixRubWidth,
                        TireWeight = newRecipes.TireWeight,
                        RecipeCode = recipeCode
                    };

                    foreach (var config in openMixConfig) //工位选择设置
                    {
                        if (config.MaterialName == material1.MaterialName
                            || config.MaterialName == material2.MaterialName
                            || config.MaterialName == material3.MaterialName)
                        {
                            try
                            {
                                var prop = recipePara.GetType().GetProperty($"S{config.StationNo + 1}");
                                prop.SetValue(recipePara, true);
                            }
                            catch
                            {
                                return;
                            }
                        }
                    }

                    zxRecipeParaService.InsertRecipeParaInfo(recipePara);
                }
                else //存在
                {
                    recipePara.SpecName = newRecipes.SpecName;
                    recipePara.SpecCode = newRecipes.SpecCode;
                    recipePara.RimInch = newRecipes.RimInch;
                    recipePara.LightWidth = newRecipes.FixRubWidth;
                    recipePara.TireWeight = newRecipes.TireWeight;

                    foreach (var config in openMixConfig) //工位选择设置
                    {
                        if (config.MaterialName == material1.MaterialName
                            || config.MaterialName == material2.MaterialName
                            || config.MaterialName == material3.MaterialName)
                        {
                            try
                            {
                                var prop = recipePara.GetType().GetProperty($"S{config.StationNo + 1}");
                                prop.SetValue(recipePara, true);
                            }
                            catch
                            {
                                return;
                            }
                        }
                    }

                    zxRecipeParaService.UpdateRecipeParaInfo(recipePara);
                }

                /////////////////////////////////////更新配方工位参数//////////////////////////////////////
                List<ZxRecipePositionParaEntity> positionParaEntities = zxRecipePositionParaService.GetRecipePositionParaInfoByRecipeCode(recipeCode);

                int position = 1;
                for (int i = 0; i < 5; i++)
                {
                    try
                    {
                        var prop = recipePara.GetType().GetProperty($"S{i + 2}");
                        object value = prop.GetValue(recipePara);
                        // 处理可空类型的null值情况
                        if (value == null)
                        {
                            continue;
                        }
                        bool positionValue;
                        positionValue = Convert.ToBoolean(value);
                        if (positionValue == true)
                        {
                            ZxRecipePositionParaEntity positionPara = positionParaEntities.Where(x => x.Position == (i + 1)).FirstOrDefault();
                            if (position == 1)
                            {
                                if (positionPara == null)//没工位参数
                                {
                                    positionPara = new ZxRecipePositionParaEntity()
                                    {
                                        RecipeCode = recipeCode,
                                        Position = i + 1,
                                        E5 = newRecipes.MaterialLayers1,
                                        E9 = (int)newRecipes.MaterialWidth1,
                                        E6 = newRecipes.MaterialLayers12,
                                        E7 = (int)newRecipes.MaterialWidth12,
                                    };
                                    zxRecipePositionParaService.InsertRecipePositionParaInfo(positionPara);
                                }
                                else//有工位参数
                                {
                                    positionPara.E5 = newRecipes.MaterialLayers1;
                                    positionPara.E9 = (int)newRecipes.MaterialWidth1;
                                    positionPara.E6 = newRecipes.MaterialLayers12;
                                    positionPara.E7 = (int)newRecipes.MaterialWidth12;
                                    zxRecipePositionParaService.UpdateRecipePositionParaInfo(positionPara);
                                }
                            }
                            else if (position == 2)
                            {
                                if (positionPara == null)//没工位参数
                                {
                                    positionPara = new ZxRecipePositionParaEntity()
                                    {
                                        RecipeCode = recipeCode,
                                        Position = i + 1,
                                        E5 = newRecipes.MaterialLayers2,
                                        E9 = (int)newRecipes.MaterialWidth2,
                                    };
                                    zxRecipePositionParaService.InsertRecipePositionParaInfo(positionPara);
                                }
                                else//有工位参数
                                {
                                    positionPara.E5 = newRecipes.MaterialLayers2;
                                    positionPara.E9 = (int)newRecipes.MaterialWidth2;
                                    zxRecipePositionParaService.UpdateRecipePositionParaInfo(positionPara);
                                }
                            }
                            else
                            {
                                if (positionPara == null)//没工位参数
                                {
                                    positionPara = new ZxRecipePositionParaEntity()
                                    {
                                        RecipeCode = recipeCode,
                                        Position = i + 1,
                                        E5 = newRecipes.MaterialLayers3,
                                        E9 = (int)newRecipes.MaterialWidth3,
                                        E6 = newRecipes.MaterialLayers32,
                                        E7 = (int)newRecipes.MaterialWidth32,
                                    };
                                    zxRecipePositionParaService.InsertRecipePositionParaInfo(positionPara);
                                }
                                else//有工位参数
                                {
                                    positionPara.E5 = newRecipes.MaterialLayers3;
                                    positionPara.E9 = (int)newRecipes.MaterialWidth3;
                                    positionPara.E6 = newRecipes.MaterialLayers32;
                                    positionPara.E7 = (int)newRecipes.MaterialWidth32;
                                    zxRecipePositionParaService.UpdateRecipePositionParaInfo(positionPara);
                                }
                            }
                            position++;
                        }

                    }
                    catch
                    {
                        continue;
                    }
                }
            }
        }

        #endregion
    }
}
