using DevExpress.PivotGrid.OLAP.Mdx;

using HslCommunication.Robot.YASKAWA;

using Mesnac.Action.ChemicalWeighing.LjMaterial;
using Mesnac.Action.ChemicalWeighing.LjPlanning.Db;
using Mesnac.Action.ChemicalWeighing.LjPlanning.Entity;
using Mesnac.Codd.Session;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Windows.Forms;




namespace Mesnac.Action.ChemicalWeighing.LjPlanning
{
    public partial class FrmWeiRecipeDataAdd : Form
    {

       

        public FrmWeiRecipeDataAdd()
        {
            InitializeComponent();

            Init();

            FillDryer();

            FillSilo();

            FillSiloWater();

            FillDataGridDryer1Action();
            //糊化
            FillDataGridSilo1Action();

            FillDataGridWeter1Action();

          

            //and MachineType='Dry' and FormulaType=1 and Machine=1 

         
         

           

            
            //dataGridDryer.DataSource = list;
            //dataGridDryer.Rows.Add();



        }

        int _id = 0;
        public FrmWeiRecipeDataAdd(int id) : this()
        {

            this._id = id;
            var main = LjFormulaDb.GetById(id);
            if (null != main)
            {
                this.txtName.Text = main.FormulaName;
                foreach (MyNameValue drpTypeItem in DrpCpType.Items)
                {
                    if (drpTypeItem.Id == main.RecipeTypeId)
                    {
                        DrpCpType.SelectedItem = drpTypeItem;
                        break;
                    }
                }

                txtCpVersion.Text = main.FormulaVersion;
            }
            var detail = LjFormulaDb.GetDetail(_id);
            UpdateDataGridDryer(detail);
            UpdateDataGridSilo(detail,main.CbSiloC);

            UpdateDryH(detail);
            UpdatSiloH(detail,main.CbSiloH);
            UpdatWeterH(detail, main.CbWeterH);
        }


        /// <summary>
        /// 更新干混机
        /// </summary>
        /// <param name="ljs"></param>
        private void UpdateDataGridDryer(List<LjFormulaDetail> detail)
        {
            dataGridDryer.DataError += DataGrid_DataError;
            dataGridDryer.AutoGenerateColumns = false;
            dataGridDryer.AllowUserToAddRows = true;
            //MachineType='Dry' and FormulaType=1 and Machine='A'
            var data = detail.Where(x => x.MachineType == "Dry" && x.FormulaType == 1 && x.Machine == "A").ToList();
            dataGridDryer.DataSource = new BindingList<LjFormulaDetail>(data);//DataGridView的行可以添加删除(只有允许添加行、删除行)
        }

        private void UpdateDataGridSilo(List<LjFormulaDetail> detail,bool check)
        {
            dataGridSilo1.DataError += DataGrid_DataError;
            dataGridSilo1.AutoGenerateColumns = false;
            dataGridSilo1.AllowUserToAddRows = true;

            dataGridSilo2.DataError += DataGrid_DataError;
            dataGridSilo2.AutoGenerateColumns = false;
            dataGridSilo2.AllowUserToAddRows = true;


            dataGridWater1.DataError += DataGrid_DataError;
            dataGridWater1.AutoGenerateColumns = false;
            dataGridWater1.AllowUserToAddRows = true;

            dataGridWater2.DataError += DataGrid_DataError;
            dataGridWater2.AutoGenerateColumns = false;
            dataGridWater2.AllowUserToAddRows = true;


            var data = detail.Where(x => x.MachineType == "Silo" && x.FormulaType == 1 && x.Machine == "A").ToList();
            dataGridSilo1.DataSource = new BindingList<LjFormulaDetail>(data);//DataGridView的行可以添加删除(只有允许添加行、删除行)


            //Silo_Water
            var data1Water = detail.Where(x => x.MachineType == "Silo_Water" && x.FormulaType == 1 
            && x.Machine == "A").ToList();

            dataGridWater1.DataSource = new BindingList<LjFormulaDetail>(data1Water);//DataGridView的行可以添加删除(只有允许添加行、删除行)


            CbSiloC.Checked = check;
            if (!check)
            {
                var dataB = detail.Where(x => x.MachineType == "Silo" && x.FormulaType == 1 && x.Machine == "B").ToList();
                dataGridSilo2.DataSource = new BindingList<LjFormulaDetail>(dataB);//DataGridView的行可以添加删除(只有允许添加行、删除行)


                var data2Water = detail.Where(x => x.MachineType == "Silo_Water" && x.FormulaType == 1
          && x.Machine == "B").ToList();
                dataGridWater2.DataSource = new BindingList<LjFormulaDetail>(data2Water);//DataGridView的行可以添加删除(只有允许添加行、删除行)

            }

        }

        
        private void UpdateDryH(List<LjFormulaDetail> detail)
        {
            dataGridDryer1Action.DataError += DataGrid_DataError;
            dataGridDryer1Action.AutoGenerateColumns = false;
            dataGridDryer1Action.AllowUserToAddRows = true;

            var data = detail.Where(x => x.MachineType == "Dry" && x.FormulaType == 2 && x.Machine == "A").ToList();
            dataGridDryer1Action.DataSource = new BindingList<LjFormulaDetail>(data);//DataGridView的行可以添加删除(只有允许添加行、删除行)

        }

