using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using GWSocketClient.model;
using GWSocketClient.util;
using Newtonsoft.Json;

namespace GWSocketClient.db
{
    public class AccsessDbLoader
    {
        private static AccsessDbLoader INSTANCE = null;

        private DataTable dataTable = new DataTable();
        private OleDbDataAdapter dataAdapter;

//        private List<WvBean> wvBeans = new List<WvBean>();
        private Dictionary<string, string> ID_INFO = new Dictionary<string, string>();

        public static AccsessDbLoader getInstance(string dbssPath = "")
        {
            return INSTANCE ?? (INSTANCE = new AccsessDbLoader(dbssPath));
        }

        public DataTable getDataTable()
        {
            return dataTable;
        }


        public OleDbDataAdapter getDataAdapter()
        {
            return dataAdapter;
        }

        public Dictionary<string, string> getUserIdInfo()
        {
            return ID_INFO;
        }

        /* public string getWebViewJson()
         {
             return JsonConvert.SerializeObject(wvBeans);
         }*/

        private AccsessDbLoader(string dbPath = "")
        {
            if (dbPath.Equals(""))
            {
                dbPath = Application.StartupPath + "/dbfile/ID_INFO.accdb;";
            }
            openConnection(dbPath);
            reloadAccessDb();
        }

        private static string strConnection = "Provider = Microsoft.ACE.OLEDB.12.0;Data Source = ";


        private OleDbConnection objConnection = null;

        private void openConnection(string dbPath)
        {
            strConnection += dbPath;
            objConnection = new OleDbConnection(strConnection);
            objConnection.Open();
        }

        public void closeConnection()
        {
            objConnection.Close();
        }

        public AccsessDbLoader reloadAccessDb(string sql = @"select * from fw")
        {
            Console.WriteLine(sql);
            try
            {
//                OleDbCommand sqlcmd = new OleDbCommand(@"select * from fw", objConnection);
                OleDbCommand sqlcmd = new OleDbCommand(sql, objConnection);

                dataAdapter = new OleDbDataAdapter(sqlcmd);
                dataTable.Clear();
                ID_INFO.Clear();
//                wvBeans.Clear();
                dataAdapter.Fill(dataTable);

                fillData(sqlcmd);
            }
            catch (OleDbException oe)
            {
                MessageBox.Show(oe.Message);
            }

            catch (Exception exception)
            {
                MyMessageBox.ShowMessageBox(exception.Message);
            }

            return this;
        }

        public AccsessDbLoader findDataByType(int mType, string query)
        {
            /*
            ID - 10进制
           ID - 16进制
           名字 - IDInfo
           描述 - Desp
           */
            string sql = "select * from fw ";

            switch (mType)
            {
                case 0:
                    sql += " where my_index = " + query;
                    break;
                case 1:
                    sql += " where MY_ID = '" + query + "'";
                    break;
                case 2:
                    sql += " where idInfo like '%" + query + "%'";
                    break;
                case 3:
                    sql += " where desp like '%" + query + "%'";
                    break;
                default:
                    return reloadAccessDb();
            }
            return reloadAccessDb(sql);
        }

        private void fillData(OleDbCommand sqlcmd)
        {
            using (OleDbDataReader reader = sqlcmd.ExecuteReader())
            {
                while (reader.Read()) //这个read调用很重要！不写的话运行时将提示找不到数据  
                {
                    WvBean wb = new WvBean();
                    int id = 0;
                    int index = 0;
                    string myId = "";
                    string idInfo = "";
                    string len = "";
                    string mode = "";
                    string desp = "";
                    string defalutValue = "";
                    string userValue = "";
                    string remark = "";
                    /*try
                    {*/
                    id = reader.GetInt32(0);
                    index = reader.GetInt32(1);
                    myId = reader.GetString(2);
                    idInfo = calcNull(reader.GetString(3));
                    len = calcNull(reader.GetString(4));
                    mode = calcNull(reader.GetString(5));
                    desp = calcNull(reader.GetString(6));
                    defalutValue = calcNull(reader.GetString(7));
                    userValue = calcNull(reader.GetString(8));
                    remark = calcNull(reader.GetString(9));
                    /* }
                     catch (Exception exception)
                     {
                     }*/

                    wb.id = id;
                    wb.index = index;
                    wb.myId = myId;
                    wb.idInfo = idInfo;
                    wb.len = len;
                    wb.mode = mode;
                    wb.desp = desp;
                    wb.defalutValue = defalutValue;
                    wb.userValue = userValue;
                    wb.remark = remark;

                    ID_INFO.Add(myId, userValue);

                    //                        wvBeans.Add(wb);
                }
            }
        }


