using ryCommon;
using ryCommonDb;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Itrycn_Project2.DbOp
{
    public partial class FrmView : RySkins.SKinForm
    {
        readonly string orderSQL = "order by addTime desc";
        readonly string tableName = "MainTable1";
        readonly string titleName = "数据";
        readonly DataProvider.DataProviderType dataType =DataProvider.DataProviderType.SQLiteDataProvider;
        readonly string SQLConnStr = Itrycn_Db.SQLConnStr;
        /// <summary>
        /// 是否启用选择模式
        /// </summary>
        public bool SelectedMode { get; set; } = false;
        /// <summary>
        /// 选择的信息
        /// </summary>
        public ViewInfo SelectedItem { get; set; }=null;
        public FrmView()
        {
            InitializeComponent();
            OlvName.AspectGetter = delegate (object x) { return ((ViewInfo)x).Name; };
            OlvAddTime.AspectGetter = delegate (object x) { return ((ViewInfo)x).AddTimeStr; };
        }
        #region 需要修改的内容
        private void RySearch1_OnSearch(object sender, EventArgs e)
        {
            //需要修改此处
            //LoadDb("(" + TableProject.name + " like @SearchText or " + TableProject.des + " like @SearchText)");
        }

        private void CtlMyPage1_OnPageChange(object sender, EventArgs e)
        {
            #region 重新载入数据
            LvCbResult.ClearObjects();
            IDbInterface db = DataProvider.CreateDataProvider(dataType);
            List<ViewInfo> list = new List<ViewInfo>();
            if (db.ConnDb(SQLConnStr) == 1)
            {
                DataSet ds = db.ReadData(ctlMyPage1.GetSQLText, ctlMyPage1.T_Parameters);
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow row = ds.Tables[0].Rows[i];
                    list.Add(new ViewInfo()
                    {
                        Id=row["id"].ToInt(),
                        Name = row["Name"].ToString(),
                        AddTime = row["AddTime"].ToInt64().ToDateTime()
                    }) ;
                }
            }
            db.Free();
            LvCbResult.AddObjects(list);
            #endregion
        }
        private void GetRow(int id, int index)
        {
            #region 重新载入数据
            IDbInterface db = DataProvider.CreateDataProvider(dataType);
            if (db.ConnDb(SQLConnStr) == 1)
            {
                DataSet ds = db.ReadData("select * from " + tableName + " where id=" + id);
                if (ds.HaveData())
                {
                    DataRow row = ds.Tables[0].Rows[0];
                    var item=(ViewInfo) LvCbResult.GetModelObject(index);
                    item.Name = row["Name"].ToString();
                    //添加剩余的项目
                    //添加完毕
                    LvCbResult.UpdateObject(item);
                }
            }
            db.Free();
            #endregion
        }
        #endregion
        public void LoadDb(string whereSQL)
        {
            string _whereSQL = whereSQL;
            IDbInterface db = DataProvider.CreateDataProvider(dataType);
            if (db.ConnDb(SQLConnStr) == 1)
            {
                #region 重新载入数据
                db.AddParameter("SearchText", "%" + rySearch1.Text + "%");
                ctlMyPage1.RecordCount = db.GetCount(tableName, _whereSQL);
                ctlMyPage1.T_Parameters = db.GetParameter();
                ctlMyPage1.SQLText= db.GetPageSQL(tableName, _whereSQL, orderSQL);
                ctlMyPage1.SQLText2 = db.GetPageSQL2(tableName, _whereSQL, orderSQL);
                ctlMyPage1.GotoPageIndex(1);
                #endregion
            }
            db.Free();
        }

        private void BtnAdd_Click(object sender, EventArgs e)
        {
            var frm = new FrmAdd()
            {
                Text = "添加"+ titleName,
                Icon = Icon,
                isAdd = 1,
                dataType = dataType,
                SQLConnStr = SQLConnStr,
            };
            frm.mr = new ModalForm(this, frm);
            frm.mr.OnDialogResult += new ModalForm.DialogResultHandler((object t, DialogResult dg) => {
                if (dg == DialogResult.OK)
                {
                    rySearch1.PerformClick();
                }
            });
            frm.mr.ShowModal();
        }

        private void BtnEdit_Click(object sender, EventArgs e)
        {
            if (LvCbResult.SelectedObject == null) { return; }
            var item = (ViewInfo)LvCbResult.SelectedObject;
            var selectId = item.Id;
            var frm = new FrmAdd()
            {
                Text = "修改"+ titleName,
                Icon = Icon,
                isAdd = 0,
                dataType = dataType,
                SQLConnStr = SQLConnStr,
            };
            frm.GetInfo(selectId.ToString());
            frm.mr = new ModalForm(this, frm);
            frm.mr.OnDialogResult += new ModalForm.DialogResultHandler((object t, DialogResult dg) => {
                if (dg == DialogResult.OK)
                {
                    GetRow(selectId, LvCbResult.SelectedIndex);
                }
            });
            frm.mr.ShowModal();
        }

        private void BtnDel_Click(object sender, EventArgs e)
        {
            if (LvCbResult.SelectedObject == null) { MessageBox.Show("请先选择要删除的项。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; }
            var item = (ViewInfo)LvCbResult.SelectedObject;
            var selectId = item.Id;
            if (RySkins.Msg.ShowMsg("确定要删除该项吗？一旦删除将不可恢复。", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
            {
                return;
            }
            IDbInterface db = DataProvider.CreateDataProvider(dataType);
            if (db.ConnDb(SQLConnStr) == 1)
            {
                db.DelById(tableName, selectId.ToString());
                LvCbResult.RemoveObject(item);
            }
        }

        private void FrmView_Load(object sender, EventArgs e)
        {
            Text = "浏览"+ titleName;
            添加数据ToolStripMenuItem.Text = "添加"+ titleName;
            修改数据ToolStripMenuItem.Text = "修改" + titleName;
            删除数据ToolStripMenuItem.Text = "删除" + titleName;
            rySearch1.PerformClick();
        }

        private void 添加数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnAdd.PerformClick();
        }

        private void 修改数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnEdit.PerformClick();
        }

        private void 删除数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnDel.PerformClick();
        }

        private void 复制并添加数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (LvCbResult.SelectedObject == null) { return; }
            var item = (ViewInfo)LvCbResult.SelectedObject;
            var selectId = item.Id;
            var frm = new FrmAdd()
            {
                Text = "添加" + titleName,
                Icon = Icon,
                isAdd = 1
            };
            frm.GetInfo(selectId.ToString());
            frm.mr = new ModalForm(this, frm);
            frm.mr.OnDialogResult += new ModalForm.DialogResultHandler((object t, DialogResult dg) => {
                if (dg == DialogResult.OK)
                {
                    rySearch1.PerformClick();
                }
            });
            frm.mr.ShowModal();
        }

        private void LvCbResult_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if(e.Button== MouseButtons.Left)
            {
                if(SelectedMode)
                {
                    SelectedItem = (ViewInfo)LvCbResult.SelectedObject;
                    DialogResult = DialogResult.OK;
                }
            }
        }
    }
    public class ViewInfo
    {
        /// <summary>
        /// id
        /// </summary>
        public int Id{ get; set; }
        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 添加时间
        /// </summary>
        public DateTime AddTime { get; set; }
        /// <summary>
        /// 添加时间字符串
        /// </summary>
        public string AddTimeStr
        {
            get { return AddTime.ToString("yyyy-MM-dd dddd HH:mm:ss"); }
        }
    }
}