        private void UpdatSiloH(List<LjFormulaDetail> detail,bool cbSiloH)
        {

            dataGridSiloH1.DataError += DataGrid_DataError;
            dataGridSiloH1.AutoGenerateColumns = false;
            dataGridSiloH1.AllowUserToAddRows = true;

            dataGridSiloH2.DataError += DataGrid_DataError;
            dataGridSiloH2.AutoGenerateColumns = false;
            dataGridSiloH2.AllowUserToAddRows = true;


            var data1SiloH = detail.Where(x => x.MachineType == "Silo" && x.FormulaType == 2
           && x.Machine == "A").ToList();

            dataGridSiloH1.DataSource = new BindingList<LjFormulaDetail>(data1SiloH);//DataGridView的行可以添加删除(只有允许添加行、删除行)
            CbSiloC.Checked = cbSiloH;
            if (!cbSiloH)
            {
                var data2SiloH = detail.Where(x => x.MachineType == "Silo" && x.FormulaType == 2
         && x.Machine == "B").ToList();

                dataGridSiloH2.DataSource = new BindingList<LjFormulaDetail>(data2SiloH);//DataGridView的行可以添加删除(只有允许添加行、删除行)
            }


        }

        private void UpdatWeterH(List<LjFormulaDetail> detail, bool cbWeterH)
        {
            dataGridWeter1.DataError += DataGrid_DataError;
            dataGridWeter1.AutoGenerateColumns = false;
            dataGridWeter1.AllowUserToAddRows = true;

            dataGridWeter2.DataError += DataGrid_DataError;
            dataGridWeter2.AutoGenerateColumns = false;
            dataGridWeter2.AllowUserToAddRows = true;

            var data1WeterH = detail.Where(x => x.MachineType == "Weter" && x.FormulaType == 2
      && x.Machine == "A").ToList();

            dataGridWeter1.DataSource = new BindingList<LjFormulaDetail>(data1WeterH);//DataGridView的行可以添加删除(只有允许添加行、删除行)

            CbWeterH.Checked = cbWeterH;
            if (!cbWeterH)
            {
                var data2WeterH = detail.Where(x => x.MachineType == "Weter" && x.FormulaType == 2
   && x.Machine == "B").ToList();

                dataGridWeter2.DataSource = new BindingList<LjFormulaDetail>(data2WeterH);//DataGridView的行可以添加删除(只有允许添加行、删除行)
            }
        }



        private void DataGrid_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = true;
        }

        private void FillDataGridDryer1Action()
        {
           

               DataGridViewComboBoxColumn combox = this.dataGridDryer1Action.Columns["ComBoxDryer1Code"] as DataGridViewComboBoxColumn;
            var list = GetAction(1);

            
            combox.DataSource = list;
            combox.DisplayMember = "Name";
            combox.ValueMember = "Id";

            combox.DataPropertyName = "ActionId";


        }

        private void FillDataGridSilo1Action()
        {


            DataGridViewComboBoxColumn combox1 = this.dataGridSiloH1.Columns["ComBoxSilo1Code"] as DataGridViewComboBoxColumn;
            var list1 = GetAction(2);
            combox1.DataSource = list1;
            combox1.DisplayMember = "Name";
            combox1.ValueMember = "Id";
            combox1.DataPropertyName = "ActionId";

            DataGridViewComboBoxColumn combox2 = this.dataGridSiloH2.Columns["ComBoxSilo2Code"] as DataGridViewComboBoxColumn;
            var list2 = GetAction(2);
            combox2.DataSource = list2;
            combox2.DisplayMember = "Name";
            combox2.ValueMember = "Id";
            combox2.DataPropertyName = "ActionId";

        }


        private void FillDataGridWeter1Action()
        {


            DataGridViewComboBoxColumn combox1 = this.dataGridWeter1.Columns["ComBoxWeter1Code"] as DataGridViewComboBoxColumn;
            var list1 = GetAction(3);
            combox1.DataSource = list1;
            combox1.DisplayMember = "Name";
            combox1.ValueMember = "Id";
            combox1.DataPropertyName = "ActionId";

            DataGridViewComboBoxColumn combox2 = this.dataGridWeter2.Columns["ComBoxWeter2Code"] as DataGridViewComboBoxColumn;
            var list2 = GetAction(3);
            combox2.DataSource = list2;
            combox2.DisplayMember = "Name";
            combox2.ValueMember = "Id";
            combox2.DataPropertyName = "ActionId";
        }


        /// <summary>
        ///  绑定配方类别
        /// </summary>

