using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO.Ports;
using System.Linq.Expressions;
using System.Linq;

namespace FileWatcher
{
    public partial class AutoMakeQTY : Form
    {

        DataHelper dh;

        DataTable dt;

        DataTable DB;

        /// <summary>
        /// 用户编号
        /// </summary>
        string iusercode;
        /// <summary>
        /// 岗位资源
        /// </summary>
        string isource;

        Thread InitDB;
        /// 当前工序
        /// </summary>
        string istepcode;
        StringBuilder sql = new StringBuilder();
        /// <summary>
        /// 缓存的文件
        /// </summary>
        public static string CachePath = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":/UAS_MES/XmlAnalysor/Cache.xml";
        /// <summary>
        /// 缓存的文件夹
        /// </summary>
        public static string CachePathFolder = Environment.GetEnvironmentVariable("windir").Substring(0, 1) + @":/UAS_MES/XmlAnalysor/";

        ftpOperater ftp = new ftpOperater();

        public AutoMakeQTY()
        {
            InitializeComponent();
            StartPosition = FormStartPosition.CenterScreen;
        }
        DataTable Dbfind;

        string IPAddress = "";
        private void nr_rule_DBChange(object sender, EventArgs e)
        {
            Dbfind = li_code.ReturnData;
            BaseUtil.SetFormValue(this.Controls, Dbfind);
        }

        private int Val(char Expression)
        {
            if (Expression >= '1' && Expression <= '9')
            {
                return unchecked((int)Expression) - 48;
            }
            return 0;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            byte[] b2 = new byte[4];
            float f2;
            string tmp_b2 = "43666AEC";

            tmp_b2 = tmp_b2.Replace(" ", "");//删除字符串中间的空格

            if (tmp_b2.Length != 8)
            {
                //判断输入字符串的长度是否合适
                MessageBox.Show("输入Byte长度错误,为连续8位4个字节,高位为0的补齐0");
            }
            else
            {
                //将收到的字符串分成4个字节,这4个字节是字符串的形式
                string tmp_char1 = tmp_b2.Substring(0, 2);
                string tmp_char2 = tmp_b2.Substring(2, 2);
                string tmp_char3 = tmp_b2.Substring(4, 2);
                string tmp_char4 = tmp_b2.Substring(6, 2);
                //将4字节的字符串格式转换成16进制的byte格式
                b2[3] = Convert.ToByte(tmp_char1, 16);
                b2[2] = Convert.ToByte(tmp_char2, 16);
                b2[1] = Convert.ToByte(tmp_char3, 16);
                b2[0] = Convert.ToByte(tmp_char4, 16);

                //将16进制byte转换成浮点数格式
                f2 = BitConverter.ToSingle(b2, 0);
                Console.WriteLine(Convert.ToString(f2)); ;
            }


            CheckForIllegalCrossThreadCalls = false;
            FormBorderStyle = FormBorderStyle.FixedSingle;
            serialPort1.DataReceived += SerialPort1_DataReceived;
            InitDB = new Thread(ConnectDB);
            //添加监控事件
            XmlWatcher.Changed += new FileSystemEventHandler(XmlWatcher_Created);
            //ATEFile.Changed += new FileSystemEventHandler(XmlWatcher_Created);
            SetLoadingWindow stw = new SetLoadingWindow(InitDB, "正在启动程序");
            stw.StartPosition = FormStartPosition.CenterScreen;
            stw.ShowDialog();
            List<string> CacheInf = new List<string>();
            IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
            for (int i = 0; i < IpEntry.AddressList.Length; i++)
            {
                if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    IPAddress = IpEntry.AddressList[i].ToString();
            }
            //获取缓存信息
            try
            {
                Type.Text = BaseUtil.GetCacheData("Type").ToString();
                ComPort.Text = BaseUtil.GetCacheData("ComPort").ToString();
                BaudRate.Text = BaseUtil.GetCacheData("BaudRate").ToString();
                li_code.Text = BaseUtil.GetCacheData("Line").ToString();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }

        double lastqty = 0;
        private void SerialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int len = serialPort1.BytesToRead;
            Byte[] readBuffer = new Byte[len];
            serialPort1.Read(readBuffer, 0, len); //将数据读入缓存
            string data = BitConverter.ToString(readBuffer, 0, readBuffer.Length).Replace("-", "");

            //Convert.ToInt32(data.Substring(6, 8), 16);
            //Console.WriteLine(data.Substring(6, 2));
            //double Num1 = double.Parse(data.Substring(8, 2)) * 10000;
            //Console.WriteLine(data.Substring(8, 2));
            //double Num2 = double.Parse(data.Substring(10, 2)) * 1000;
            //Console.WriteLine(data.Substring(10, 2));
            //double Num3 = double.Parse(data.Substring(12, 2)) * 100;
            //Console.WriteLine(data.Substring(12, 2));
            //double Num4 = double.Parse(data.Substring(14, 2)) * 10;
            //Console.WriteLine(data.Substring(14, 2));
            //double Num5 = double.Parse(data.Substring(16, 2));
            if (data != "")
            {
                double qty = Convert.ToInt32(data.Substring(6, 8), 16);
                if (lastqty > qty)
                {
                    lastqty = 0;
                }
                NowQTY.Text = qty.ToString();
                if (Type.Text == "投入")
                {
                    string ma_inqty = dh.getFieldDataByCondition("make", "nvl(ma_inqty,0)", "ma_code='" + ma_code.Text + "'").ToString();
                    dh.ExecuteSql("update make set ma_inqty=nvl(ma_inqty,0)+'" + (qty - lastqty) + "' where ma_code='" + ma_code.Text + "' ", "update");
                    dh.ExecuteSql("insert into makehourcount(mhc_id,mhc_macode,mhc_indate,mhc_type,mhc_qty,mhc_linecode)" +
                        "values(makehourcount_seq.nextval,'" + ma_code.Text + "',sysdate,'" + Type.Text + "','" + (qty - lastqty) + "','" + li_code.Text + "')", "insert");
                }
                else
                {
                    string ma_endqty = dh.getFieldDataByCondition("make", "nvl(ma_endqty,0)", "ma_code='" + ma_code.Text + "'").ToString();
                    dh.ExecuteSql("update make set ma_endqty=nvl(ma_endqty,0)+'" + (qty - lastqty) + "' where ma_code='" + ma_code.Text + "' ", "update");
                    dh.ExecuteSql("insert into makehourcount(mhc_id,mhc_macode,mhc_indate,mhc_type,mhc_qty,mhc_linecode)" +
                             "values(makehourcount_seq.nextval,'" + ma_code.Text + "',sysdate,'" + Type.Text + "','" + (qty - lastqty) + "','" + li_code.Text + "')", "insert");
                }
                lastqty = qty;
            }
        }

