using Repository.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Repository.BaseRepository.Interface;
using System.Data;
using Dapper;
using System.Text;

namespace Repository.Services.Implement
{
    /// <summary>
    /// 資料派送Service
    /// </summary>
    public class BackgroundService
    {
        private readonly IDbConnection conn;
        private readonly IDbTransaction trans;
        private List<string> mode_list = new List<string>() { "insert", "insert_list", "update", "update_list", "delete", "purge_specify_insert", "purge_all_insert", "purge" };
        public BackgroundService(IDbConnection conn, IDbTransaction trans)
        {
            this.conn = conn;
            this.trans = trans;
        }

        public string InsertGenerateString(List<string> properties, string table_name)
        {
            var insertQuery = new StringBuilder($"INSERT INTO {table_name} ");

            insertQuery.Append("(");

            properties.ForEach(prop => { insertQuery.Append($"{table_name}.{prop.Replace("@", "")},"); });

            insertQuery
                .Remove(insertQuery.Length - 1, 1)
                .Append(") VALUES (");

            properties.ForEach(prop => { insertQuery.Append($"{prop},"); });

            insertQuery
                .Remove(insertQuery.Length - 1, 1)
                .Append(");");

            return insertQuery.ToString();
        }
        public string UpdateGenerateString(List<string> properties, string table_name, string sWhere)
        {
            var updateQuery = new StringBuilder($"UPDATE {table_name} SET ");

            properties.ForEach(property =>
            {
                if (property.Contains("@"))
                {
                    updateQuery.Append($"{property.Replace("@", "")}={property},");
                }
            });

            updateQuery.Remove(updateQuery.Length - 1, 1); //remove last comma
            updateQuery.Append($" WHERE {sWhere}");

            return updateQuery.ToString();
        }

        /// <summary>
        /// 加入至背景執行任務(單筆情況)
        /// </summary>
        /// <param name="building_ip"></param>
        /// <param name="building_guid"></param>
        /// <param name="target_table"></param>
        /// <param name="mode"></param>
        /// <param name="parameter"></param>
        /// <param name="fileInfos"></param>
        /// <returns></returns>
        public async Task AddTask(string building_ip, string building_guid, string target_table, string mode, Dictionary<string, object> parameter, List<Models.FileInfo> fileInfos = null, string data_guid = "")
        {
            List<string> temp_ips = new List<string>();
            temp_ips = await GetBuilgingIPs(building_ip, building_guid);

            if (temp_ips != null && temp_ips.Count > 0)
            {
                foreach (var temp_ip in temp_ips)
                {
                    if (!string.IsNullOrEmpty(temp_ip) && !string.IsNullOrEmpty(target_table) && mode_list.Contains(mode.ToLower()))
                    {
                        Dictionary<string, object> backgroundServiceTaskDic = new Dictionary<string, object>()
                        {
                            { "@task_type", 1},
                            { "@target_ip", temp_ip},
                            { "@target_table", target_table},
                            { "@mode", mode.ToLower()},
                            { "@repeat_times", 0},
                            { "@is_complete", 0},
                        };

                        if (parameter != null)
                        {
                            var data_json = JsonSerializer.Serialize(parameter);
                            if (!string.IsNullOrEmpty(data_json))
                            {
                                backgroundServiceTaskDic.Add("@target_data", data_json);
                            }
                        }

                        if (fileInfos != null && fileInfos.Count > 0)
                        {
                            var file_json = JsonSerializer.Serialize(fileInfos);
                            if (!string.IsNullOrEmpty(file_json))
                            {
                                backgroundServiceTaskDic.Add("@target_files", file_json);
                            }
                        }

                        List<string> properties = backgroundServiceTaskDic.Keys.ToList();
                        string sql = InsertGenerateString(properties, "background_service_task");
                        await conn.ExecuteAsync(sql, backgroundServiceTaskDic, trans);
                    }
                }
            }
        }

