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 DotNettyFrom.config;
using DotNettyFrom.db;
using DotNettyFrom.model;
using DotNettyFrom.util;

namespace DotNettyFrom.form
{
    public delegate void OnItemHandlerResult(int action, string message);

    public partial class ItemEditorForm : Form
    {
        public event OnItemHandlerResult ItemHandler;
        private string _id;
        private bool _isAdd = true; //true-add

        private int len = 4;

        public ItemEditorForm(string id = null)
        {
            this._id = id;
            InitializeComponent();
        }

        private void ItemEditorForm_Load(object sender, EventArgs e)
        {
            CBInputType.SelectedIndex = 0;
            CbProtocolNo.SelectedIndex = SystemConfig.CurrentType - 1;


            if (SystemConfig.CurrentType == SystemConfig.Dtu)
            {
                len = 4;
            }
            else if (SystemConfig.CurrentType == SystemConfig.Water2)
            {
                len = 2;
            }

            if (_id != null)
            {
                _isAdd = false;
                try
                {
                    int id = int.Parse(_id);
                    UpdateOption(id);
                }
                catch (Exception)
                {
                    this.Close();
                }
            }
        }

        private void UpdateOption(int id)
        {
            BtnOp.Text = "修改";
            WvBean wb = DbHelper.GetInstance().SelectOneCmdById(id);
            if (wb == null)
            {
                MessageBox.Show("出错,数据库找不到.id = " + id);
                this.Close();
            }
            this.Text = "修改ID - " + wb.id;
            _isAdd = false;

            CbProtocolNo.SelectedIndex = wb.protocolNo - 1;

            TbItemId.Enabled = false;
            CBInputType.Enabled = false;

            LbDbPriKey.Text = wb.id + "";
            TbItemId.Text = wb.index + "";
            TbitemId2.Text = wb.myId;
            TbInfo.Text = wb.idInfo;
            if (wb.len.Contains("-"))
            {
                TbLen.Enabled = false;
                CBLenUnFix.Checked = true;
            }
            else
            {
                TbLen.Text = wb.len;
            }
            if (wb.mode.Contains("R"))
            {
                CheckBoxRead.Checked = true;
            }
            if (wb.mode.Contains("W"))
            {
                CheckBoxWrite.Checked = true;
            }
            TbDesp.Text = wb.desp;
            TbDv.Text = wb.defalutValue;
            TbUv.Text = wb.userValue;
            TbRemark.Text = wb.remark;
        }


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

        private void TbItemId_TextChanged(object sender, EventArgs e)
        {
            string text = TbItemId.Text.Trim();
            if (text.Equals(""))
            {
                TbitemId2.Text = "";
                return;
            }
            if (CBInputType.SelectedIndex == 0)
            {
                //10 ->16

                try
                {
                    int _id = int.Parse(text);
                    TbitemId2.Text = CmdUtil.FrontWithZero(CmdUtil.Dec2Hex(_id), len);
                    RtbInfo.Text = "";
                }
                catch (Exception esException)
                {
                    RtbInfo.Text = esException.Message;
                }
            }
            else if (CBInputType.SelectedIndex == 1)
            {
                //16 -> 10

                try
                {
                    TbitemId2.Text = CmdUtil.Hex2Dec(text) + "";
                    RtbInfo.Text = "";
                }
                catch (Exception esException)
                {
                    RtbInfo.Text = esException.Message;
                }
            }
        }

