using HighWayIot.Log4net;
using HighWayIot.Plc;
using HighWayIot.Plc.PlcHelper;
using HighWayIot.Repository.domain;
using HighWayIot.Repository.service;
using HighWayIot.Rfid;
using HighWayIot.TouchSocket;
using HighWayIot.Winform.Business;
using HighWayIot.Winform.Properties;
using HslCommunication;
using Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;

using static System.Windows.Forms.VisualStyles.VisualStyleElement;


namespace HighWayIot.Winform.UserControlPages
{
    public partial class TestPage : UserControl
    {
        private static LogHelper logger = LogHelper.Instance;

        /// <summary>
        /// TCP客户端
        /// </summary>
        private TouchSocketTcpClient _touchSocketTcpClient = TouchSocketTcpClient.Instance;

        /// <summary>
        /// RFID数据分析
        /// </summary>
        private RfidDataAnalyse _RfidDataAnalyse = new RfidDataAnalyse();

        XmlUtil xmlUtil = new XmlUtil();

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

        private void Init()
        {
            ArrayList list = new ArrayList();
            foreach (var kv in GeneralUtils.GetEnumKeyValuePairs<DataTypeEnum>().ToDictionary(i => i.Key, i => i.Value))
            {
                list.Add(kv);
            }
            //PlcType.DataSource = 
            //PlcType.DataSource = ;
        }

        /// <summary>
        /// RFID测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            var a = _touchSocketTcpClient.Send($"192.168.0.{RFIDtext.Text}", _RfidDataAnalyse.Send02H(1000));
            LogHelper.Instance.Info($"192.168.0.{RFIDtext.Text} 发送" + (a ? "成功" : "失败"));
        }