        /// <summary>
        /// 加入至背景執行任務(多筆情況)
        /// </summary>
        /// <param name="building_ip"></param>
        /// <param name="building_guid"></param>
        /// <param name="target_table"></param>
        /// <param name="mode"></param>
        /// <param name="parameter"></param>
        /// <param name="fileInfos"></param>
        /// <returns></returns>
        public async Task AddTask(string building_ip, string building_guid, string target_table, string mode, List<Dictionary<string, object>> parameter, List<Models.FileInfo> fileInfos = null, string data_guid = "")
        {
            List<string> temp_ips = new List<string>();
            temp_ips = await GetBuilgingIPs(building_ip, building_guid);

            if (temp_ips != null && temp_ips.Count > 0)
            {
                foreach (var temp_ip in temp_ips)
                {
                    if (!string.IsNullOrEmpty(temp_ip) && !string.IsNullOrEmpty(target_table) && mode_list.Contains(mode.ToLower()))
                    {
                        Dictionary<string, object> backgroundServiceTaskDic = new Dictionary<string, object>()
                        {
                            { "@task_type", 1},
                            { "@target_ip", temp_ip},
                            { "@target_table", target_table},
                            { "@mode", mode.ToLower()},
                            { "@repeat_times", 0},
                            { "@is_complete", 0},
                        };

                        if (parameter != null)
                        {
                            var data_json = JsonSerializer.Serialize(parameter);
                            if (!string.IsNullOrEmpty(data_json))
                            {
                                backgroundServiceTaskDic.Add("@target_data", data_json);
                            }
                        }

                        if (fileInfos != null && fileInfos.Count > 0)
                        {
                            var file_json = JsonSerializer.Serialize(fileInfos);
                            if (!string.IsNullOrEmpty(file_json))
                            {
                                backgroundServiceTaskDic.Add("@target_files", file_json);
                            }
                        }

                        List<string> properties = backgroundServiceTaskDic.Keys.ToList();
                        string sql = InsertGenerateString(properties, "background_service_task");
                        await conn.ExecuteAsync(sql, backgroundServiceTaskDic, trans);
                    }
                }
            }
        }

        /// <summary>
        /// 加入至背景執行任務(只有檔案派送)
        /// </summary>
        /// <param name="building_ip"></param>
        /// <param name="building_guid"></param>
        /// <param name="target_table"></param>
        /// <param name="mode"></param>
        /// <param name="parameter"></param>
        /// <param name="fileInfos"></param>
        /// <returns></returns>
        public async Task AddTask(string building_ip, string building_guid, string target_table, List<Models.FileInfo> fileInfos = null)
        {
            List<string> temp_ips = new List<string>();
            temp_ips = await GetBuilgingIPs(building_ip, building_guid);

            if (temp_ips != null && temp_ips.Count > 0)
            {
                foreach (var temp_ip in temp_ips)
                {
                    if (!string.IsNullOrEmpty(temp_ip) && !string.IsNullOrEmpty(target_table))
                    {
                        Dictionary<string, object> backgroundServiceTaskDic = new Dictionary<string, object>()
                        {
                            { "@task_type", 1},
                            { "@target_ip", temp_ip},
                            { "@target_table", target_table},
                            { "@mode", ""},
                            { "@repeat_times", 0},
                            { "@is_complete", 0},
                        };

                        if (fileInfos != null && fileInfos.Count > 0)
                        {
                            var file_json = JsonSerializer.Serialize(fileInfos);
                            if (!string.IsNullOrEmpty(file_json))
                            {
                                backgroundServiceTaskDic.Add("@target_files", file_json);
                            }
                        }

                        List<string> properties = backgroundServiceTaskDic.Keys.ToList();
                        string sql = InsertGenerateString(properties, "background_service_task");
                        await conn.ExecuteAsync(sql, backgroundServiceTaskDic, trans);
                    }
                }
            }
        }

        /// <summary>
        /// 取得目標派送的棟別清單
        /// </summary>
        /// <param name="building_ip"></param>
        /// <param name="building_guid"></param>
        /// <returns></returns>
        private async Task<List<string>> GetBuilgingIPs(string building_ip = "", string building_guid = "")
        {
            List<string> temp_ips = new List<string>();
            if (!string.IsNullOrEmpty(building_ip))
            {
                //有填寫IP,直接用
                temp_ips.Add(building_ip);
            }
            else if (!string.IsNullOrEmpty(building_guid))
            {
                //未填寫IP,抓取該棟別IP
                var sql = $"SELECT * FROM building WHERE deleted = 0 AND building_guid = @Building_guid";
                var result = await conn.QueryFirstOrDefaultAsync<BuildInfo>(sql, new { Building_guid = building_guid }, trans);

                //抓取api_port
                var port_sql = $"SELECT system_value FROM variable WHERE system_type = 'ip_config' AND system_key = 'api_port'";
                var port_result = await conn.QueryFirstOrDefaultAsync<string>(port_sql, "", trans);

                temp_ips.Add(result.Ip_address + ":"+ port_result);
            }
            else
            {
                //未填寫IP、棟別guid 代表全抓
                var sql = $"SELECT * FROM building  WHERE deleted = 0";

                var buildInfos = (await conn.QueryAsync<BuildInfo>(sql, null, trans)).ToList();

                //抓取api_port
                var port_sql = $"SELECT system_value FROM variable WHERE system_type = 'ip_config' AND system_key = 'api_port'";
                var port_result = await conn.QueryFirstOrDefaultAsync<string>(port_sql, "", trans);

                foreach (var build in buildInfos)
                {
                    temp_ips.Add(build.Ip_address + ":" + port_result);
                }
            }

            temp_ips = temp_ips.Distinct().ToList();

            return temp_ips;
        }
    }
}