        private void BtnOp_Click(object sender, EventArgs e)
        {
            RtbInfo.Text = "";

            #region Check

            int MyIndex = Int32.MinValue;
            string MyId = "";


            if (TbItemId.Text.Trim().Equals(""))
            {
                RtbInfo.Text = "ID不能为空";
                return;
            }

            if (TbitemId2.Text.Trim().Equals(""))
            {
                RtbInfo.Text = "ID不能为空";
                return;
            }


            if (CBInputType.SelectedIndex == 0)
            {
                MyIndex = int.Parse(TbItemId.Text.Trim());
                MyId = TbitemId2.Text.Trim();
            }
            else if (CBInputType.SelectedIndex == 1)
            {
                MyIndex = int.Parse(TbitemId2.Text.Trim());
                MyId = TbItemId.Text.Trim();
            }

            string lenString = "";

            if (!CBLenUnFix.Checked)
            {
                lenString = TbLen.Text.Trim();
            }
            else
            {
                lenString = "-1";
            }

            if (lenString.Equals(""))
            {
                RtbInfo.Text = "长度不能为空!";
                return;
            }

            bool modeBool = CheckBoxWrite.Checked || CheckBoxRead.Checked;
            if (!modeBool)
            {
                RtbInfo.Text = "读写模式不能为空.至少要有一个!";
                return;
            }

            string defalutValueString = TbDv.Text.Trim();
            string userValueString = TbUv.Text.Trim();
            if (defalutValueString.Equals(""))
            {
                RtbInfo.Text = "默认长度不能为空!";
                return;
            }
            if (userValueString.Equals(""))
            {
                userValueString = defalutValueString;
            }


            if (defalutValueString.Length % 2 != 0)
            {
                RtbInfo.Text = "默认值长度不是整数!!!defalutValueString.Length=" + (defalutValueString.Length / 2.0);
                return;
            }
            if (userValueString.Length % 2 != 0)
            {
                RtbInfo.Text = "用户值长度不是整数!!!defalutValueString.Length=" + (userValueString.Length / 2.0);
                return;
            }

            if (!lenString.Contains("-") && CBUnCheckUD.Checked)
            {
                int len = int.Parse(lenString);

                if ((defalutValueString.Length / 2) != len)
                {
                    RtbInfo.Text = "默认值长度不对.定义长度是=" + len + " ,你输入长度是=" +
                                   (defalutValueString.Length / 2);
                    return;
                }
                if ((userValueString.Length / 2) != len)
                {
                    RtbInfo.Text = "用户值长度不对.定义长度是=" + len + " ,你输入长度是=" + (userValueString.Length / 2.0);
                    return;
                }
            }

            #endregion

            #region 组装操作

            WvBean wb = new WvBean();
            wb.index = MyIndex;
            wb.myId = MyId;
            wb.idInfo = TbInfo.Text.Trim();
            wb.len = lenString;
            string modeString = CheckBoxRead.Checked ? "R" : "";
            modeString += CheckBoxWrite.Checked ? "W" : "";
            wb.mode = modeString;
            wb.desp = TbDesp.Text.Trim();
            wb.defalutValue = defalutValueString;
            wb.userValue = userValueString;
            wb.remark = TbRemark.Text.Trim();
            wb.protocolNo = CbProtocolNo.SelectedIndex + 1;

            #endregion

            #region 数据库

            int res = -1;


            if (_isAdd)
            {
                //add
                try
                {
                    res = DbHelper.GetInstance().InsertCmd(wb);
                }
                catch (Exception exception)
                {
                    RtbInfo.Text = "异常:" + exception.Message + "\n请确定 " + MyIndex + " 是否已经存在";
                }
            }
            else
            {
                //update
                try
                {
                    wb.id = int.Parse(LbDbPriKey.Text);
                    res = DbHelper.GetInstance().UpdateCmd(wb);
                }
                catch (Exception exception)
                {
                    RtbInfo.Text = "异常:" + exception.Message + "\n请确定 " + MyIndex + " 是否已经存在";
                }
            }

            if (res > 0)
            {
                if (ItemHandler != null)
                    this.ItemHandler(0, "成功"); //执行委托实例  
                this.Close();
            }

            #endregion
        }

        private void CBLenUnFix_CheckedChanged(object sender, EventArgs e)
        {
            if (CBLenUnFix.Checked)
            {
                TbLen.Text = "";
                TbLen.Enabled = false;
            }
            else
            {
                TbLen.Enabled = true;
            }
        }

        private void TbLen_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void TbDv_TextChanged(object sender, EventArgs e)
        {
            LbDefaultV.Text = (TbDv.Text.Trim().Length / 2.0) + "";
        }

        private void TbUv_TextChanged(object sender, EventArgs e)
        {
            LbUserV.Text = (TbUv.Text.Trim().Length / 2.0) + "";
        }
    }
}