using Dapper;
using MySql.Data.MySqlClient;
using Siger.Middlelayer.Common.Configuration;
using Siger.Middlelayer.Redis;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;

namespace Siger.Middlelayer.Dapper
{
    public class InitDbConfig
    {

        string GetConnectStr()
        {
            string _dbConnection;

            var useOneDb = ConfigManager.GetValue("DbSetting", "UseOneDb", true);
            if (useOneDb)
            {
                _dbConnection = ConfigManager.GetValue("DbSetting", "DbConnectionKM", string.Empty);
            }
            else
            {
                _dbConnection = ConfigManager.GetValue("DbClusterSetting", "ClusterConnectionKM", string.Empty);
            }
            if (string.IsNullOrEmpty(_dbConnection))
            {
                throw new Exception("DbSetting about [ConnectionKM] not found.");
            }
            return _dbConnection;
        }

        public IDbConnection GetCustomDbConnection(int companyId, int projectId)
        {
            try
            {
                var connecctionStr = $"{GetConnectStr()};database={string.Format("{0}_{1}", companyId, projectId)}";

                var connect = new MySqlConnection(connecctionStr);
                connect.Open();
                return connect;
            }
            catch (Exception e)
            {
                throw new Exception($"connect mysql db {companyId}_{projectId} failed, error:" + e);
            }
        }

        public IDbConnection GetBaseDbConnection()
        {
            try
            {
                string _dbConnection = GetConnectStr();

                var connect = new MySqlConnection(_dbConnection);
                connect.Open();
                return connect;
            }
            catch (Exception e)
            {
                throw new Exception($"connect mysql BaseDb failed, error:" + e);
            }
        }

        public bool InitDb(int companyId, int projectId)
        {
            //todo:规划后规则创库
            var createDbSql = $"create database {companyId}_{projectId};";
            var conn = GetBaseDbConnection();
            var ret = conn.Execute(createDbSql);
            return ret > 0;
        }

        public bool InitTable(int companyId, int projectId)
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CreateSql", "Cid_Pid.sql");
            if (File.Exists(path))
            {

                var sql = File.ReadAllText(path);
                var conn = GetCustomDbConnection(companyId, projectId);
                var ret = conn.Execute(sql);
                return ret > 0;
            }
            else
            {
                throw new Exception("建表文件不存在!");
            }
        }

    }
}