        public int insert2Db(WvBean wb)
        {
            try
            {
                string sql =
                    "INSERT INTO fw(my_index,MY_ID,idInfo,len,mode,desp,default_value,user_value,remark) VALUES(";
                sql += wb.index + ",";
                sql += "'" + wb.myId + "',";
                sql += "'" + wb.idInfo + "',";
                sql += "'" + wb.len + "',";
                sql += "'" + wb.mode + "',";
                sql += "'" + wb.desp + "',";
                sql += "'" + wb.defalutValue + "',";
                sql += "'" + wb.userValue + "',";
                sql += "'" + wb.remark + "')";
//                Console.WriteLine(sql);
                OleDbCommand inst = new OleDbCommand(sql, objConnection);

                return inst.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            Console.WriteLine(wb.ToString());
            return -1;
        }

        public int delete4Db(int id)
        {
            string sql = "delete from fw where ID=" + id;
            OleDbCommand inst = new OleDbCommand(sql, objConnection);
            return inst.ExecuteNonQuery();
        }

        public int update2Db(WvBean wb)
        {
            /*string sql = "update fw set index=" + wb.index + ", MY_ID='" + wb.myId + "',idInfo='" + wb.idInfo +
                         "',len='" + wb.len +
                         "',mode='" +
                         wb.mode + "',desp='" + wb.desp + "',default_value='" + wb.defalutValue + "',user_value='" +
                         wb.userValue + "',remark='" + wb.remark + "' where ID=" + wb.id;*/

            string sql = "update fw set my_index=" + wb.index + ",MY_ID=\"" + wb.myId + "\",idInfo=\"" + wb.idInfo +
                         "\",len=\"" + wb.len +
                         "\",mode=\"" +
                         wb.mode + "\",desp=\"" + wb.desp + "\",default_value=\"" + wb.defalutValue +
                         "\",user_value=\"" +
                         wb.userValue + "\",remark=\"" + wb.remark + "\" where ID=" + wb.id;

            Console.WriteLine(sql);
            OleDbCommand inst = new OleDbCommand(sql, objConnection);

            return inst.ExecuteNonQuery();
        }

        public int resetUserData()
        {
            string sql = "update fw set user_value=default_value";
            Console.WriteLine(sql);
            OleDbCommand inst = new OleDbCommand(sql, objConnection);
            return inst.ExecuteNonQuery();
        }


        public int setReceiveData(string id, string value)
        {
            int idInt = Utils.hexToTen(id);
            string sql = "update fw set user_value=\"" + (value.Trim()) + "\" where my_index=" + idInt;
            Console.WriteLine(sql);
            OleDbCommand inst = new OleDbCommand(sql, objConnection);
            return inst.ExecuteNonQuery();
        }

        public int deleteAllData()
        {
            string sql = "delete from fw";
            Console.WriteLine(sql);
            OleDbCommand inst = new OleDbCommand(sql, objConnection);
            return inst.ExecuteNonQuery();
        }


        private string calcNull(string ojb)
        {
            if (ojb.Trim().Equals("") || ojb == null)
            {
                return "";
            }
            return ojb;
        }
    }
}