using Dapper;
using SolarPower.Helper;
using SolarPower.Models;
using SolarPower.Models.Company;
using SolarPower.Models.Role;
using SolarPower.Models.User;
using SolarPower.Repository.Interface;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;

namespace SolarPower.Repository.Implement
{
    public class CompanyRepository : RepositoryBase<Company>, ICompanyRepository
    {
        public CompanyRepository(IDatabaseHelper databaseHelper) : base(databaseHelper)
        {
            tableName = "company";
        }

        /// <summary>
        /// 取得下拉式公司選單，須為Deleted: 0
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public async Task<List<CompanySelectItemList>> GetCompanySelectOptionListAsync(int companyId = 0)
        {
            List<CompanySelectItemList> result;
            using (IDbConnection conn = this._databaseHelper.GetConnection())
            {
                try
                {
                    var sql = $"SELECT Id AS Value, Name AS Text FROM {tableName} WHERE Deleted = 0";

                    if (companyId > 0)
                    {
                        sql += " AND Id = @SelectedCompanyId";
                    }

                    result = (await conn.QueryAsync<CompanySelectItemList>(sql, new { SelectedCompanyId = companyId })).ToList();
                }
                catch (Exception exception)
                {
                    throw exception;
                }
                return result;
            }
        }

        /// <summary>
        /// 取得當前使用者所在的公司資訊
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public MyCompany GetMyCompanyInfoById(int id)
        {
            MyCompany result;
            using (IDbConnection conn = this._databaseHelper.GetConnection())
            {
                conn.Open();
                try
                {
                    var sql = $"SELECT * FROM {tableName} WHERE Deleted = 0 AND Status = @Status AND Id = @Id";

                    result = conn.QueryFirstOrDefault<MyCompany>(sql, new { Status = CompanyStatusEnum.Normal, Id = id });
                }
                catch (Exception exception)
                {
                    throw exception;
                }
                finally
                {
                    conn.Close();
                }
                return result;
            }
        }

        /// <summary>
        /// 透過搜尋條件，查詢過濾後的公司
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public async Task<List<CompanyDataTable>> GetAllByFilterAsync(PostCompanyFilter filter)
        {
            List<CompanyDataTable> result;
            using (IDbConnection conn = this._databaseHelper.GetConnection())
            {
                try
                {
                    var sql = @$"SELECT *, psc.SPStationAmount FROM {tableName} c
                                LEFT JOIN (SELECT ps.CompanyId, COUNT(*) AS SPStationAmount
                                            FROM power_station ps 
                                            WHERE ps.Deleted = 0 GROUP BY ps.CompanyId) psc ON psc.CompanyId = c.Id
                                WHERE c.Deleted = 0";

                    if (filter.SelectedCompanyId > 0)
                    {
                        sql += @" AND Id = @SelectedCompanyId";
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(filter.Name))
                        {
                            sql += @" AND Name LIKE CONCAT('%', @Name, '%')";
                        }

                        if (!string.IsNullOrEmpty(filter.Phone))
                        {
                            sql += @" AND Phone LIKE CONCAT('%', @Phone, '%')";
                        }

                        if (!string.IsNullOrEmpty(filter.TaxIDNumber))
                        {
                            sql += @" AND TaxIDNumber LIKE CONCAT('%', @TaxIDNumber, '%')";
                        }
                    }

                    result = (await conn.QueryAsync<CompanyDataTable>(sql, filter)).ToList();
                }
                catch (Exception exception)
                {
                    throw exception;
                }
                return result;
            }
        }

        /// <summary>
        /// 透過搜尋條件，查詢過濾後的公司
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public async Task<int> GetNormalUserNumberByCompanyIdAsync(int id)
        {
            int result = 0;
            using (IDbConnection conn = this._databaseHelper.GetConnection())
            {
                try
                {
                    var sql = $"SELECT COUNT(*) FROM user WHERE Deleted = 0 AND Status = @Status AND CompanyId = @CompanyId";

                    result = (await conn.QueryAsync<int>(sql, new { Status = CompanyStatusEnum.Normal, CompanyId = id })).FirstOrDefault();
                }
                catch (Exception exception)
                {
                    throw exception;
                }
                return result;
            }
        }

