using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid;
using Uninpho.DBOperation.Model;
using Uninpho.DBOperation.Operation;
using Uninpho.Tools.components.MTLFF;
using System.IO;
using System.Reflection;

namespace Uninpho.Tools.components
{
    public partial class JHjgjFrom : DevExpress.XtraEditors.XtraForm
    {
        bool gsEdit = false;
        bool dsEdit = false;
        List<T_jgjdistance_table> GSnew = new List<T_jgjdistance_table>();//存储还没有值的空白行
        List<T_jgjdistance_table> DSnew = new List<T_jgjdistance_table>();//存储还没有值的空白行

        List<T_jgjdistance_table> GSedit = new List<T_jgjdistance_table>();//已有数据修改过的条目
        List<T_jgjdistance_table> DSedit = new List<T_jgjdistance_table>();//已有数据修改过的条目

        List<T_jgjdistance_table> tablelist = new List<T_jgjdistance_table>();//全部数据
        List<T_jgjdistance_table> GS = new List<T_jgjdistance_table>();//高速 展示数据
        List<T_jgjdistance_table> DS = new List<T_jgjdistance_table>();//普速 展示数据

        public JHjgjFrom()
        {
            InitializeComponent();
        }

        private void bandedGridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            DataAnalysis.DACommon.addXuHao(e);
        }

        private void JHjgjFrom_Load(object sender, EventArgs e)
        {
            tablelist = DataAnalysisToPG.QueryJGJXGJJ();
            GS = tablelist.Where(i => i.Sudutype == 0).ToList();
            DS = tablelist.Where(i => i.Sudutype == 1).ToList();
            initShow(GSgridControl, GS, GSnew);
            initShow(DSgridControl, DS, DSnew);
        }

