using System;
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 LFP_Manager.DataStructure;
using LFP_Manager.Function;
using LFP_Manager.Controls;
using LFP_Manager.Utils;

namespace LFP_Manager.Forms
{
    public partial class fmxInventoryConfig2 : DevExpress.XtraEditors.XtraForm
    {
        #region VARIABLES

        private bool fBarCode = false;
        private bool ctrlKey = false;

        private CommConfig Config;
        private int SystemId = 0;
        private int CmdResult = 0;
        private int CellDivUnit = 0;
        private DeviceSystemData SystemData;
        private DeviceInforation wInvDate;

        private string oldMdSn;

        public event InvDataUpdateEvent OnUpdate = null;
        public event InvDateCmdEvent OnCommand = null;

        #endregion

        #region CONSTRUCTORS
        public fmxInventoryConfig2()
        {
            InitializeComponent();
        }

        public fmxInventoryConfig2(CommConfig aConfig, int sId, ref DeviceSystemData aSystemData, int aCellDivUnit)
        {
            InitializeComponent();

            oldMdSn = "";
            Config = aConfig;
            SystemId = sId;
            SystemData = aSystemData;
            SystemData.mNo = SystemId;

            CellDivUnit = aCellDivUnit;

            tmrDisplay.Enabled = true;
            tmrCmd.Enabled = true;

            KeyPreview = true;
            KeyDown += new KeyEventHandler(teBarCode_KeyDown);
            KeyPress += new KeyPressEventHandler(teBarCode_KeyPress);
        }
        #endregion

        void InitData()
        {
            wInvDate = new DeviceInforation
            {
                module_sn = new byte[32]
            };
        }

        #region TIMER ENVENT

        private void tmrDisplay_Tick(object sender, EventArgs e)
        {
            DisplayValue();
            OnUpdate?.Invoke(this);
        }

        #endregion

        #region PUBLIC FUCTIONS
        public void UpdateData(ref DeviceSystemData aSystemData)
        {
            SystemData = aSystemData;
        }

        #endregion

        #region PROCESSING DATA

        private bool CheckMdSerialNo(string mSN)
        {
            bool result = false;

            csDbUtils.MdDbCreate(Config, mSN);

            DataTable dtMdData = new DataTable();
            DataTable dtMdMatch = new DataTable();
            DataTable dtErrorLog = new DataTable();

            //string sql = String.Format("SELECT * FROM TInventoryData WHERE pcb_sn = {0}", bSN);
            string sql = String.Format("SELECT * FROM TInventoryData");
            dtMdData = csDbUtils.GetDataTableBySelect(Config, mSN, sql, "TInventoryData");

            if (dtMdData != null)
            {
                if (dtMdData.Rows.Count > 1)
                {
                    DataRow[] arrRows = null;
                    arrRows = dtMdData.Select(String.Format("module_sn = '{0}'", mSN));
                    if (arrRows.Length > 0) { result = true; }
                }
            }
            return result;
        }
        private void CmdMDateWrite()
        {
            UInt32 mTimeStamp = csUtils.CalcKKTimeStamp(DateTime.Now);
            wInvDate.ManufactureDate = mTimeStamp;

            OnCommand?.Invoke(SystemId, 999, 1, ref wInvDate);
        }

        private void CheckResult()
        {
            byte[] a = Encoding.UTF8.GetBytes(nMdNo.Text);
            byte[] b = SystemData.Information.pcb_sn;

            try
            {
                csDbUtils.MdLogDataInsert(ref Config, nMdNo.Text, ref SystemData, DateTime.Now, CellDivUnit);
                csDbUtils.MdSnDataInsert(Config, SystemData, nMdNo.Text);

                oldMdSn = nMdNo.Text;

                //MessageBox.Show(String.Format("Module data insert complete - [{0}]", nMdNo.Text)
                //    , "Information"
                //    , MessageBoxButtons.OK
                //    , MessageBoxIcon.Information
                //    );
                lbResult.Text = String.Format("PASS: {0}", String.Format("Module data insert complete - [{0}]", nMdNo.Text));
                lbResult.ForeColor = Color.Blue;
            }
            catch (Exception ex)
            {
                throw new Exception(String.Format("Module data insert fail - [{0}] \r\n{1}", nMdNo.Text, ex.Message));
                //MessageBox.Show(String.Format("Module data insert fail - [{0}] \r\n{1}", nMdNo.Text, ex.Message)
                //    , "Warning"
                //    , MessageBoxButtons.OK
                //    , MessageBoxIcon.Warning
                //    );
            }
        }

        private bool SelectModuleSN(string mSN)
        {
            bool result = false;

            //string sql = String.Format("SELECT * FROM TInventoryData WHERE pcb_sn = {0}", bSN);
            string sql = String.Format("SELECT * FROM TModuleValue");
            DataTable dtMdData = csDbUtils.GetDataTableBySelect(Config, mSN, sql, "TModuleValue");

            if (dtMdData != null)
            {
                if (dtMdData.Rows.Count > 0)
                {
                    mnView.DataSource = dtMdData;
                    //DataRow[] arrRows = null;
                    //arrRows = dtMdData.Select(String.Format("module_sn = '{0}'", mSN));
                    //if (arrRows.Length > 0) { result = true; }
                }
                gbDvResult.Text = string.Format("Module Number List ({0})", dtMdData.Rows.Count);
            }
            return result;
        }

        #endregion

        #region BUTTON EVENT

