using HighWayIot.Common.LANConnectConfig;
using HighWayIot.Common.XmlConfig;
using HighWayIot.TouchSocket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HighWayIot.Winform.MainForm
{
    public partial class MainForm : Form
    {

        public MainForm()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            TouchSocketCOM.Instance.ComAction += WeightData;
            action += AddWeightData;
            WeightCountComboBox.DataSource = Enumerable.Range(1, 24).ToList();
            RollNumberTextBox.KeyDown += TextBox_KeyDown;
        }

        private string WholeData = string.Empty;

        private string TempData = string.Empty;

        private List<double> WeightResults = new List<double>();

        private Action<string> action;

        private string AverageResult;

        /// <summary>
        /// 登陆验证
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Login_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 自动登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoginForm_Load(object sender, EventArgs e)
        {
            TouchSocketCOM.Instance.CreateConnection();
        }

        private void TestButton_Click(object sender, EventArgs e)
        {
            try
            {
                AddWeightData(XmlUtil.Instance.BaseInnerTextReader("InputPath"));
                AddWeightData(XmlUtil.Instance.BaseInnerTextReader("OutputPath"));
                foreach (var s in XmlUtil.Instance.ConfigReader())
                {
                    AddWeightData(s);
                }
            }
            catch
            {
                MessageBox.Show("配置文件读取失败，请检查配置文件是否存在或格式是否正确。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 处理串口数据
        /// </summary>
        /// <param name="data"></param>
        public void WeightData(string data)
        {
            data.Trim();
            TempData = TempData + data;
            // 检查数据是否包含单次称量结束标志（g）
            if (TempData.Contains("g"))
            {
                // 提取数据，去掉结束标志（g）后的部分
                WholeData = TempData.Substring(0, TempData.IndexOf("g")).Trim();
                TempData = string.Empty;
                // 检查数据是否为数字（浮点数）格式
                if (double.TryParse(WholeData, out double result))
                {
                    WeightResults.Add(result); // 将结果添加到列表中 
                }
                else
                {
                    action.Invoke($"第[{WeightResults.Count}]次称重数据格式转换失败");
                    return;
                }
                action.Invoke($"第{WeightResults.Count}次称重：{WholeData}g");
                // 检查是否达到了预期的称重次数
                if (WeightResults.Count.ToString() == WeightCountComboBox.Text)
                {
                    double resultAvg = WeightResults.Average(); // 计算平均值
                    AverageResult = resultAvg.ToString("F5"); // 保留5位小数
                    action.Invoke($"膜卷号[{RollNumberTextBox.Text}]称重结束，结果为[{AverageResult}]，请上传结果");
                    action.Invoke($"-----------------------------------------------------");
                    WeightResultTextBox.Text = AverageResult; // 结果输出到文本框
                    WeightResults.Clear(); // 清空结果列表，准备下一次称重
                }
            }
        }

        /// <summary>
        /// 向ListBox中添加数据
        /// </summary>
        /// <param name="data"></param>
        private void AddWeightData(string data)
        {
            LogBox.Items.Add(data);
            LogBox.TopIndex = LogBox.Items.Count - 1;
        }

        /// <summary>
        /// 按的是回车键时清空当前选中的 TextBox
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                TextBox currentTextBox = sender as TextBox;
                if (currentTextBox != null)
                {
                    //回车后的业务逻辑
                    //先核对膜卷号

                    //准备开始称重
                    action.Invoke($"膜卷号[{RollNumberTextBox.Text}]开始称重");
                    WeightResults.Clear();
                    WeightResultTextBox.Clear();
                    e.Handled = true;       // 阻止触发 AcceptButton（如果有）
                }
            }
        }

        /// <summary>
        /// 写入测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WriteInTestButton_Click(object sender, EventArgs e)
        {
            AddWeightData(LANConnect.Instance.WriteTxt(XmlUtil.Instance.BaseInnerTextReader("OutputPath"), $"{RollNumberTextBox.Text}.txt", "测试11111").ToString());
        }

        /// <summary>
        /// 剪切测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CutTestButton_Click(object sender, EventArgs e)
        {
            AddWeightData(LANConnect.Instance.MoveFile(XmlUtil.Instance.BaseInnerTextReader("InputPath"), XmlUtil.Instance.BaseInnerTextReader("ArchievePath"), $"{RollNumberTextBox.Text}.txt").ToString());
        }

        /// <summary>
        /// 读取测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReadTestButton_Click(object sender, EventArgs e)
        {
            AddWeightData(LANConnect.Instance.ReadTxt(XmlUtil.Instance.BaseInnerTextReader("InputPath"), $"{RollNumberTextBox.Text}.txt"));
        }
    }
}