        private void ConnectDB()
        {
            dh = new DataHelper();
            SystemInf.dh = dh;

            ma_code.TableName = "make";
            ma_code.SelectField = "ma_code # 工单号";
            ma_code.FormName = Name;
            ma_code.DBTitle = "工单查询";
            ma_code.SetValueField = new string[] { "ma_code" };
            ma_code.Condition = "";
            ma_code.DbChange += nr_rule_DBChange;

            li_code.TableName = "line";
            li_code.SelectField = "li_code # 线别编号,li_name # 线别名称";
            li_code.FormName = Name;
            li_code.DBTitle = "线别查询";
            li_code.SetValueField = new string[] { "li_code" };
            li_code.Condition = "";
            li_code.DbChange += nr_rule_DBChange;
        }
        SerialPort serialPort1 = new SerialPort();



        private void StartWatch_Click(object sender, EventArgs e)
        {
            BaseUtil.SetCacheData("Type", Type.Text);
            BaseUtil.SetCacheData("ComPort", ComPort.Text);
            BaseUtil.SetCacheData("BaudRate", BaudRate.Text);
            BaseUtil.SetCacheData("Line", li_code.Text);
            if (!dh.CheckExist("Make", "ma_code='" + ma_code.Text + "'"))
            {
                OperateResult.AppendText("工单号不能为空\n");
                return;
            }
            if (!dh.CheckExist("line", "li_code='" + li_code.Text + "'"))
            {
                OperateResult.AppendText("线别不能为空\n");
                return;
            }
            if (Type.Text == "印刷机")
            {
              
            }
            else
            {
                string ExitConfirm = MessageBox.Show(this, "确认计数器是否置为0?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
                if (ExitConfirm != "Yes")
                {
                    return;
                }
                //设置按钮不可点击
                StartWatch.Enabled = false;
                ma_code.Enabled = false;
                StopWatch.Enabled = true;
                try
                {
                    serialPort1.PortName = ComPort.Text;
                    serialPort1.BaudRate = int.Parse(BaudRate.Text);
                    serialPort1.Open();
                    Timer.Start();
                }
                catch (Exception mes)
                {
                    if (BaudRate.Text == "" || BaudRate.Text == "")
                        OperateResult.AppendText(">>请先维护波特率和串口\n");
                    else
                        OperateResult.AppendText(">>" + mes.Message + "\n");
                }
            }
            OperateResult.AppendText("开始执行监控\n");
        }

        private void XmlWatcher_Created(object sender, FileSystemEventArgs e)
        {
            OperateResult.AppendText("文件修改:" + e.FullPath + "\n");
            TxtHandleProcess(e.FullPath);
        }

        string nextLine;
        private void TxtHandleProcess(string FileName)
        {
            List<string> badcode = new List<string>();
            List<string> badlocation = new List<string>();
            List<string> badprod = new List<string>();

        }

        private void StopWatch_Click(object sender, EventArgs e)
        {
            XmlWatcher.EnableRaisingEvents = false;
            StartWatch.Enabled = true;
            ma_code.Enabled = true;

            StopWatch.Enabled = false;
            OperateResult.AppendText("停止执行监控\n");
        }

        private void Clean_Click(object sender, EventArgs e)
        {
            OperateResult.Clear();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            string ExitConfirm = MessageBox.Show(this, "确认退出?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString();
            if (ExitConfirm != "Yes")
            {
                WindowState = FormWindowState.Minimized;
                e.Cancel = true;
            }
        }


        private void Timer_Tick(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                byte[] data = HexStringToBytes("01 03 00 01 00 06 94 08");
                serialPort1.Write(data, 0, data.Length);
            }

            if (Type.Text == "印刷机")
            {
                DateTime targetDate = new DateTime(2025, 3, 17);
                var AllXmls = Directory.GetFiles(FolderPath.Text, "*.*", SearchOption.AllDirectories).Where(s => s.ToUpper().EndsWith(".CSV") || s.ToUpper().EndsWith(".INI"));
                foreach (var Xml in AllXmls)
                {
                    //解析当天日志
                    if (Xml.Contains(DateTime.Now.ToString("yyyy-MM-dd")))
                    {
                        var filteredLines = File.ReadLines(Xml).Skip(1) // 跳过标题行
                        .Where(line =>
                        {
                            string[] parts = line.Split(',');
                            if (parts.Length < 2) return false;
                            if (DateTime.TryParse(parts[1], out DateTime timestamp))
                            {
                                return timestamp > DateTime.Now.AddDays(-10);
                            }
                            return false;
                        });
                        foreach (var line in filteredLines)
                        {
                            dh.ExecuteSql("insert into makehourcount(mhc_id,mhc_macode,mhc_indate,mhc_type,mhc_qty,mhc_linecode)" +
                         "values(makehourcount_seq.nextval,'" + ma_code.Text + "',sysdate,'" + Type.Text + "','1','" + li_code.Text + "')", "insert");
                        }
                    }
                }
            }
        }

        private void AutoStart_CheckedChanged(object sender, EventArgs e)
        {
            SetAutoRun();
        }
        private void SetAutoRun()
        {
            if (AutoStart.Checked) //设置开机自启动  
            {
                string path = Application.ExecutablePath;
                RegistryKey rk = Registry.LocalMachine;
                RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                rk2.SetValue("FileWatcher.exe", path);
                rk2.Close();
                rk.Close();
            }
            else //取消开机自启动  
            {
                string path = Application.ExecutablePath;
                RegistryKey rk = Registry.LocalMachine;
                RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                rk2.DeleteValue("FileWatcher.exe", false);
                rk2.Close();
                rk.Close();
            }
        }

        private byte[] HexStringToBytes(string hs)//十六进制字符串转byte
        {
            string a = hs.Replace(" ", "");
            int bytelength = 0;
            if (a.Length % 2 == 0)
            {
                bytelength = a.Length / 2;
            }
            else
            {
                bytelength = a.Length / 2 + 1;
            }
            byte[] b = new byte[bytelength];
            //逐个字符变为16进制字节数据
            for (int i = 0; i < bytelength; i++)
            {
                if (i == bytelength - 1)
                {
                    b[i] = Convert.ToByte(a.Substring(i * 2), 16);
                }
                else
                {
                    b[i] = Convert.ToByte(a.Substring(i * 2, 2), 16);
                }
            }
            //按照指定编码将字节数组变为字符串
            return b;
        }

        private void ChooseFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folder = new FolderBrowserDialog();
            folder.Description = "选择监控文件夹";
            DialogResult result = folder.ShowDialog();
            if (result == DialogResult.OK)
            {
                FolderPath.Text = folder.SelectedPath;
            }
        }
    }
}