        /// <summary>
        /// 测试按钮3
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            byte[] sideBytes = new byte[2];
            sideBytes[0] = sideBytes[0].SetBoolByIndex(0, false);
            sideBytes[0] = sideBytes[0].SetBoolByIndex(1, true);
            sideBytes[0] = sideBytes[0].SetBoolByIndex(2, false);
            sideBytes[0] = sideBytes[0].SetBoolByIndex(3, true);
            sideBytes[0] = sideBytes[0].SetBoolByIndex(4, false);
            sideBytes[0] = sideBytes[0].SetBoolByIndex(5, true);
            sideBytes[0] = sideBytes[0].SetBoolByIndex(6, false);
            sideBytes[0] = sideBytes[0].SetBoolByIndex(7, true);
            sideBytes[1] = sideBytes[1].SetBoolByIndex(0, false);
            sideBytes[1] = sideBytes[1].SetBoolByIndex(1, true);
            ushort sideBitData = sideBytes.FromBytes();
            sideBytes = BitConverter.GetBytes(sideBitData);
            if (PlcConnect.PlcWriteBytes2("D409", sideBytes).IsSuccess)
            {
                MessageBox.Show("写入成功");
            }
        }

        /// <summary>
        /// 测试按钮1
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            OperateResult<byte[]> sideResult = PlcConnect.ReadByte2("D409", 1);
            byte[] sideData;
            if (sideResult.IsSuccess)
            {
                sideData = sideResult.Content;
                List<bool> result = new List<bool>();
                result.Add(sideData[0].GetBoolByIndex(0));
                result.Add(sideData[0].GetBoolByIndex(1));
                result.Add(sideData[0].GetBoolByIndex(2));
                result.Add(sideData[0].GetBoolByIndex(3));
                result.Add(sideData[0].GetBoolByIndex(4));
                result.Add(sideData[0].GetBoolByIndex(5));
                result.Add(sideData[0].GetBoolByIndex(6));
                result.Add(sideData[0].GetBoolByIndex(7));
                result.Add(sideData[1].GetBoolByIndex(0));
                result.Add(sideData[1].GetBoolByIndex(1));
            }
        }

        /// <summary>
        /// 配方同步方法
        /// </summary>
        public void SyncRecipe(ZxMesPlanTransferEntity newRecipe)
        {
            if(newRecipe == null)
            {
                return;
            }
            //同步到配方（配方和称量，如果是新的加字段）
            List<ZxRecipeEntity> RecipeLists = ZxRecipeService.Instance.GetRecipeInfos();
            var nowEneity = RecipeLists.Where(x => x.RecipeCode == newRecipe.RecipeCode && x.IsDeleted == false).FirstOrDefault();
            if (nowEneity != null)   //有就更新 只更新配方和称量信息
            {
                //同步配方
                nowEneity.RecipeSpecCode = newRecipe.SpecCode;
                nowEneity.RecipeSpecName = newRecipe.SpecName;
                nowEneity.SizeKind = newRecipe.RimInch;
                nowEneity.FixedWidth = newRecipe.FixRubWidth;
                if (!ZxRecipeService.Instance.UpdateRecipeInfo(nowEneity))
                {
                    return;
                }

                //同步称量信息
                List<ZxWeightEntity> zxWeightEntities = ZxWeightService.Instance.GetWeightInfos(nowEneity.RecipeCode);
                for (int i = 1; i <= 3; i++)
                {
                    string typeName = string.Empty;
                    switch (i)
                    {
                        case 1:
                            typeName = "基部胶";
                            break;
                        case 2:
                            typeName = "中层胶";
                            break;
                        case 3:
                            typeName = "胎面胶";
                            break;
                        default:
                            break;
                    }
                    string MaterialName = Convert.ToString(newRecipe.GetType().GetProperty($"MaterialName{i}").GetValue(newRecipe));
                    if (!string.IsNullOrEmpty(MaterialName))
                    {
                        ZxWeightEntity weight = zxWeightEntities.FirstOrDefault(x => x.MaterialCode == MaterialName);
                        if (weight != null) //原来就有
                        {
                            weight.SetThickness = Convert.ToDecimal(newRecipe.GetType().GetProperty($"MaterialThickness{i}").GetValue(newRecipe)); //(decimal)newRecipe.MaterialThickness1;
                            weight.SetWidth = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialWidth{i}").GetValue(newRecipe)); //newRecipe.MaterialWidth1;
                            weight.SetWidth2 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialWidth{i}2").GetValue(newRecipe)); //newRecipe.MaterialWidth12;
                            weight.SetWidth3 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialWidth{i}3").GetValue(newRecipe)); //newRecipe.MaterialWidth13;
                            weight.SetLayer = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialLayers{i}").GetValue(newRecipe)); //newRecipe.MaterialLayers1;
                            weight.SetLayer2 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialLayers{i}2").GetValue(newRecipe)); //newRecipe.MaterialLayers12;
                            weight.SetLayer3 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialLayers{i}3").GetValue(newRecipe)); //newRecipe.MaterialLayers13;
                            ZxWeightService.Instance.UpdateWeightInfo(weight);
                        }
                        else //原来没有就添加
                        {
                            ZxWeightService.Instance.InsertWeightInfo(new ZxWeightEntity()
                            {
                                RecipeCode = newRecipe.RecipeCode,
                                MaterialCode = MaterialName,
                                MaterialName = MaterialName + typeName,
                                MaterialType = typeName,
                                SetThickness = Convert.ToDecimal(newRecipe.GetType().GetProperty($"MaterialThickness{i}").GetValue(newRecipe)),
                                SetWidth = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialWidth{i}").GetValue(newRecipe)),
                                SetWidth2 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialWidth{i}2").GetValue(newRecipe)),
                                SetWidth3 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialWidth{i}3").GetValue(newRecipe)),
                                SetLayer = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialLayers{i}").GetValue(newRecipe)),
                                SetLayer2 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialLayers{i}2").GetValue(newRecipe)),
                                SetLayer3 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialLayers{i}3").GetValue(newRecipe)),
                                SetError = 1,
                                IsUse = true,
                                IsDeleted = false,
                            });
                        }
                    }
                }
            }
            else  //没有就插入 全部同步
            {
                //同步配方
                ZxRecipeEntity entity = new ZxRecipeEntity()
                {
                    RecipeName = newRecipe.RecipeName,
                    RecipeCode = newRecipe.RecipeCode,
                    RecipeSpecCode = newRecipe.SpecCode,
                    RecipeSpecName = newRecipe.SpecName,
                    SizeKind = newRecipe.RimInch,
                    FixedWidth = newRecipe.FixRubWidth,
                    IsUse = true,
                    IsDeleted = false,
                };
                ZxRecipeService.Instance.InsertRecipeInfo(entity);

                //同步称量信息
                List<ZxWeightEntity> zxWeightEntities = ZxWeightService.Instance.GetWeightInfos(nowEneity.RecipeCode);
                for (int i = 1; i <= 3; i++)
                {
                    string typeName = string.Empty;
                    switch (i)
                    {
                        case 1:
                            typeName = "基部胶";
                            break;
                        case 2:
                            typeName = "中层胶";
                            break;
                        case 3:
                            typeName = "胎面胶";
                            break;
                        default:
                            break;
                    }
                    string MaterialName = Convert.ToString(newRecipe.GetType().GetProperty($"MaterialName{i}").GetValue(newRecipe));
                    if (!string.IsNullOrEmpty(MaterialName))
                    {
                        ZxWeightEntity weight = zxWeightEntities.FirstOrDefault(x => x.MaterialCode == MaterialName);
                        if (weight != null) //原来就有
                        {
                            weight.SetThickness = Convert.ToDecimal(newRecipe.GetType().GetProperty($"MaterialThickness{i}").GetValue(newRecipe)); //(decimal)newRecipe.MaterialThickness1;
                            weight.SetWidth = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialWidth{i}").GetValue(newRecipe)); //newRecipe.MaterialWidth1;
                            weight.SetWidth2 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialWidth{i}2").GetValue(newRecipe)); //newRecipe.MaterialWidth12;
                            weight.SetWidth3 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialWidth{i}3").GetValue(newRecipe)); //newRecipe.MaterialWidth13;
                            weight.SetLayer = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialLayers{i}").GetValue(newRecipe)); //newRecipe.MaterialLayers1;
                            weight.SetLayer2 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialLayers{i}2").GetValue(newRecipe)); //newRecipe.MaterialLayers12;
                            weight.SetLayer3 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialLayers{i}3").GetValue(newRecipe)); //newRecipe.MaterialLayers13;
                            ZxWeightService.Instance.UpdateWeightInfo(weight);
                        }
                        else //原来没有就添加
                        {
                            ZxWeightService.Instance.InsertWeightInfo(new ZxWeightEntity()
                            {
                                RecipeCode = newRecipe.RecipeCode,
                                MaterialCode = MaterialName,
                                MaterialName = MaterialName + typeName,
                                MaterialType = typeName,
                                SetThickness = Convert.ToDecimal(newRecipe.GetType().GetProperty($"MaterialThickness{i}").GetValue(newRecipe)),
                                SetWidth = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialWidth{i}").GetValue(newRecipe)),
                                SetWidth2 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialWidth{i}2").GetValue(newRecipe)),
                                SetWidth3 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialWidth{i}3").GetValue(newRecipe)),
                                SetLayer = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialLayers{i}").GetValue(newRecipe)),
                                SetLayer2 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialLayers{i}2").GetValue(newRecipe)),
                                SetLayer3 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialLayers{i}3").GetValue(newRecipe)),
                                SetError = 1,
                                IsUse = true,
                                IsDeleted = false,
                            });
                        }
                    }
                }

                //同步公共参数
                ZxRecipeParaEntity recipeParaEntity = new ZxRecipeParaEntity();
                recipeParaEntity.RimInch = newRecipe.RimInch;
                recipeParaEntity.LightWidth = newRecipe.FixRubWidth;
                recipeParaEntity.SlowDistance = 0;
                recipeParaEntity.StopDistance = 0;
                recipeParaEntity.TireWeight = newRecipe.TireWeight;
                recipeParaEntity.SpecCode = newRecipe.SpecCode;
                recipeParaEntity.SpecName = newRecipe.SpecName;
                recipeParaEntity.RecipeCode = newRecipe.RecipeCode;

                //自动工位选择
                zxWeightEntities.Clear();
                zxWeightEntities = ZxWeightService.Instance.GetWeightInfos(nowEneity.RecipeCode);
                List<ZxOpenMixMaterialEntity> openMixConfig = ZxOpenMixMaterialService.Instance.GetInfos();
                foreach (ZxWeightEntity weightEntity in zxWeightEntities)
                {
                    var config = openMixConfig.Where(x => x.MaterialName == weightEntity.MaterialName).FirstOrDefault();
                    if (config == null)
                    {
                        continue;
                    }
                    var prop = recipeParaEntity.GetType().GetProperty($"S{config.StationNo + 1}");
                    if (prop != null)
                    {
                        prop.SetValue(recipeParaEntity, true);
                    }
                    //自动包边选择
                    if (!(weightEntity.SetLayer2 == 0
                        || weightEntity.SetLayer2 == null
                        || weightEntity.SetWidth2 == null
                        || weightEntity.SetWidth2 == 0))
                    {
                        var propp = recipeParaEntity.GetType().GetProperty($"B{config.StationNo - 1}");
                        if (propp != null)
                        {
                            propp.SetValue(recipeParaEntity, true);
                        }
                    }
                    if (!(weightEntity.SetLayer3 == 0
                        || weightEntity.SetLayer3 == null
                        || weightEntity.SetWidth3 == null
                        || weightEntity.SetWidth3 == 0))
                    {
                        var propp = recipeParaEntity.GetType().GetProperty($"B{config.StationNo + 4}");
                        if (propp != null)
                        {
                            propp.SetValue(recipeParaEntity, true);
                        }
                    }
                    //设置胎体重量
                    if (weightEntity.MaterialType == "胎面胶")
                    {
                        recipeParaEntity.TireWeight = Convert.ToSingle(weightEntity.SetWeight);
                        switch (config.StationNo)
                        {
                            case 3:
                                recipeParaEntity.S7 = true;
                                break;
                            case 4:
                                recipeParaEntity.S8 = true;
                                break;
                            case 5:
                                recipeParaEntity.S9 = true;
                                break;
                            default:
                                break;
                        }
                    }
                }
                ZxRecipeParaEntity nowRecipeParaEntity = ZxRecipeParaService.Instance.GetRecipeParaInfoByRecipeCode(nowEneity.RecipeCode).FirstOrDefault();

                if (nowRecipeParaEntity != null) //如果存在就更改
                {
                    recipeParaEntity.Id = nowRecipeParaEntity.Id;
                    ZxRecipeParaService.Instance.UpdateRecipeParaInfo(recipeParaEntity);
                }
                else
                {
                    ZxRecipeParaService.Instance.InsertRecipeParaInfo(recipeParaEntity);
                }

                //同步工位参数
                ZxRecipePositionParaService.Instance.DeleteRecipePositionParaInfoByRecipeCode(newRecipe.RecipeCode); //删除可能存在的脏数据
                for (int i = 1; i <= 3; i++)
                {
                    string MaterialName = Convert.ToString(newRecipe.GetType().GetProperty($"MaterialName{i}").GetValue(newRecipe));
                    if (string.IsNullOrEmpty(MaterialName))
                    {
                        continue;
                    }

                    var config = openMixConfig.Where(x => x.MaterialName.Contains(MaterialName)).FirstOrDefault();
                    if (config == null)
                    {
                        continue;
                    }
                    ZxRecipePositionParaEntity positionEntity = new ZxRecipePositionParaEntity()
                    {
                        RecipeCode = newRecipe.RecipeCode,
                        Position = config.StationNo,
                        E1 = 15,
                        E2 = 52,
                        E5 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialLayers{i}").GetValue(newRecipe)) * 10,
                        E9 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialWidth{i}").GetValue(newRecipe)),
                        E6 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialLayers{i}2").GetValue(newRecipe)) * 10,
                        E7 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialWidth{i}2").GetValue(newRecipe)),
                        E3 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialLayers{i}3").GetValue(newRecipe)) * 10,
                        E4 = Convert.ToInt32(newRecipe.GetType().GetProperty($"MaterialWidth{i}3").GetValue(newRecipe)),
                        E10 = 800,
                        E8 = 300
                    };

                    ZxRecipePositionParaService.Instance.InsertRecipePositionParaInfo(positionEntity);
                }

            }

        }

        private void TestButton1_Click(object sender, EventArgs e)
        {
            var a = ZxMesPlanTransferService.Instance.GetRecipeInfos(x => x.RequestFlag == false).FirstOrDefault();
            SyncRecipe(a);
        }
    }
}