        private void initShow(GridControl GC, List<T_jgjdistance_table> data, List<T_jgjdistance_table> datanew)
        {
            var dataSource = data.Concat(datanew).ToList<T_jgjdistance_table>();
            GC.DataSource = dataSource;
        }
        /// <summary>
        /// 删除
        /// </summary>
        private void DelBtn_Click(object sender, EventArgs e)
        {
            if (UserInform.userinf.Pow == 0)
            {
                XtraMessageBox.Show("您无权删除数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {        
                    if (XtraMessageBox.Show("是否删除所选?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    if (DSTabControl.SelectedTabPageIndex == 0)
                    {
                        if (!GSgridView.OptionsBehavior.Editable)
                        {
                            XtraMessageBox.Show("请先启用编辑模式!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            //高速
                            delData(GSgridView, GSgridView.GetSelectedRows(), ref GS, ref GSnew);
                            XtraMessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else
                    {
                        if (!GSgridView.OptionsBehavior.Editable)
                        {
                            XtraMessageBox.Show("请先启用编辑模式!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            //普速
                            delData(DSgridView, DSgridView.GetSelectedRows(), ref DS, ref DSnew);
                            XtraMessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="GV"></param>
        /// <param name="row"></param>
        private void delData(GridView GV, int[] row,ref List<T_jgjdistance_table> data, ref List<T_jgjdistance_table> datanew)
        {
            for (int i = row.Length - 1; i >= 0; i--)
            {
                var va1 = GV.GetRowCellValue(row[i], "Id").ToString();
                try
                {
                    var aa = data.Where(it => it.Id == va1).Single();
                    data.Remove(aa);
                }
                catch
                {
                }
                try
                {
                    var aa = data.Where(it => it.Id == va1).Single();

                    datanew.Remove(aa);
                }
                catch
                {
                }
                DataAnalysisToPG.DelJGJXGJJ(va1);
                GV.DeleteRow(row[i]);
            }
        }

        /// <summary>
        /// 新增
        /// </summary>
        private void AddBtn_Click(object sender, EventArgs e)
        {
            if (DSTabControl.SelectedTabPageIndex == 0)
            {
                //高速
                AddData(GSgridControl, GSgridView, ref GS, ref GSnew, 0);
            }
            else
            {
                //普速
                AddData(DSgridControl, DSgridView, ref DS, ref DSnew, 1);
            }
        }

        private void AddData(GridControl GC, GridView GV, ref List<T_jgjdistance_table> listshow, ref List<T_jgjdistance_table> list, int type)
        {
            if (!GV.OptionsBehavior.Editable)
            {
                XtraMessageBox.Show("请先启用编辑模式!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            else
            {
                //1、先在数据库创一个空白的条
                T_jgjdistance_table da = new T_jgjdistance_table() { Sudutype = type };
                DataAnalysisToPG.InsertJGJXGJJ(da);
                //2、修改isnew属性为no
                tablelist = DataAnalysisToPG.QueryJGJXGJJ();
                T_jgjdistance_table dataa = tablelist.Where(i => i.Isnew == null && i.Sudutype == type).Single();
                DataAnalysisToPG.UpdataJGJXGJJ(true, dataa);
                //3、更新DataScoure
                dataa.Isnew = "no";
                list.Add(dataa);
                //4、更新显示
                initShow(GC, listshow, list);
                //5、聚焦最后一行
                GV.SelectRow(listshow.Count + list.Count - 1);
                GV.FocusedRowHandle = listshow.Count - 1;
            }
        }

        /// <summary>
        /// 编辑
        /// </summary>
        private void EditBtn_Click(object sender, EventArgs e)
        {
            if (DSTabControl.SelectedTabPageIndex == 0)
            {
                //高速
                EditData(GSgridView, ref gsEdit);
            }
            else
            {
                //普速
                EditData(DSgridView, ref dsEdit);
            }
        }

        private void EditData(GridView GV, ref bool Editbool)
        {
            if (!GV.OptionsBehavior.Editable)
            {
                if (UserInform.userinf.Pow == 0)
                {
                    XtraMessageBox.Show("您没有权限执行编辑操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    Editbool = true;
                    GV.OptionsBehavior.Editable = true;
                    EditBtn.Text = "结束编辑";
                    XtraMessageBox.Show("已启用编辑!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                Editbool = false;
                GV.OptionsBehavior.Editable = false;
                EditBtn.Text = "编辑";
                XtraMessageBox.Show("已结束编辑!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// tab切换,btn显示切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DSTabControl_SelectedPageChanging(object sender, DevExpress.XtraTab.TabPageChangingEventArgs e)
        {
            if (e.Page.Text == "高速")
            {
                selectPageBtn(GSgridView, gsEdit);
            }
            else
            {
                selectPageBtn(DSgridView, dsEdit);
            }
        }

        private void selectPageBtn(GridView GV, bool Editbool)
        {
            if (Editbool)
            {
                GV.OptionsBehavior.Editable = true;
                EditBtn.Text = "结束编辑";
            }
            else
            {
                GV.OptionsBehavior.Editable = false;
                EditBtn.Text = "编辑";
            }
        }

        private async void GSgridView_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            await Task.Run(() =>
            {
                if (DSTabControl.SelectedTabPageIndex == 0)
                {
                    //高速
                    CellDataChange(GSgridView, e, ref GSnew, ref GSedit, ref GS, 0);
                }
                else
                {
                    //普速
                    CellDataChange(DSgridView, e, ref DSnew, ref DSedit, ref DS, 1);
                }
            });
        }

        private void CellDataChange(GridView GV, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e, ref List<T_jgjdistance_table> updatalist, ref List<T_jgjdistance_table> updatalistold, ref List<T_jgjdistance_table> updatalistall, int sudutype)
        {
            //收集变化的值      
            string nana = GV.FocusedColumn.FieldName;
            string Caption = GV.FocusedColumn.Caption;
            string val = GV.GetRowCellValue(e.RowHandle, nana).ToString();
            string uuid = GV.GetRowCellValue(e.RowHandle, "Id").ToString();
            string typ = GV.GetRowCellValue(e.RowHandle, "Isnew").ToString();
            if (typ == "no")
            {
                //新行
                loopProp(ref updatalist, uuid, val, nana);
            }
            else if (typ == "yes")
            {
                int isis = 0;
                try
                {
                    updatalistold.Where(i => i.Id == uuid).Single();
                }
                catch
                {
                    isis = 1;
                }
                var ishave = tablelist.Where(i => i.Id == uuid && i.Sudutype == sudutype).Single();
                //旧行修改
                if (updatalistold.Count == 0 || isis == 1)
                {
                    updatalistold.Add(new T_jgjdistance_table() { Id = uuid, Isnew = typ, Zch = ishave.Zch, Dcqc = ishave.Dcqc, Gdjxgjj = ishave.Gdjxgjj, Sudutype = sudutype });
                }
                loopProp(ref updatalistold, uuid, val, nana);
                loopProp(ref updatalistall, uuid, val, nana);
            }
        }

        private void loopProp(ref List<T_jgjdistance_table> updatalist,string uuid,string value,string nana)
        {
            for (int i = 0; i < updatalist.Count; i++)
            {
                if (updatalist[i].Id == uuid)
                {
                    Type t = updatalist[i].GetType();//获得该类的Type
                    foreach (PropertyInfo pi in t.GetProperties())
                    {
                        if (pi.Name == nana)
                        {
                            pi.SetValue(updatalist[i], Convert.ToDecimal(value));
                        }
                    }
                }
            }
        }


        private void JHjgjFrom_FormClosed(object sender, FormClosedEventArgs e)
        {
            DataAnalysisToPG.ClearCacheJGJXGJJ();
        }

        private void SaveBtn_Click(object sender, EventArgs e)
        {
            //保存
            if (DSTabControl.SelectedTabPageIndex == 0)
            {
                //高速
                saveData(0, ref GSnew, ref GSedit, ref GS, GSgridControl);
            }
            else
            {
                //普速
                saveData(1, ref DSnew, ref DSedit, ref DS, DSgridControl);
            }


        }

        private void saveData(int type,ref List<T_jgjdistance_table> data ,ref List<T_jgjdistance_table> data1, ref List<T_jgjdistance_table> alldata, GridControl GC)
        {
            foreach (var item in data.Concat(data1).ToList())
            {
                DataAnalysisToPG.UpdataJGJXGJJ(false, item);
            }
            //清除临时数据
            DataAnalysisToPG.ClearCacheJGJXGJJ();
            data.Clear();
            data1.Clear();
            //更新显示
            tablelist = DataAnalysisToPG.QueryJGJXGJJ();
            alldata = tablelist.Where(i => i.Sudutype == type).ToList();
            initShow(GC, alldata, data);
            XtraMessageBox.Show("保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        ///// <summary>
        ///// 添加txt数据
        ///// </summary>
        //private void sendData()
        //{
        //    OpenFileDialog opf = new OpenFileDialog();
        //    opf.Multiselect = true;
        //    if (opf.ShowDialog() == DialogResult.OK)
        //    {
        //        foreach (var item in opf.FileNames)
        //        {
        //            seadtxt(item);
        //        }

        //    }
        //}

        //public void seadtxt(string txtPath)
        //{
        //    int type = Path.GetFileNameWithoutExtension(txtPath) == "高速" ? 0: 1;
        //    StreamReader SR = new StreamReader(txtPath);
        //    while (!SR.EndOfStream)
        //    {
        //        string[] str = SR.ReadLine().Replace(" ", "\t").Split('\t');

        //                T_jgjdistance_table data = new T_jgjdistance_table();
        //                data.Zch = Convert.ToDecimal(str[0].Trim());
        //                data.Dcqc = Convert.ToDecimal(str[1].Trim());
        //                data.Gdjxgjj = Convert.ToDecimal(str[2].Trim());
        //                data.Sudutype = type;
        //                DataAnalysisToPG.InsertJGJXGJJ(data);

        //    }
        //}
    }
}