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;

namespace MixTraffic
{
    public partial class frmCommonCluster : Form
    {
        DataHelper _DataHelper;
        CommonCluster curCommonCluster = null;
        int curIndex = 0;
        private static frmCommonCluster _CommonClusterForm;
        public static frmCommonCluster ShowForm(DataHelper DataHelper)
        {
            if (_CommonClusterForm == null)
            {
                _CommonClusterForm = new frmCommonCluster(DataHelper);
                _CommonClusterForm.FormClosed += _CommonClusterForm_FormClosed;
                _CommonClusterForm.WindowState = FormWindowState.Maximized;
                _CommonClusterForm.Show();
            }
            else
            {
                _CommonClusterForm.Activate();
            }
            return _CommonClusterForm;
        }

        private static void _CommonClusterForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            _CommonClusterForm = null;
        }

        private  frmCommonCluster(DataHelper DataHelper)
        {
            InitializeComponent();
            Register();
            _DataHelper = DataHelper;
            cmbOccupiedWay.DropDownStyle = ComboBoxStyle.DropDownList;
            cmbOccupiedWay.SelectedIndex = 0;
        }

        private void Register()
        {
            btnAdd.Click += BtnAdd_Click;
            btnEdit.Click += BtnEdit_Click;
            btnDelete.Click += BtnDelete_Click;
            lvCommonClusters.SelectedIndexChanged += LvCommonClusters_SelectedIndexChanged;
            btnRefresh.Click += BtnRefresh_Click;
            this.Load += FrmCommonCluster_Load;
        }

        private void FrmCommonCluster_Load(object sender, EventArgs e)
        {
            LoadFromTable();
        }

        private void BtnRefresh_Click(object sender, EventArgs e)
        {
            LoadFromTable(curIndex);
        }

        void LoadFromTable(int selectedIndex = 0)
        {
            lvCommonClusters.Items.Clear();
            using (var session = _DataHelper.session)
            {
                var clusters = session.QueryOver<CommonCluster>().List();
                if (clusters != null)
                {
                    foreach (var item in clusters)
                    {
                        ListViewItem subItem = new ListViewItem();
                        subItem.Tag = item;
                        subItem.Text = item.ID.ToString();
                        subItem.SubItems.Add(item.OccupiedWay>=0&&item.OccupiedWay<3?((OccupiedWay)item.OccupiedWay).ToString():"其他");
                        subItem.SubItems.Add(item.Address.ToString());
                        subItem.SubItems.Add(item.Edges);
                        lvCommonClusters.Items.Add(subItem);

                    }
                }
            }
            if (lvCommonClusters.Items.Count > selectedIndex)
            {
                lvCommonClusters.Items[selectedIndex].Selected = true;
            }
        }
        private void LvCommonClusters_SelectedIndexChanged(object sender, EventArgs e)
        {
            curCommonCluster = null;
            if (lvCommonClusters.SelectedIndices.Count > 0)
            {
                int index = lvCommonClusters.SelectedIndices[0];
                curCommonCluster = (CommonCluster)lvCommonClusters.Items[index].Tag;
            }
            RefreshCards(curCommonCluster);
        }

        private void RefreshCards(CommonCluster curCommonCluster)
        {
            if (curCommonCluster != null)
            {
                txtAddress.Text = curCommonCluster.Address.ToString();
                txtEdges.Text = curCommonCluster.Edges;
                txtID.Text = curCommonCluster.ID.ToString();
                cmbOccupiedWay.SelectedIndex = curCommonCluster.OccupiedWay;
            }
            else
            {
                txtAddress.Text = "";
                txtEdges.Text = "";
                txtID.Text = "";
                cmbOccupiedWay.SelectedIndex = 0;
            }
        }

        private void BtnDelete_Click(object sender, EventArgs e)
        {
            if (lvCommonClusters.SelectedIndices.Count <= 0)
            {
                return;
            }
            int index = lvCommonClusters.SelectedIndices[0];
            curIndex = index <= curIndex ? index : curIndex;
            int tempID;
            if (int.TryParse(txtID.Text, out tempID))
            {
                try
                {
                    using (var session = _DataHelper.session)
                    {
                        session.Delete(curCommonCluster);
                        session.Flush();
                    }
                }
                catch
                {
                    MessageBox.Show("请区域编号是否存在！");
                }
                LoadFromTable(curIndex);
            }
        }

        private void BtnEdit_Click(object sender, EventArgs e)
        {
            if (!CheckInput())
            {
                return;
            }
            int tempID;
            int tempAddress;
            string tempEdges;
            int tempOccupiedWay;
            int.TryParse(txtID.Text, out tempID);
            int.TryParse(txtAddress.Text, out tempAddress);
            tempEdges = txtEdges.Text;
            tempOccupiedWay = cmbOccupiedWay.SelectedIndex;
            using (var session = _DataHelper.session)
            {
                var result = session.QueryOver<CommonCluster>().Where(p => p.ID == tempID).List();
                if(result.Count<=0)
                {
                    MessageBox.Show("请区域编号是否存在！");
                    return;
                }
                CommonCluster tempCluster = result.First();
                tempCluster.OccupiedWay = tempOccupiedWay;
                tempCluster.Edges = tempEdges;
                tempCluster.Address = tempAddress;
                session.Update(tempCluster);
                session.Flush();
            }
            LoadFromTable(curIndex);
        }

        private void BtnAdd_Click(object sender, EventArgs e)
        {
            if (!CheckInput())
            {
                return;
            }
            int tempID;
            int tempAddress;
            string tempEdges;
            int tempOccupiedWay;
            int.TryParse(txtID.Text, out tempID);
            int.TryParse(txtAddress.Text, out tempAddress);
            tempEdges = txtEdges.Text;
            tempOccupiedWay = cmbOccupiedWay.SelectedIndex;
            CommonCluster newCluster = new CommonCluster() { OccupiedWay = tempOccupiedWay, Edges = tempEdges, Address = tempAddress, ID = tempID };
            using (var session = _DataHelper.session)
            {
                var result = session.QueryOver<CommonCluster>().Where(p => p.ID == newCluster.ID).List();
                if (result.Count > 0)
                {
                    MessageBox.Show("请检查区域编号是否重复！");
                    return;
                }
                session.Save(newCluster);
                session.Flush();
            }
            LoadFromTable(curIndex);
        }

        bool CheckInput(CommonCluster curCommonCluster = null)
        {
            if (string.IsNullOrWhiteSpace(txtAddress.Text) || string.IsNullOrWhiteSpace(txtEdges.Text) || string.IsNullOrWhiteSpace(txtID.Text))
            {
                MessageBox.Show("输入项均不能为空！");
                return false;
            }
            char[] separator = new char[] { ',' };
            string tempEdges = txtEdges.Text.Trim();
            string[] strArr = tempEdges.Split(separator);
            foreach (var item in strArr)
            {
                int outUnt;
                if (!int.TryParse(item, out outUnt) || outUnt <= 0)
                {
                    MessageBox.Show("包含路段格式填写错误，只允许填写的内容为整数用逗号隔开,并且没一个整数值必须大于0！");
                    return false;
                }
            }
            int tempAddress;
            if (!int.TryParse(txtAddress.Text.Trim(), out tempAddress) || tempAddress < 0 || tempAddress >= 2000)
            {
                MessageBox.Show("错误的内存地址值！");
                return false;
            }

            int tempID;
            if (!int.TryParse(txtID.Text.Trim(), out tempID) || tempAddress <= 0)
            {
                MessageBox.Show("错误的区域编号！");
                return false;
            }
            return true;
        }
    }
}