        private void Init() 
        {
            DrpCpType.ValueMember = "Id";
            DrpCpType.DisplayMember = "Name";
            var ls = new List<MyNameValue>();
            string sql = "select recipetype_Id as Id,recipetype_Name as Name from Base_RecipeType";

            var dataTable = DBHelp.GetTable(sql);
            var dr = dataTable.Rows;
            ls = new List<MyNameValue>();
            foreach (DataRow o in dr)
            {
                ls.Add(new MyNameValue()
                {
                    Id = (int)o["Id"],
                    Name = o["Name"].ToString()
                });
            }
            DrpCpType.DataSource = ls;
           
        }

        private List<MyNameValue> GetStockMaterrial(int mtypId)
        {
            string sql = "select  Id, Code, StockName, MTypeId, MTypeName, MId, MName, Remark from  lj_stock_material";

            var dataTable = DBHelp.GetTable(sql);
            List<MyNameValue> ls = new List<MyNameValue>();

            foreach (DataRow o in dataTable.Rows)
            {
                int tableMTypeId = Convert.ToInt32(o["MTypeId"]);
                if (mtypId != 0)
                {
                    if (tableMTypeId == mtypId)
                    {
                        ls.Add(new MyNameValue()
                        {
                            Id = (int)o["Id"],
                            Name = o["StockName"].ToString() + $"({o["MName"]})"
                        });
                    }
                }
            }
            return ls;
        }


        private List<MyNameValue> GetAction(int deviceUnitId)
        {
            string sql = "select ActionCode.id, code, ActionName, ActionCode.Remark, DeviceUnitId, DeviceUnit.Name \r\n         " +
                "   from ActionCode\r\n       " +
                "     left join  DeviceUnit  on ActionCode.DeviceUnitId = DeviceUnit.Id   where IsEnable=1";

           if(deviceUnitId > 0)
            {
                sql += " and  DeviceUnitId=" + deviceUnitId ;

              

            }

            sql += " order by code";
            var dataTable = DBHelp.GetTable(sql);
            List<MyNameValue> ls = new List<MyNameValue>();
            foreach (DataRow o in dataTable.Rows)
            {

                ls.Add(new MyNameValue()
                {
                    Id = (int)o["id"],
                    Name = o["ActionName"].ToString()
                }) ;
            }
            return ls;

        }

        private DataRow GetCodeActionById(int id)
        {
            string sql = "select code as Code, ActionName as Name from ActionCode where Id=" + id;
            var dataTable = DBHelp.GetTable(sql);
            return dataTable.Rows[0];

        }

        /// <summary>
        ///  干混机称量配方 物料下拉选择
        /// </summary>

        private void FillDryer()
        {

           
            DataGridViewComboBoxColumn combox = dataGridDryer.Columns["ComBoxDryer1Bin"] as DataGridViewComboBoxColumn;
            var list = GetStockMaterrial(1);


            list.RemoveAll(x => x.Id == 5);
            list.RemoveAll(x => x.Id == 6);


           
            combox.DataSource = list;
            combox.DisplayMember = "Name";
            combox.ValueMember = "Id";
            combox.DataPropertyName = "StockMaterialId";

        }
        /// <summary>
        ///  糊化机1 2 物料选择进行初始化
        /// </summary>

        private void FillSilo()
        {
            DataGridViewComboBoxColumn combox1 = dataGridSilo1.Columns["ComBoxSilo1Bin"] as DataGridViewComboBoxColumn;
            var list1 = GetStockMaterrial(1);

            list1 = list1.Where(x => x.Id == 5 || x.Id == 6).ToList();

            combox1.DataSource = list1;
            combox1.DisplayMember = "Name";
            combox1.ValueMember = "Id";
            combox1.DataPropertyName = "StockMaterialId";

            DataGridViewComboBoxColumn combox2 = dataGridSilo2.Columns["ComBoxSilo2Bin"] as DataGridViewComboBoxColumn;
            var list2 = GetStockMaterrial(1);

            list2 = list2.Where(x => x.Id == 5 || x.Id == 6).ToList();

            combox2.DataSource = list2;
            combox2.DisplayMember = "Name";
            combox2.ValueMember = "Id";
            combox2.DataPropertyName = "StockMaterialId";



        }

        /// <summary>
        ///  糊化机1 2 物料选择进行初始化 水秤
        /// </summary>
        private void FillSiloWater()
        {
            DataGridViewComboBoxColumn comboxWater1 = dataGridWater1.Columns["ComBoxSilo1BinWater"] as DataGridViewComboBoxColumn;
            var comboxWater1List = GetStockMaterrial(4);
            comboxWater1.DataSource = comboxWater1List;
            comboxWater1.DisplayMember = "Name";
            comboxWater1.ValueMember = "Id";
            comboxWater1.DataPropertyName = "StockMaterialId";


            DataGridViewComboBoxColumn comboxWater2 = dataGridWater2.Columns["ComBoxSilo2BinWater"] as DataGridViewComboBoxColumn;
            var comboxWater2List = GetStockMaterrial(4);
            comboxWater2.DataSource = comboxWater2List;
            comboxWater2.DisplayMember = "Name";
            comboxWater2.ValueMember = "Id";
            comboxWater2.DataPropertyName = "StockMaterialId";

        }

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {

           
        }