        private void btnInvWrite_Click(object sender, EventArgs e)
        {
            string result = "";
            try
            {
                if (nMdNo.Text.Length == 24)
                {
                    csDbUtils.MdDbCreate(Config, nMdNo.Text);
                    if ((SystemData.Information.pcb_sn == null) || (SystemData.Information.pcb_sn == null) || (SystemData.Information.pcb_sn[0] == 0))
                    {
                        result = "No BMS Serial Number - Please check CAN communication";
                        return;
                    }

                    if (CheckMdSerialNo(nMdNo.Text) == false)
                    {
                        CheckResult();

                        //byte[] mSN = Encoding.UTF8.GetBytes(nMdNo.Text);

                        //if (wInvDate.module_sn == null) wInvDate.module_sn = new byte[32];
                        //for (int i = 0; i < wInvDate.module_sn.Length; i++)
                        //{
                        //    wInvDate.module_sn[i] = 0;
                        //}
                        //for (int i = 0; i < mSN.Length; i++)
                        //{
                        //    wInvDate.module_sn[i] = mSN[i];
                        //}
                        //CmdMDateWrite();

                        //CmdResult = 1;
                    }
                    else
                    {
                        result = "Already used Module serial number";
                    }
                }
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            finally
            {
                if (result != "")
                {
                    //_ = MessageBox.Show(string.Format("{0} - [{1}]", result, nMdNo.Text)
                    //    , "Warning"
                    //    , MessageBoxButtons.OK
                    //    , MessageBoxIcon.Warning
                    //    );
                    lbResult.Text = String.Format("Fail: {0}", result);
                    lbResult.ForeColor = Color.Red;

                    csLog.SystemErrorLog(Config, result, DateTime.Now, Application.ExecutablePath);
                }
                oldMdSn = nMdNo.Text;
                nMdNo.Text = "";
            }
        }
        #endregion

        #region DISPLAY DATA

        private void DisplayValue()
        {
            // Device PCB S/N
            byte[] tmpPcbNo = new byte[SystemData.Information.pcb_sn.Length + 1];
            for (int i = 0; i < SystemData.Information.pcb_sn.Length; i++)
            {
                tmpPcbNo[i] = SystemData.Information.pcb_sn[i];
            }
            tmpPcbNo[SystemData.Information.pcb_sn.Length] = 0;

            string strPcbSerial = Encoding.Default.GetString(tmpPcbNo).Trim('\0');
            lbPcbSerial.Text = String.Format("BMS S/N: {0}", strPcbSerial);

            // Device Module S/N
            byte[] tmpMdNo = new byte[SystemData.Information.module_sn.Length + 1];
            for (int i = 0; i < SystemData.Information.module_sn.Length; i++)
            {
                tmpMdNo[i] = SystemData.Information.module_sn[i];
            }
            tmpMdNo[SystemData.Information.module_sn.Length] = 0;

            string strMdSerial = Encoding.Default.GetString(tmpMdNo).Trim('\0');
            lbMdSerial.Text = String.Format("Module S/N: {0}", strMdSerial);
        }

        #endregion

        #region GLOBAL KEYBOARD HOOK
        private void fmxInventoryConfig2_Load(object sender, EventArgs e)
        {
        }

        private void teBarCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (fBarCode == false)
            {
                if (e.KeyChar == 0x0D)
                {
                    fBarCode = true;

                    btnInvWrite_Click(sender, e);
                    //checkBarCode1(nMdNo.Text);
                }
                else if (e.KeyChar == 22)
                {
                    //ctrlKey = true;
                    IDataObject ido = Clipboard.GetDataObject();
                    if (ido.GetDataPresent(typeof(string)))
                    {
                        nMdNo.Text = (string)ido.GetData(typeof(string));
                    }
                }
                else if (e.KeyChar > 0x20)
                {
                    if (e.KeyChar == 'v')
                    {
                        if (ctrlKey)
                        {
                            IDataObject ido = Clipboard.GetDataObject();
                            if (ido.GetDataPresent(typeof(string)))
                            {
                                nMdNo.Text = (string)ido.GetData(typeof(string));
                            }
                        }
                    }
                    else
                    {
                        nMdNo.Text += e.KeyChar;
                    }
                }
            }
        }

        private void teBarCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (fBarCode)
            {
                nMdNo.Text = "";
                fBarCode = false;
            }
        }

        public void checkBarCode1(string code)
        {
            if (CheckMdSerialNo(code))
            {

            }
            else
            {

            }

            //if (dt.Rows.Count > 0)
            //{
            //    DataRow aRow = dt.Rows[0];

            //    MakeCellInformation(aRow);
            //    MakeCellAssyNo(aRow);
            //}
            //else
            //{
            //    MakeBarCodeForm("The data could" + Environment.NewLine + "not be found." + Environment.NewLine + "(无数据)", 1);
            //}
        }

        private void MakeBarCodeForm(string result, int flag)
        {
            lbResult.Text = result;
            switch (flag)
            {
                case 0:
                    lbResult.ForeColor = Color.Blue;
                    break;
                case 1:
                    lbResult.ForeColor = Color.Red;
                    break;
            }
        }

        #endregion

        #region BUTTON EVENT

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                string lotNo;
                if (oldMdSn == "")
                {
                    lotNo = "01PPBCNA013006CAW0000019";
                }
                else
                {
                    lotNo = oldMdSn;
                }
                SelectModuleSN(lotNo);
                mnView.AutoResizeColumns();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnExportExcel_Click(object sender, EventArgs e)
        {
            //
        }
        #endregion
    }
}