        /// <summary>
        /// 取得單一公司資料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Company> GetOneCompany(int id)
        {
            Company result;
            using (IDbConnection conn = this._databaseHelper.GetConnection())
            {
                conn.Open();
                try
                {
                    var sql = $"SELECT * FROM {tableName} WHERE deleted = 0 AND id = @Id";

                    result = await conn.QueryFirstOrDefaultAsync<Company>(sql, new { Id = id });
                }
                catch (Exception exception)
                {
                    throw exception;
                }
                finally
                {
                    conn.Close();
                }
                return result;
            }
        }

        /// <summary>
        /// 修改公司資料
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task UpdateCompany(UpdateCompany entity, List<string> properties)
        {

            using (IDbConnection conn = this._databaseHelper.GetConnection())
            {
                conn.Open();
                using (var trans = conn.BeginTransaction())
                {
                    try
                    {
                        var sql = GenerateUpdateQuery(properties);

                        await conn.ExecuteAsync(sql, entity, trans);

                        trans.Commit();
                    }
                    catch (Exception exception)
                    {
                        trans.Rollback();
                        throw exception;
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }

        /// <summary>
        /// 透過統編，取得單一公司基本資料
        /// </summary>
        /// <param name="taxIDNumber"></param>
        /// <returns></returns>
        public async Task<SimpleCompany> GetOneNormalSimpleCompanyByTaxIDNumber(string taxIDNumber)
        {
            SimpleCompany result;
            using (IDbConnection conn = this._databaseHelper.GetConnection())
            {
                conn.Open();
                try
                {
                    var sql = $"SELECT * FROM {tableName} WHERE Deleted = 0 AND TaxIDNumber = @TaxIDNumber";

                    result = await conn.QueryFirstOrDefaultAsync<SimpleCompany>(sql, new { TaxIDNumber = taxIDNumber });
                }
                catch (Exception exception)
                {
                    throw exception;
                }
                finally
                {
                    conn.Close();
                }
                return result;
            }
        }

        /// <summary>
        /// 透過公司編號，取得該公司的註冊人數
        /// </summary>
        /// <param name="companyId"></param>
        /// <returns></returns>
        public async Task<int> GetRegisterNumberByCompanyId(int companyId)
        {
            int result;
            using (IDbConnection conn = this._databaseHelper.GetConnection())
            {
                conn.Open();
                try
                {
                    var sql = $"SELECT COUNT(*) FROM user WHERE Deleted = 0 AND Status = @Status AND CompanyId = @CompanyId";

                    result = await conn.QueryFirstOrDefaultAsync<int>(sql, new { Status = UserStatusEnum.Normal, CompanyId = companyId });
                }
                catch (Exception exception)
                {
                    throw exception;
                }
                finally
                {
                    conn.Close();
                }
                return result;
            }
        }

        /// <summary>
        /// 透過公司編號，取得該公司的權限池
        /// </summary>
        /// <param name="companyId"></param>
        /// <returns></returns>
        public async Task<List<CompanyAuthDataTable>> GetCompanyAuthByCompanyId(int companyId)
        {
            List<CompanyAuthDataTable> result;
            using (IDbConnection conn = this._databaseHelper.GetConnection())
            {
                conn.Open();
                try
                {
                    var sql = @$"SELECT
                                    ap.*,
                                    CASE WHEN cap_id.CompanyId IS NOT NULL THEN 1 ELSE 0 END AS CheckAuth
                                    FROM auth_page ap
                                    LEFT JOIN (SELECT * FROM company_auth_page WHERE CompanyId = @CompanyId) cap_id ON ap.AuthCode = cap_id.AuthCode
                                ";

                    result = (await conn.QueryAsync<CompanyAuthDataTable>(sql, new { CompanyId = companyId })).ToList();
                }
                catch (Exception exception)
                {
                    throw exception;
                }
                finally
                {
                    conn.Close();
                }
                return result;
            }
        }

        /// <summary>
        /// 實際刪除公司權限池
        /// </summary>
        /// <param name="companyAuths"></param>
        /// <returns></returns>
        public async Task PurgeCompanyAuth(List<CompanyAuth> companyAuths)
        {
            using (IDbConnection conn = this._databaseHelper.GetConnection())
            {
                conn.Open();
                using (var trans = conn.BeginTransaction())
                {
                    try
                    {
                        var sql = $"DELETE FROM company_auth_page WHERE CompanyId = @CompanyId AND AuthCode = @AuthCode";

                        await conn.ExecuteAsync(sql, companyAuths, trans);

                        trans.Commit();
                    }
                    catch (Exception exception)
                    {
                        trans.Rollback();
                        throw exception;
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }

        /// <summary>
        /// 實際刪除公司權限池
        /// </summary>
        /// <param name="companyAuths"></param>
        /// <returns></returns>
        public async Task PurgeCompanyRoleAuth(int companyId, List<CompanyAuth> companyAuths)
        {
            using (IDbConnection conn = this._databaseHelper.GetConnection())
            {
                conn.Open();
                using (var trans = conn.BeginTransaction())
                {
                    try
                    {
                        //找出該公司底下有該權限的角色
                        var auths = companyAuths.Select(x => x.AuthCode).ToList();

                        var sqlRole = @$"SELECT ra.Id, ra.AuthCode FROM role_auth ra
                                        LEFT JOIN role r ON ra.Id = r.Id
                                        WHERE r.CompanyId = @CompanyId AND ra.AuthCode IN @AuthCode";

                        var roles = (await conn.QueryAsync<RoleAuth>(sqlRole, new { CompanyId = companyId, AuthCode = auths }, trans)).ToList();

                        var sql = $"DELETE FROM role_auth WHERE Id = @Id AND AuthCode = @AuthCode";

                        await conn.ExecuteAsync(sql, roles, trans);

                        trans.Commit();
                    }
                    catch (Exception exception)
                    {
                        trans.Rollback();
                        throw exception;
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }

        /// <summary>
        /// 新增公司權限池
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="properties"></param>
        /// <returns></returns>
        public async Task<int> AddCompanyAuthAsync(List<CompanyAuth> entity, List<string> properties)
        {
            int count;
            using (IDbConnection conn = _databaseHelper.GetConnection())
            {
                conn.Open();
                try
                {
                    string sql = $"INSERT INTO company_auth_page (CompanyId, AuthCode, CreatedBy) VALUES (@CompanyId, @AuthCode, @CreatedBy)";

                    count = await conn.ExecuteAsync(sql, entity);
                }
                catch (Exception exception)
                {
                    throw exception;
                }
                finally
                {
                    conn.Close();
                }

                return count;
            }
        }

        /// <summary>
        /// 創建公司自己的DB
        /// </summary>
        /// <param name="db_name"></param>
        /// <returns></returns>
        public async Task CreatCompanyDB(string db_name)
        {
            using (IDbConnection conn = this._databaseHelper.GetConnection())
            {
                conn.Open();
                using (var trans = conn.BeginTransaction())
                {
                    try
                    {
                        var sql = @$"
                                    -- 傾印 子資料庫結構
                                        CREATE DATABASE IF NOT EXISTS `{db_name}`;
                                        USE `{db_name}`;

                                    -- 傾印  資料表 controller 結構
                                    CREATE TABLE IF NOT EXISTS `controller` (
                                      `Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                                      `Deleted` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否刪除， 0:否 1:是',
                                      `PowerStationId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '所屬電站編號',
                                      `ControllerId` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '控制器編號',
                                      `SerialNumber` varchar(4) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '控制器各電站流水號',
                                      `CreatedBy` int(10) unsigned NOT NULL,
                                      `CreatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
                                      `UpdatedBy` int(10) unsigned DEFAULT NULL,
                                      `UpdatedAt` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
                                      PRIMARY KEY (`Id`)
                                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='控制器';

                                    -- 傾印  資料表 device 結構
                                    CREATE TABLE IF NOT EXISTS `device` (
                                      `Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                                      `Deleted` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否刪除， 0:否 1:是',
                                      `UID` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '設備編號，縣市 +區域+電廠流水號(0001~9999)+設備類別(字母：3碼) + SN(設備流水號；3碼)',
                                      `PowerStationId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '所屬電站編號',
                                      `Enabled` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否啟用， 0:否 1:是',
                                      `Status` tinyint(4) NOT NULL DEFAULT '0' COMMENT '狀態 ，0:未啟用 1:正常 2:異常',
                                      `SerialNumber` varchar(4) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT '0' COMMENT '設備流水號',
                                      `Name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '設備名稱',
                                      `Type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '類型',
                                      `TypeName` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '類型名稱',
                                      `ControllerId` int(10) unsigned DEFAULT NULL COMMENT '控制器Id',
                                      `Brand` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '廠牌',
                                      `ProductModel` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '型號',
                                      `DBName` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
                                      `TableName` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
                                      `ColName` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
                                      `InstallDate` timestamp NULL DEFAULT NULL COMMENT '安裝日期',
                                      `CreatedBy` int(10) unsigned NOT NULL COMMENT '建立者',
                                      `CreatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '建立時間',
                                      `UpdatedBy` int(10) unsigned DEFAULT NULL COMMENT '修改者',
                                      `UpdatedAt` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '修改時間',
                                      PRIMARY KEY (`Id`) USING BTREE,
                                      KEY `IDX_01` (`Deleted`) USING BTREE,
                                      KEY `IDX_02` (`UID`,`PowerStationId`)
                                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='裝置列表';

                                    -- 傾印  資料表 inverter 結構
                                    CREATE TABLE IF NOT EXISTS `inverter` (
                                      `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '流水號',
                                      `Deleted` tinyint(4) DEFAULT '0' COMMENT '是否刪除',
                                      `Enabled` tinyint(4) DEFAULT '0' COMMENT '是否啟用，0:未啟用 1:啟用',
                                      `Status` tinyint(4) DEFAULT '0' COMMENT '狀態，0:未啟用 1:正常 2:異常',
                                      `InstallDate` timestamp NULL DEFAULT NULL COMMENT '安裝日期',
                                      `SerialNumber` varchar(4) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '逆變器流水號(用控制器排序)',
                                      `InverterName` varchar(50) DEFAULT NULL COMMENT '逆變器名稱',
                                      `InverterId` varchar(50) DEFAULT NULL COMMENT '逆變器UID',
                                      `ControllerId` int(10) DEFAULT NULL COMMENT '所屬控制器',
                                      `Brand` varchar(50) DEFAULT NULL COMMENT '廠牌',
                                      `Model` varchar(50) DEFAULT NULL COMMENT '型號',
                                      `Capacity` double(10,3) DEFAULT NULL COMMENT '裝置容量 kWp',
                                      `Pyrheliometer` int(10) DEFAULT NULL COMMENT '日照計設備流水號',
                                      `CreatedBy` int(10) unsigned NOT NULL,
                                      `CreatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
                                      `UpdatedBy` int(10) DEFAULT NULL,
                                      `UpdatedAt` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
                                      PRIMARY KEY (`Id`)
                                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='逆變器';

                                    -- 傾印  資料表 land_building 結構
                                    CREATE TABLE IF NOT EXISTS `land_building` (
                                      `Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                                      `Deleted` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否刪除， 0:否 1:是',
                                      `PowerStationId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '所屬電站編號',
                                      `Address` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '地址',
                                      `LeaseNotarizationAt` timestamp NULL DEFAULT NULL COMMENT '租約公證日期',
                                      `Landowner` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '地主姓名',
                                      `Purpose` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '房屋用途',
                                      `LeaseRate` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '租金比例(%)',
                                      `Coordinate` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '座標',
                                      `Phone` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '電話',
                                      `CreatedBy` int(10) unsigned NOT NULL COMMENT '建立者',
                                      `CreatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '建立時間',
                                      `UpdatedBy` int(10) unsigned DEFAULT NULL COMMENT '修改者',
                                      `UpdatedAt` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '修改時間',
                                      PRIMARY KEY (`Id`),
                                      KEY `IDX_01` (`Deleted`,`PowerStationId`)
                                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='土地與房屋';

                                    -- 傾印  資料表 operation_firm 結構
                                    CREATE TABLE IF NOT EXISTS `operation_firm` (
                                      `Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                                      `Deleted` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否刪除， 0:否 1:是',
                                      `PowerStationId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '所屬電站編號',
                                      `Name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '名稱',
                                      `Type` tinyint(4) NOT NULL DEFAULT '0' COMMENT '廠商類別，0:施工 1:清洗 2:運維',
                                      `ContactPerson` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '聯絡人',
                                      `Phone` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '電話',
                                      `Email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT 'Email',
                                      `CreatedBy` int(10) unsigned NOT NULL COMMENT '建立者',
                                      `CreatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '建立時間',
                                      `UpdatedBy` int(10) unsigned DEFAULT NULL COMMENT '修改者',
                                      `UpdatedAt` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '修改時間',
                                      PRIMARY KEY (`Id`),
                                      KEY `IDX_01` (`Deleted`,`PowerStationId`)
                                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='運維廠商';

                                    -- 傾印  資料表 power_station 結構
                                    CREATE TABLE IF NOT EXISTS `power_station` (
                                        `Id` int(10) unsigned NOT NULL DEFAULT '0',
                                        `Deleted` TINYINT(4) NOT NULL DEFAULT '0' COMMENT '是否刪除， 0:否 1:是',
                                        `CompanyId` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '公司編號',
                                        `CityId` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '電站縣市',
                                        `AreaId` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '電站區域',
                                        `HealthStatus` TINYINT(4) UNSIGNED NOT NULL DEFAULT '1' COMMENT '1:設備正常 2:設備斷線 3:設備異常',
                                        `Address` VARCHAR(100) NULL DEFAULT NULL COMMENT '電站詳細地址' COLLATE 'utf8mb4_unicode_ci',
                                        `Name` VARCHAR(50) NULL DEFAULT NULL COMMENT '名稱' COLLATE 'utf8mb4_unicode_ci',
                                        `MainDisplay` VARCHAR(50) NULL DEFAULT NULL COMMENT '主要顯示圖片' COLLATE 'utf8mb4_unicode_ci',
                                        `Code` VARCHAR(50) NULL DEFAULT NULL COMMENT '電站代碼，縣市+區域+四碼流水號' COLLATE 'utf8mb4_unicode_ci',
                                        `SerialNumber` VARCHAR(4) NULL DEFAULT NULL COMMENT '四碼流水號' COLLATE 'utf8mb4_unicode_ci',
                                        `IsEscrow` TINYINT(4) NOT NULL DEFAULT '0' COMMENT '是否為代管，0:否 1:是',
                                        `EscrowName` VARCHAR(50) NULL DEFAULT NULL COMMENT '代管名稱' COLLATE 'utf8mb4_unicode_ci',
                                        `ElectricityMeterAt` TIMESTAMP NULL DEFAULT NULL COMMENT '台電掛錶日',
                                        `EstimatedRecoveryTime` VARCHAR(10) NULL DEFAULT NULL COMMENT '預估回收時間' COLLATE 'utf8mb4_unicode_ci',
                                        `GeneratingCapacity` DECIMAL(10,1) NOT NULL DEFAULT '0.0' COMMENT '電廠發電容量，單位(千瓦)',
                                        `PowerRate` DECIMAL(10,3) NOT NULL DEFAULT '0.000' COMMENT '受電費率',
                                        `Coordinate` VARCHAR(50) NULL DEFAULT NULL COMMENT '座標' COLLATE 'utf8mb4_unicode_ci',
                                        `InverterBrand` VARCHAR(50) NULL DEFAULT NULL COMMENT '逆變器廠牌' COLLATE 'utf8mb4_unicode_ci',
                                        `InverterProductModel` VARCHAR(50) NULL DEFAULT NULL COMMENT '逆變器型號' COLLATE 'utf8mb4_unicode_ci',
                                        `InverterAmount` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '逆變器數量',
                                        `PhotovoltaicPanelBrand` VARCHAR(50) NULL DEFAULT NULL COMMENT '光電板廠牌' COLLATE 'utf8mb4_unicode_ci',
                                        `PhotovoltaicPanelProductModel` VARCHAR(50) NULL DEFAULT NULL COMMENT '光電板型號' COLLATE 'utf8mb4_unicode_ci',
                                        `PhotovoltaicPanelSpecification` VARCHAR(100) NULL DEFAULT NULL COMMENT '光電板規格' COLLATE 'utf8mb4_unicode_ci',
                                        `PhotovoltaicPanelAmount` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '光電板數量',
                                        `BoEFileName` VARCHAR(255) NULL DEFAULT NULL COMMENT '能源局原檔案名' COLLATE 'utf8mb4_unicode_ci',
                                        `BoEFile` VARCHAR(255) NULL DEFAULT NULL COMMENT '能源局檔案' COLLATE 'utf8mb4_unicode_ci',
                                        `BoEDiscountRate` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '能源局折扣率',
                                        `BoEDeviceRegisterNumber` VARCHAR(50) NULL DEFAULT NULL COMMENT '能源局設備登記編號' COLLATE 'utf8mb4_unicode_ci',
                                        `BoERentRatio` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '能源局租金比率，單位(%)',
                                        `TPCContractNumber` VARCHAR(50) NULL DEFAULT NULL COMMENT '台電契約編號' COLLATE 'utf8mb4_unicode_ci',
                                        `TPCContractAt` TIMESTAMP NULL DEFAULT NULL COMMENT '台電簽約日期',
                                        `TPCSellDeadline` INT(10) UNSIGNED NULL DEFAULT '0' COMMENT '台電售電期限，單位(年)',
                                        `TPCMeterReading` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '台電每期抄錶日',
                                        `TPCPurchaseElectricityAt` TIMESTAMP NULL DEFAULT NULL COMMENT '台電正式購電日',
                                        `TPCSellElectricityAt` TIMESTAMP NULL DEFAULT NULL COMMENT '台電正式售電日',
                                        `SolarType` TINYINT(4) NOT NULL DEFAULT '0' COMMENT '電站類型',
                                        `kwh` DECIMAL(10,3) UNSIGNED NOT NULL DEFAULT '0.000',
                                        `Today_kwh` DECIMAL(10,3) UNSIGNED NOT NULL DEFAULT '0.000' COMMENT '今日發電量',
                                        `Total_kwh` DECIMAL(10,3) UNSIGNED NOT NULL DEFAULT '0.000' COMMENT '總發電量',
                                        `today_kwhkwp` DECIMAL(10,3) NULL DEFAULT NULL COMMENT '今日kwhkwp',
                                        `avg_kwhkwp` DECIMAL(10,3) NULL DEFAULT NULL COMMENT '30天平均kwhkwp',
                                        `today_money` DECIMAL(10,2) NULL DEFAULT NULL COMMENT '今日金額',
                                        `total_money` DECIMAL(10,2) NULL DEFAULT NULL COMMENT '總金額',
                                        `today_PR` DECIMAL(5,2) NULL DEFAULT NULL COMMENT '電站Pr值',
                                        `avg_PR` DECIMAL(5,2) NULL DEFAULT NULL COMMENT '平均Pr值',
                                        `today_carbon` DECIMAL(10,2) NULL DEFAULT NULL COMMENT '今日減碳量',
                                        `total_carbon` DECIMAL(10,2) NULL DEFAULT NULL COMMENT '總減碳量',
                                        `today_irradiance` DECIMAL(5,2) NULL DEFAULT NULL COMMENT '今日日照度',
                                        `avg_irradiance` DECIMAL(5,2) NULL DEFAULT NULL COMMENT '平均日照度',
                                        `SolarHour` DECIMAL(5,2) UNSIGNED NOT NULL DEFAULT '0.00' COMMENT '總運轉小時',
                                        `SiteDB` VARCHAR(20) NULL DEFAULT NULL COMMENT '電站 DB name: solar_com' COLLATE 'utf8mb4_unicode_ci',
                                        `TodayWeather` VARCHAR(20) NULL DEFAULT NULL COMMENT '今日天氣' COLLATE 'utf8mb4_unicode_ci',
                                        `TodayWeatherTemp` DECIMAL(5,2) UNSIGNED NOT NULL DEFAULT '0.00' COMMENT '今日溫度',
                                        `CreatedBy` INT(10) UNSIGNED NOT NULL COMMENT '建立者',
                                        `CreatedAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '建立時間',
                                        `UpdatedBy` INT(10) UNSIGNED NULL DEFAULT NULL COMMENT '修改者',
                                        `UpdatedAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改時間',
                                        PRIMARY KEY (`Id`),
                                        KEY `IDX_01` (`Deleted`),
                                        KEY `IDX_02` (`CompanyId`),
                                        KEY `IDX_03` (`CityId`,`AreaId`)
                                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='電站資料';

                                    -- 傾印  資料表 power_station_exception 結構
                                    CREATE TABLE IF NOT EXISTS `power_station_exception` (
                                      `Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                                      `Deleted` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否刪除， 0:否 1:是',
                                      `PowerStationId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '電站編號',
                                      `Type` tinyint(4) NOT NULL DEFAULT '0' COMMENT '類型，0:PR值',
                                      `UpperLimit` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '上限值',
                                      `LowerLimit` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '下限值',
                                      `Alarm` tinyint(4) NOT NULL DEFAULT '0' COMMENT '警報方式，0:email通知',
                                      `CreatedBy` int(10) unsigned NOT NULL COMMENT '建立者',
                                      `CreatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '建立時間',
                                      `UpdatedBy` int(10) unsigned DEFAULT NULL COMMENT '修改者',
                                      `UpdatedAt` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '修改時間',
                                      PRIMARY KEY (`Id`),
                                      KEY `IDX_01` (`Deleted`,`PowerStationId`)
                                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='電站異常值設定';

                                    -- 傾印  資料表 power_station_image 結構
                                    CREATE TABLE IF NOT EXISTS `power_station_image` (
                                      `Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                                      `Deleted` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否刪除， 0:否 1:是',
                                      `PowerStationId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '電站編號',
                                      `IsMainDisplay` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否主要顯示圖片， 0:否 1:是',
                                      `Image` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '圖片檔名',
                                      `CreatedBy` int(10) unsigned NOT NULL COMMENT '建立者',
                                      `CreatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '建立時間',
                                      `UpdatedBy` int(10) unsigned DEFAULT NULL COMMENT '修改者',
                                      `UpdatedAt` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '修改時間',
                                      PRIMARY KEY (`Id`),
                                      KEY `IDX_01` (`Deleted`,`IsMainDisplay`,`PowerStationId`) USING BTREE
                                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='電站資料';

                                    -- 傾印  資料表 power_station_single_line_diagram 結構
                                    CREATE TABLE IF NOT EXISTS `power_station_single_line_diagram` (
                                      `Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                                      `Deleted` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否刪除， 0:否 1:是',
                                      `PowerStationId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '電站編號',
                                      `Image` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '圖片檔名',
                                      `CreatedBy` int(10) unsigned NOT NULL COMMENT '建立者',
                                      `CreatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '建立時間',
                                      PRIMARY KEY (`Id`),
                                      KEY `IDX_01` (`Deleted`,`PowerStationId`) USING BTREE
                                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='電站單線圖';

                                    -- 傾印  資料表 sharedevice 結構
                                    CREATE TABLE IF NOT EXISTS `sharedevice` (
                                      `Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                                      `PowerStationId` int(10) DEFAULT NULL COMMENT '自己的電站編號',
                                      `DeviceId` int(10) DEFAULT NULL COMMENT '共用其他電站的設備',
                                      `CreatedBy` int(10) unsigned NOT NULL,
                                      `CreatedAt` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
                                      PRIMARY KEY (`Id`)
                                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='共享設備';
                        ";

                        await conn.ExecuteAsync(sql, trans);

                        trans.Commit();
                    }
                    catch (Exception exception)
                    {
                        trans.Rollback();
                        throw exception;
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }
    }
}