        private void dataGridView1_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            e.Row.Cells["TxtDryer1Weight"].Value = "0";
            e.Row.Cells["TxtDryer1Tolerance"].Value = "0";
        }

        private void button1_Click(object sender, System.EventArgs e)
        {

            string txtNameStr=txtName.Text.Trim();
            if (txtNameStr.Length == 0)
            {

                MessageBox.Show("请输入配方名称");
                return;
            }
            var txtCpVersionStr=txtCpVersion.Text.Trim();
            if (txtCpVersionStr.Length==0)
            {
                MessageBox.Show("请输入配方版本");
                return;
            }



            //干混机
            List<ClEntity> clDry = GetClEnity(dataGridDryer);

            

            //湿混机1
            List<ClEntity> clSoil1 = GetClEnity(dataGridSilo1);
            List<ClEntity> clSoil1Water = GetClEnity(dataGridWater1);

            //湿混机2
            List<ClEntity> clSoil2 = new List<ClEntity>();

            List<ClEntity> clSoil2Water = new List<ClEntity>();
            //如果Copy 2 copy 1
            if (CbSiloC.Checked)
            {
                clSoil2.AddRange(clSoil1);
                clSoil2Water.AddRange(clSoil1Water);
            }
            else
            {
                clSoil2= GetClEnity(dataGridSilo2);
                clSoil2Water=GetClEnity(dataGridWater2);
            }

            //干混机1 获取混合配方
            List<ChEntity> dataGridDryer1List = GetChEnity(dataGridDryer1Action);


            //湿混机1 dataGridSiloH1

            List<ChEntity> dataGridSiloH1List = GetChEnity(dataGridSiloH1);
            List<ChEntity> dataGridSiloH2List = new List<ChEntity>();

            if (CbSiloC.Checked)
            {
                dataGridSiloH2List.AddRange(dataGridSiloH1List);
            }
            else
            {
                dataGridSiloH2List = GetChEnity(dataGridSiloH2);
            }


            List<ChEntity> dataGridWeter1List= GetChEnity(dataGridWeter1);

            List<ChEntity> dataGridWeter2List = new List<ChEntity>();
            if (CbWeterH.Checked)
            {
                dataGridWeter2List.AddRange (dataGridWeter1List);
            }
            else
            {
                dataGridWeter2List=GetChEnity(dataGridWeter2);
            }


            Save(clDry, clSoil1, clSoil1Water, clSoil2, clSoil2Water,
                dataGridDryer1List, dataGridSiloH1List,
                dataGridSiloH2List, dataGridWeter1List, dataGridWeter2List);


            this.DialogResult = DialogResult.OK;

            //if (CbSilo1.Checked)
            //{
            //    clSoil= GetClEnity(dataGridSilo);
            //}

            //List<ClEntity> clSoi2 = new List<ClEntity>();
            //if (CbSilo2.Checked)
            //{
            //    clSoil = GetClEnity(dataGridSilo);
            //}


            //List<ClEntity> clSoiHWater = new List<ClEntity>();
            //if (CbSilo2.Checked)
            //{
            //    clSoiHWater = GetClEnity(dataGridWater);
            //}



            //先看统一配方干
            // Save(clDry,clSoil, clSoi2);
        }


        
        private List<ChEntity> GetChEnity(DataGridView dataGridView)
        {
            List<ChEntity> clDry = new List<ChEntity>();
            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                try
                {
                    ChEntity entity = new ChEntity();
                    object obj = row.Cells[0].Value;
                    var sss = row.Cells[0].FormattedValue;
                    if (obj != null)
                    {
                        entity.ActionId = Convert.ToInt32(obj);
                       
                    }
                    else
                    {
                        continue;
                    }

                    obj = row.Cells[1].Value;
                    if (obj != null)
                    {
                        entity.TimeInfo = Convert.ToInt16(obj);
                    }

                    obj = row.Cells[2].Value;
                    if (obj != null)
                    {
                        entity.Temp = Convert.ToSingle(obj);
                    }

                    obj = row.Cells[3].Value;
                    if (obj != null)
                    {
                        entity.Speed = Convert.ToSingle(obj);
                    }

                    if(row.Cells.Count>4)
                    {
                        obj = row.Cells[4].Value;
                        if(obj != null)
                        {
                            entity.SetValue = Convert.ToSingle(obj);
                        }
                    }

                    if (row.Cells.Count >5)
                    {
                        obj = row.Cells[5].Value;
                        if (obj != null)
                        {
                            entity.SetTolerance = Convert.ToSingle(obj);
                        }
                    }

                    clDry.Add(entity);
                }
                catch (Exception)
                {

                    MessageBox.Show("请检查混合配方数据");
                    break;
                }



            }
            return clDry;
        }


        /// <summary>
        /// 从gdataGridView获取 实体便于插入数据
        /// </summary>
        /// <param name="dataGridView"></param>
        /// <returns></returns>
        private List<ClEntity> GetClEnity(DataGridView dataGridView)
        {
            List<ClEntity> clDry = new List<ClEntity>();
            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                try
                {
                    ClEntity entity = new ClEntity();
                    object obj = row.Cells[0].Value;
                    var sss = row.Cells[0].FormattedValue;
                    if (obj != null)
                    {
                        entity.StockMaterialId = Convert.ToInt32(obj);
                    }
                    else
                    {
                        continue;
                    }

                    obj = row.Cells[1].Value;
                    if (obj != null)
                    {
                        entity.Weight = Convert.ToSingle(obj);
                    }

                    obj = row.Cells[2].Value;
                    if (obj != null)
                    {
                        entity.Tolerance = Convert.ToSingle(obj);
                    }
                    clDry.Add(entity);
                }
                catch (Exception)
                {

                    MessageBox.Show("请检查称量配方");
                    break;
                }



            }
            return clDry;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="cls">保存干混机称量配方</param>
        /// <param name="soil1">湿混机1</param>
        /// <param name="soilWater1">湿混机1 水</param>
        /// <param name="soil2">湿混机2</param>
        /// <param name="soilWater2">湿混机2 水</param>
        /// <param name="dataGridDryer1List">干混机1 混合配方</param>
        /// <param name="dataGridSiloH1List">糊化机1 混合配方</param>

        private void Save(List<ClEntity>  cls, List<ClEntity> soil1, 
            List<ClEntity> soilWater1, List<ClEntity> soil2, List<ClEntity> soilWater2,
            List<ChEntity> dataGridDryer1List,

             List<ChEntity> dataGridSiloH1List,

             List<ChEntity> dataGridSiloH2List,

             List<ChEntity> dataGridWeter1List,
             List<ChEntity> dataGridWeter2List
            )
        {
            DbHelper dbHelper = Mesnac.Basic.DataSourceFactory.Instance.GetDbHelper(Mesnac.Basic.DataSourceFactory.MCDbType.Local);

            string formulaNameNoStr = "0";
            string formulaName=this.txtName.Text;
            int recipeTypeId = Convert.ToInt32(DrpCpType.SelectedValue);
            string recipeTypeName = DrpCpType.Text;
            string formulaVersion = txtCpVersion.Text;
            try
            {

                int cbSiloC = 0;
                int cbSiloH = 0;
                int   cbWeterH = 0;
                if(CbSiloC.Checked)
                {
                    cbSiloC = 1;
                }
                if(CbSiloC.Checked)
                {
                    cbSiloH = 1;
                }
                if (CbWeterH.Checked)
                {
                    cbWeterH = 1;  
                }


                dbHelper.BeginTransaction();

                dbHelper.ClearParameter();
                dbHelper.CommandType = CommandType.Text;

                //主表1 1个单元
                int id = 0;
                if (_id > 0)
                {
                    id = _id;
                }
                else
                {
                    id= Convert.ToInt32(DBHelp.GetOne("select  isnull(max(Id),0) as no  from Lj_Formula")) + 1;
                }
                string sql = "insert into Lj_Formula " +
                    "(Id, FormulaNo, FormulaName, RecipeTypeId, RecipeTypeName, IsEnable, FormulaVersion, CreateTime,Unit,CbSiloC,CbSiloH,CbWeterH\r\n )\r\n" +
                    
                 $"values ({id},{formulaNameNoStr},'{formulaName}',{recipeTypeId},'{recipeTypeName}',1,'{formulaVersion}',GETDATE(),1,{cbSiloC},{cbSiloH},{cbWeterH});";



                if (_id > 0)
                {
                    sql = "update Lj_Formula";
                    sql += $" set FormulaName='{formulaName}' ";
                    sql += $"  , RecipeTypeId='{recipeTypeId}' ";
                    sql += $"  , recipeTypeName='{recipeTypeName}' ";
                    sql += $"  , FormulaVersion='{formulaVersion}' ";
                    sql += $"  , UpdateTime=GETDATE() ";
                    sql += $"  , CbSiloC={cbSiloC} ";
                    sql += $"  , CbSiloH={cbSiloH} ";
                    sql += $"  , CbWeterH={cbWeterH}  where Id= {_id}";
                       
                }

                dbHelper.CommandText = sql;
                dbHelper.ExecuteNonQuery();


                if (_id > 0)
                {
                    dbHelper.CommandText = $"delete  from Lj_Formula_Detail where FormulaId={_id}";
                    dbHelper.ExecuteNonQuery();
                }


                    //干混机1
                    foreach (ClEntity clEntity in cls)
                {

                    var dr=GetByMaterialId(clEntity.StockMaterialId);
                    int code = Convert.ToInt32(dr["Code"]);
                    int mId = Convert.ToInt32(dr["MId"]);
                    string Mname = dr["MName"].ToString();
                    //FormulaType 1 称量 2 混合

                    string sqlA = $"insert into Lj_Formula_Detail " +
                        $"(FormulaId, BinNo, MId, MName, Weight, Tolerance, Machine, MachineType, FormulaType,\r\n                               ActionCode, ActionName, TimeInfo, Temp, Speed, SetValue, SetTolerance,StockMaterialId)\r\n" +
                 $"values ({id},{code},{mId},'{Mname}',{clEntity.Weight},{clEntity.Tolerance},'A','Dry',1,0,'',0,0,0,0,0,{clEntity.StockMaterialId})";

                    dbHelper.CommandText = sqlA;
                    dbHelper.ExecuteNonQuery();
                }



                //湿混1
                foreach (ClEntity clEntity in soil1)
                {

                    var dr = GetByMaterialId(clEntity.StockMaterialId);
                    int code = Convert.ToInt32(dr["Code"]);
                    int mId = Convert.ToInt32(dr["MId"]);
                    string Mname = dr["MName"].ToString();
                    //FormulaType 1 称量 2 混合
                    // Machine A 左侧 B右侧

                    string sqlA = $"insert into Lj_Formula_Detail " +
                        $"(FormulaId, BinNo, MId, MName, Weight, Tolerance, Machine, MachineType, FormulaType,\r\n                               ActionCode, ActionName, TimeInfo, Temp, Speed, SetValue, SetTolerance,StockMaterialId)\r\n" +
                    $"values ({id},{code},{mId},'{Mname}',{clEntity.Weight},{clEntity.Tolerance},'A','Silo',1,0,'',0,0,0,0,0,{clEntity.StockMaterialId})";

                    dbHelper.CommandText = sqlA;
                    dbHelper.ExecuteNonQuery();
                }


                //湿混1 水
                foreach (ClEntity clEntity in soilWater1)
                {

                    var dr = GetByMaterialId(clEntity.StockMaterialId);
                    int code = Convert.ToInt32(dr["Code"]);
                    int mId = Convert.ToInt32(dr["MId"]);
                    string Mname = dr["MName"].ToString();
                    //FormulaType 1 称量 2 混合

                    string sqlA = $"insert into Lj_Formula_Detail " +
                        $"(FormulaId, BinNo, MId, MName, Weight, Tolerance, Machine, MachineType, FormulaType,\r\n                               ActionCode, ActionName, TimeInfo, Temp, Speed, SetValue, SetTolerance,StockMaterialId)\r\n" +
                    $"values ({id},{code},{mId},'{Mname}',{clEntity.Weight},{clEntity.Tolerance},'A','Silo_Water',1,0,'',0,0,0,0,0,{clEntity.StockMaterialId})";

                    dbHelper.CommandText = sqlA;
                    dbHelper.ExecuteNonQuery();
                }




                //湿混2
                foreach (ClEntity clEntity in soil2)
                {

                    var dr = GetByMaterialId(clEntity.StockMaterialId);
                    int code = Convert.ToInt32(dr["Code"]);
                    int mId = Convert.ToInt32(dr["MId"]);
                    string Mname = dr["MName"].ToString();
                    //FormulaType 1 称量 2 混合

                    string sqlA = $"insert into Lj_Formula_Detail " +
                        $"(FormulaId, BinNo, MId, MName, Weight, Tolerance, Machine, MachineType, FormulaType,\r\n                               ActionCode, ActionName, TimeInfo, Temp, Speed, SetValue, SetTolerance,StockMaterialId)\r\n" +
                    $"values ({id},{code},{mId},'{Mname}',{clEntity.Weight},{clEntity.Tolerance},'B','Silo',1,0,'',0,0,0,0,0,{clEntity.StockMaterialId})";

                    dbHelper.CommandText = sqlA;
                    dbHelper.ExecuteNonQuery();
                }

           
                 //湿混2 水
                foreach (ClEntity clEntity in soilWater2)
                {

                    var dr = GetByMaterialId(clEntity.StockMaterialId);
                    int code = Convert.ToInt32(dr["Code"]);
                    int mId = Convert.ToInt32(dr["MId"]);
                    string Mname = dr["MName"].ToString();
                    //FormulaType 1 称量 2 混合

                    string sqlA = $"insert into Lj_Formula_Detail " +
                        $"(FormulaId, BinNo, MId, MName, Weight, Tolerance, Machine, MachineType, FormulaType,\r\n                               ActionCode, ActionName, TimeInfo, Temp, Speed, SetValue, SetTolerance,StockMaterialId)\r\n" +
                    $"values ({id},{code},{mId},'{Mname}',{clEntity.Weight},{clEntity.Tolerance},'B','Silo_Water',1,0,'',0,0,0,0,0,{clEntity.StockMaterialId})";

                    dbHelper.CommandText = sqlA;
                    dbHelper.ExecuteNonQuery();
                }


                //-------------------混合配方--------------------------------------------------

                foreach(ChEntity chEntity in dataGridDryer1List)
                {
                    var dr = GetCodeActionById(chEntity.ActionId);
                    int code = Convert.ToInt32(dr["Code"]);
                    string actionName = dr["Name"].ToString();
                  
                    //FormulaType 1 称量 2 混合

                    string sqlA = $"insert into Lj_Formula_Detail " +
                        $"(FormulaId, BinNo, MId, MName, Weight, Tolerance, Machine, MachineType, FormulaType,\r\n                               ActionCode, ActionName, TimeInfo, Temp, Speed, SetValue, SetTolerance,ActionId)\r\n" +
                    $"values ({id},{code},{0},'',{0},{0},'A','Dry',2,{code},'{actionName}',{chEntity.TimeInfo},{chEntity.Temp},{chEntity.Speed},{chEntity.SetValue},{chEntity.SetTolerance},{chEntity.ActionId})";

                    dbHelper.CommandText = sqlA;
                    dbHelper.ExecuteNonQuery();
                }


                foreach (ChEntity chEntity in dataGridSiloH1List)
                {
                    var dr = GetCodeActionById(chEntity.ActionId);
                    int code = Convert.ToInt32(dr["Code"]);
                    string actionName = dr["Name"].ToString();

                    //FormulaType 1 称量 2 混合

                    string sqlA = $"insert into Lj_Formula_Detail " +
                        $"(FormulaId, BinNo, MId, MName, Weight, Tolerance, Machine, MachineType, FormulaType,\r\n                               ActionCode, ActionName, TimeInfo, Temp, Speed, SetValue, SetTolerance,ActionId)\r\n" +
                    $"values ({id},{code},{0},'',{0},{0},'A','Silo',2," +
                    $"{code},'{actionName}',{chEntity.TimeInfo},{chEntity.Temp},{chEntity.Speed},{chEntity.SetValue},{chEntity.SetTolerance},{chEntity.ActionId})";

                    dbHelper.CommandText = sqlA;
                    dbHelper.ExecuteNonQuery();
                }

                foreach (ChEntity chEntity in dataGridSiloH2List)
                {
                    var dr = GetCodeActionById(chEntity.ActionId);
                    int code = Convert.ToInt32(dr["Code"]);
                    string actionName = dr["Name"].ToString();

                    //FormulaType 1 称量 2 混合

                    string sqlA = $"insert into Lj_Formula_Detail " +
                        $"(FormulaId, BinNo, MId, MName, Weight, Tolerance, Machine, MachineType, FormulaType,\r\n                               ActionCode, ActionName, TimeInfo, Temp, Speed, SetValue, SetTolerance,ActionId)\r\n" +
                    $"values ({id},{code},{0},'',{0},{0},'B','Silo',2," +
                    $"{code},'{actionName}',{chEntity.TimeInfo},{chEntity.Temp},{chEntity.Speed},{chEntity.SetValue},{chEntity.SetTolerance},{chEntity.ActionId})";

                    dbHelper.CommandText = sqlA;
                    dbHelper.ExecuteNonQuery();
                }

                //湿1 混合配方



                foreach (ChEntity chEntity in dataGridWeter1List)
                {
                    var dr = GetCodeActionById(chEntity.ActionId);
                    int code = Convert.ToInt32(dr["Code"]);
                    string actionName = dr["Name"].ToString();

                    //FormulaType 1 称量 2 混合

                    string sqlA = $"insert into Lj_Formula_Detail " +
                        $"(FormulaId, BinNo, MId, MName, Weight, Tolerance, Machine, MachineType, FormulaType,\r\n                               ActionCode, ActionName, TimeInfo, Temp, Speed, SetValue, SetTolerance,ActionId)\r\n" +
                    $"values ({id},{code},{0},'',{0},{0},'A','Weter',2," +
                    $"{code},'{actionName}',{chEntity.TimeInfo},{chEntity.Temp},{chEntity.Speed},{chEntity.SetValue},{chEntity.SetTolerance},{chEntity.ActionId})";

                    dbHelper.CommandText = sqlA;
                    dbHelper.ExecuteNonQuery();
                }

                foreach (ChEntity chEntity in dataGridWeter2List)
                {
                    var dr = GetCodeActionById(chEntity.ActionId);
                    int code = Convert.ToInt32(dr["Code"]);
                    string actionName = dr["Name"].ToString();

                    //FormulaType 1 称量 2 混合

                    string sqlA = $"insert into Lj_Formula_Detail " +
                        $"(FormulaId, BinNo, MId, MName, Weight, Tolerance, Machine, MachineType, FormulaType,\r\n                               ActionCode, ActionName, TimeInfo, Temp, Speed, SetValue, SetTolerance,ActionId)\r\n" +
                    $"values ({id},{code},{0},'',{0},{0},'B','Weter',2," +
                    $"{code},'{actionName}',{chEntity.TimeInfo},{chEntity.Temp},{chEntity.Speed},{chEntity.SetValue},{chEntity.SetTolerance},{chEntity.ActionId})";

                    dbHelper.CommandText = sqlA;
                    dbHelper.ExecuteNonQuery();
                }


                dbHelper.CommitTransaction();
            }
            catch(Exception ex) {
                dbHelper.RollbackTransaction();
            }

        }

        private void CbSilo1_CheckedChanged(object sender, EventArgs e)
        {
           

       
        }

       
        private void CbSilo2_CheckedChanged(object sender, EventArgs e)
        {
            CbSilo1_CheckedChanged(sender, e);
        }

        private void dataGridSilo_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            e.Row.Cells["TxtSilo1Weight"].Value = "0";
            e.Row.Cells["TxtSilo1Tolerance"].Value = "0";
        }

        private void dataGridWater_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
           
            e.Row.Cells["TxtSilo1WeightWater"].Value = "0";
            e.Row.Cells["TxtSilo1ToleranceWater"].Value = "0";
        }

        private void dataGridDryer1Action_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            e.Row.Cells["ComBoxDryer1TimeInfo"].Value = "0";
            e.Row.Cells["ComBoxDryer1Temp"].Value = "0";
            e.Row.Cells["ComBoxDryer1Speed"].Value = "0";
        }

        private void dataGridWeter1_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
        
            e.Row.Cells["ComBoxWeter1TimeInfo"].Value = "0";
            e.Row.Cells["ComBoxWeter1Temp"].Value = "0";
            e.Row.Cells["ComBoxWeter1Speed"].Value = "0";
            e.Row.Cells["ComBoxWeter1SetValue"].Value = "0";
            e.Row.Cells["ComBoxWeter1SetTolerance"].Value = "0";
        }

        private void dataGridSilo1_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            e.Row.Cells["ComBoxSilo1TimeInfo"].Value = "0";
            e.Row.Cells["ComBoxSilo1Temp"].Value = "0";
            e.Row.Cells["ComBoxSilo1Speed"].Value = "0";
        }


        private DataRow GetByMaterialId(int id)
        {
            string sql = "select  Id, Code, StockName, MTypeId, MTypeName, MId, MName, Remark from  lj_stock_material  where Id=" + id;

             var dataTable=DBHelp.GetTable(sql);
            return dataTable.Rows[0];
        }

        private void BtnCanel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dataGridSilo2_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            //e.Row.Cells["ComBoxSilo2Bin"].Value = "0";
            e.Row.Cells["TxtSilo2Weight"].Value = "0";
            e.Row.Cells["TxtSilo2Tolerance"].Value = "0";
        }

        private void dataGridWater2_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            e.Row.Cells["TxtSilo2WeightWater"].Value = "0";
            e.Row.Cells["TxtSilo2ToleranceWater"].Value = "0";
        }

        private void dataGridWater1_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            e.Row.Cells["TxtSilo1WeightWater"].Value = "0";
            e.Row.Cells["TxtSilo1ToleranceWater"].Value = "0";
        }

        private void dataGridSiloH1_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            e.Row.Cells["ComBoxSilo1TimeInfo"].Value = "0";
            e.Row.Cells["ComBoxSilo1Temp"].Value = "0";
            e.Row.Cells["ComBoxSilo1Speed"].Value = "0";
        }

        private void dataGridSiloH2_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            e.Row.Cells["ComBoxSilo2TimeInfo"].Value = "0";
            e.Row.Cells["ComBoxSilo2Temp"].Value = "0";
            e.Row.Cells["ComBoxSilo2Speed"].Value = "0";
        }

        private void dataGridWeter1_DefaultValuesNeeded_1(object sender, DataGridViewRowEventArgs e)
        {
            e.Row.Cells["ComBoxWeter1TimeInfo"].Value = "0";
            e.Row.Cells["ComBoxWeter1Temp"].Value = "0";
            e.Row.Cells["ComBoxWeter1Speed"].Value = "0";
            e.Row.Cells["ComBoxWeter1SetValue"].Value = "0";
            e.Row.Cells["ComBoxWeter1SetTolerance"].Value = "0";
        }

        private void dataGridWeter2_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            e.Row.Cells["ComBoxWeter2TimeInfo"].Value = "0";
            e.Row.Cells["ComBoxWeter2Temp"].Value = "0";
            e.Row.Cells["ComBoxWeter2Speed"].Value = "0";
            e.Row.Cells["ComBoxWeter2SetValue"].Value = "0";
            e.Row.Cells["ComBoxWeter2SetTolerance"].Value = "0";
        }

        private void dataGridDryer_CellContentClick(object sender, DataGridViewCellEventArgs e)
        { 

        }

        private void CbSiloC_CheckedChanged(object sender, EventArgs e)
        {
            if(CbSiloC.Checked == true)
            {
              this.tabPage4.Parent = null;
              this.tabPage4.Enabled = false; // no casting required.
            }
            else
            {
                tabControl2.TabPages.Add(this.tabPage4);
                this.tabPage4.Enabled = true;
            }

            if (CbSiloC.Checked == true)
            {
                this.tabPage2.Parent = null;
                this.tabPage2.Enabled = false; // no casting required.
            }
            else
            {
                tabControl1.TabPages.Add(this.tabPage2);
                this.tabPage2.Enabled = true;
            }
        }

        private void CbSiloH_CheckedChanged(object sender, EventArgs e)
        {
            
        }

        private void CbWeterH_CheckedChanged(object sender, EventArgs e)
        {
            if (CbWeterH.Checked == true)
            {
                this.tabPage6.Parent = null;
                this.tabPage6.Enabled = false; // no casting required.
            }
            else
            {
                tabControl3.TabPages.Add(this.tabPage6);
                this.tabPage6.Enabled = true;
            }
        }

        private void tabPage3_Click(object sender, EventArgs e)
        {

        }
    }
    
}