using Backend.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Repository.BackendRepository.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;

namespace Backend.Controllers
{
    public class EmergencySettingController : MybaseController<EmergencySettingController>
    {
        private readonly IBackendRepository backendRepository;

        public EmergencySettingController(IBackendRepository backendRepository)
        {
            this.backendRepository = backendRepository;
        }
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public async Task<ApiResult<List<KeyValue>>> DisasterList()
        {
            ApiResult<List<KeyValue>> apiResult = new ApiResult<List<KeyValue>>();
            List<KeyValue> Variable = new List<KeyValue>();

            try
            {
                var sqlString = @$"select system_value as Value, system_key as Name from variable a where a.system_type = 'disaster' and a.deleted = 0";
                Variable = await backendRepository.GetAllAsync<KeyValue>(sqlString);

                apiResult.Code = "0000";
                apiResult.Data = Variable;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }

            return apiResult;
        }

        [HttpPost]
        public async Task<ApiResult<List<KeyValueID>>> GetSettingList(int system_parent_id)
        {
            ApiResult<List<KeyValueID>> apiResult = new ApiResult<List<KeyValueID>>();
            List<KeyValueID> keyvalue = new List<KeyValueID>();
            try
            {
                keyvalue = await backendRepository.GetAllAsync<KeyValueID>($"select id, system_key as name,system_value as value from variable where deleted = 0 and system_parent_id = {system_parent_id} and system_type = 'DisasterSetting' order by system_priority");
                apiResult.Data = keyvalue;
                apiResult.Code = "0000";
            }
            catch (Exception ex)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + system_parent_id);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + ex.Message);
            }
            return apiResult;
        }



        [HttpPost]
        public async Task<ApiResult<string>> SaveSettingModal(SaveGrouping post)
        {
            ApiResult<string> apiResult = new ApiResult<string>();
            try
            {
                if (post.id == 0)
                {

                    var value = await backendRepository.GetOneAsync<int>("select td.system_value from variable td where td.system_type = 'DisasterSetting' order by cast(td.system_value as int) desc");
                    var dictionary = new Dictionary<string, object>()
                        {
                            {"@system_type", "DisasterSetting"},
                            {"@system_key",post.name},
                            {"@system_value", value + 1},
                            {"@system_remark","急救大步驟設定"},
                            {"@system_priority",post.priority},
                            {"@system_parent_id", post.disaster}
                        };
                    await backendRepository.AddOneByCustomTable(dictionary, "variable");

                    var Nid = await backendRepository.GetOneAsync<int>($"select id from variable where system_type = 'DisasterSetting' and system_key = N'{post.name}' and system_value = '{value + 1}'");

                    var dictionary2 = new Dictionary<string, object>()
                        {
                            {"@system_type", "Verify"},
                            {"@system_key","驗證開關"},
                            {"@system_remark","急救大步驟設定驗證開關"},
                            {"@system_priority",0},
                            {"@system_parent_id", Nid}
                        };
                    if (post.verify == 0)
                    {
                        dictionary2.Add("@system_value", 0);
                    }
                    else
                    {
                        dictionary2.Add("@system_value", 1);
                    }

                    await backendRepository.AddOneByCustomTable(dictionary2, "variable");
                    apiResult.Code = "0000";
                    apiResult.Msg = "新增成功";
                }
                else
                {
                    var dictionary = new Dictionary<string, object>()
                        {
                            {"@system_key",post.name},
                            {"@system_priority",post.priority}
                        };
                    await backendRepository.UpdateOneByCustomTable(dictionary, "variable", $" id = {post.id}");
                    if (post.verify == 0)
                    {
                        var dictionary2 = new Dictionary<string, object>()
                            {
                                {"@system_value",0}
                            };
                        await backendRepository.UpdateOneByCustomTable(dictionary2, "variable", $" system_type = 'Verify' and system_parent_id = '{post.id}'");
                    }
                    else
                    {
                        var haveVerify = await backendRepository.GetOneAsync<string>("variable", $"system_type = 'Verify' and system_parent_id = '{post.id}'");
                        if (haveVerify == null)
                        {
                            var dictionary2 = new Dictionary<string, object>()
                                {
                                    {"@system_type", "Verify"},
                                    {"@system_key","驗證開關"},
                                    {"@system_remark","急救大步驟設定驗證開關"},
                                    {"@system_priority",0},
                                    {"@system_parent_id", post.id},
                                    {"@system_value", 1}
                                };
                            await backendRepository.AddOneByCustomTable(dictionary2, "variable");
                        }
                        else
                        {
                            var dictionary2 = new Dictionary<string, object>()
                                {
                                    {"@system_value",1}
                                };
                            await backendRepository.UpdateOneByCustomTable(dictionary2, "variable", $" system_type = 'Verify' and system_parent_id = '{post.id}'");
                        }
                    }
                    apiResult.Code = "0000";
                    apiResult.Msg = "儲存成功";
                }

            }
            catch (Exception ex)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                string json = System.Text.Json.JsonSerializer.Serialize(post);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + json);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + ex.Message);
            }
            return apiResult;
        }

        [HttpPost]
        public async Task<ApiResult<string>> SaveSubSetting(EmergencySetting post)
        {
            ApiResult<string> apiResult = new ApiResult<string>();
            try
            {
                if (post.emergency_guid == null)
                {
                    var dictionary = new Dictionary<string, object>()
                    {
                        {"@emergency_guid", Guid.NewGuid()},
                        {"@priority",post.priority},
                        {"@big_setting", post.big_setting},
                        {"@full_name",post.full_name},
                        {"@set_doing",post.set_doing},
                        {"@url_text", post.url_text},
                        {"@url_link", post.url_link},
                        {"@not_answer",post.not_answer},
                        {"@created_by",myUserInfo.Userinfo_guid }
                    };
                    await backendRepository.AddOneByCustomTable(dictionary, "emergency_setting");
                    apiResult.Code = "0000";
                    apiResult.Msg = "新增成功";
                }
                else
                {
                    var dictionary = new Dictionary<string, object>()
                    {
                        {"@priority",post.priority},
                        {"@big_setting", post.big_setting},
                        {"@full_name",post.full_name},
                        {"@set_doing",post.set_doing},
                        {"@url_text", post.url_text},
                        {"@url_link", post.url_link},
                        {"@not_answer",post.not_answer},
                        {"@updated_by",myUserInfo.Userinfo_guid },
                        {"@updated_at",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }
                    };
                    await backendRepository.UpdateOneByCustomTable(dictionary, "emergency_setting", $"emergency_guid = '{post.emergency_guid}'");
                    apiResult.Code = "0000";
                    apiResult.Msg = "儲存成功";
                }

            }
            catch (Exception ex)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                string json = System.Text.Json.JsonSerializer.Serialize(post);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + json);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + ex.Message);
            }
            return apiResult;
        }


        [HttpPost]
        public async Task<ActionResult> Emergency_Setting_table(int selectsetting)
        {
            List<EmergencySettingTable> Emergency_Setting_tables = new List<EmergencySettingTable>();
            ApiResult<List<EmergencySettingTable>> apiResult = new ApiResult<List<EmergencySettingTable>>();
            try
            {
                Emergency_Setting_tables = await backendRepository.GetAllAsync<EmergencySettingTable>($@"
                    select v.system_key big_setting_name,* from emergency_setting es left join variable v on es.big_setting = v.id
                    where es.big_setting = {selectsetting} and es.deleted = 0 ");
                apiResult.Code = "0000";
                apiResult.Data = Emergency_Setting_tables;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + selectsetting);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }
            var result = Json(new
            {
                data = apiResult
            });
            return result;
        }

        [HttpPost]
        public async Task<ApiResult<SaveGrouping>> GetOnesetting(int selectsetting)
        {
            ApiResult<SaveGrouping> apiResult = new ApiResult<SaveGrouping>();
            try
            {
                var sql = $@"select v.system_priority as priority,v.system_key as name,s.system_value verify
                              from variable v 
                              left join variable s on v.id = s.system_parent_id
                              where v.id = {selectsetting} and v.deleted = 0";

                var group = await backendRepository.GetOneAsync<SaveGrouping>(sql);
                apiResult.Data = group;
                apiResult.Code = "0000";
            }
            catch (Exception ex)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + selectsetting);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + ex.Message);
            }
            return apiResult;
        }

        [HttpPost]
        public async Task<ApiResult<string>> DeletedOneSubSetting(string guid)
        {
            ApiResult<string> apiResult = new ApiResult<string>();
            try
            {
                await backendRepository.DeleteOne(guid, "emergency_setting", "emergency_guid");
                apiResult.Code = "0000";
                apiResult.Msg = "刪除成功";
            }
            catch (Exception ex)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + guid);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + ex.Message);
            }
            return apiResult;
        }


        [HttpPost]
        public async Task<ApiResult<EmergencySetting>> GetOneSubSetting(string guid)
        {
            ApiResult<EmergencySetting> apiResult = new ApiResult<EmergencySetting>();
            try
            {
                var SubSetting = await backendRepository.GetOneAsync<EmergencySetting>("emergency_setting", $"emergency_guid = '{guid}'");
                apiResult.Data = SubSetting;
                apiResult.Code = "0000";
            }
            catch (Exception ex)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + guid);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + ex.Message);
            }
            return apiResult;
        }

        [HttpPost]
        public async Task<ApiResult<string>> SaveAndOpenSimulationExercise(Eventpost eventpost)
        {
            ApiResult<string> apiResult = new ApiResult<string>();
            try 
            {
                var newguid = Guid.NewGuid();
                var dictionary = new Dictionary<string, object>()
                    {
                        {"@emergency_event_guid",newguid},
                        {"@disaster",eventpost.disaster},
                        {"@building_guid", eventpost.build},
                        {"@type",eventpost.type}
                    };
                await backendRepository.AddOneByCustomTable(dictionary, "emergency_event");
                apiResult.Data = newguid.ToString();
                apiResult.Code = "0000";
                apiResult.Msg = "新增成功";
            }
            catch(Exception ex)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                string json = System.Text.Json.JsonSerializer.Serialize(eventpost);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + json);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + ex.Message);
            }
            return apiResult;
        }

        [HttpPost]
        public async Task<ApiResult<List<SaveGrouping>>> GetBigsetting(int disaster)
        {
            ApiResult<List<SaveGrouping>> apiResult = new ApiResult<List<SaveGrouping>>();
            try
            {
                var sql = $@"  
                      select 
                      v.id id,
                      v.system_key name,
                      f.system_value verify
                      from variable v 
                      join variable f on v.id = f.system_parent_id and f.system_type = 'Verify'
                      where v.system_type = 'DisasterSetting' 
                      and v.system_parent_id = '{disaster}' 
                      and v.deleted = 0 
                      order by v.system_priority";


                var list = await backendRepository.GetAllAsync<SaveGrouping>(sql);

                apiResult.Data = list;
                apiResult.Code = "0000";
                apiResult.Msg = "新增成功";
            }
            catch (Exception ex)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + disaster);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + ex.Message);
            }
            return apiResult;
        }

        [HttpPost]
        public async Task<ApiResult<List<EmergencySettingTable>>> GetEmergencySetting(int selectsetting)
        {
            List<EmergencySettingTable> Emergency_Setting_tables = new List<EmergencySettingTable>();
            ApiResult<List<EmergencySettingTable>> apiResult = new ApiResult<List<EmergencySettingTable>>();
            try
            {
                Emergency_Setting_tables = await backendRepository.GetAllAsync<EmergencySettingTable>($@"
                    select v.system_key big_setting_name,* from emergency_setting es left join variable v on es.big_setting = v.id
                    where es.big_setting = {selectsetting} and es.deleted = 0 order by es.priority");
                apiResult.Code = "0000";
                apiResult.Data = Emergency_Setting_tables;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + selectsetting);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }
            return apiResult;
        }


        [HttpPost]
        public async Task<ApiResult<EmergencyitemWithguid>> GetContentAndMakeItem(Emergencyitempost post)
        {
            
            ApiResult<EmergencyitemWithguid> apiResult = new ApiResult<EmergencyitemWithguid>();
            try
            {
                var Emergency_Setting_tables = await backendRepository.GetOneAsync<EmergencyitemWithguid>($@"
                    select v.system_key big_setting_name,* from emergency_setting es left join variable v on es.big_setting = v.id
                    where es.emergency_guid = '{post.emergency_guid}'");
                
                if(post.make_item == 1)
                {
                    var haveguid = await backendRepository.GetOneAsync<string>($"select emergency_item_guid from emergency_item where event_guid = '{post.event_guid}' and big_setting = '{post.big_setting}' and step_setting = '{post.step_setting}'");
                    if(haveguid == null)
                    {
                        var newguid = Guid.NewGuid();
                        var dictionary = new Dictionary<string, object>()
                        {
                            {"@emergency_item_guid",newguid},
                            {"@event_guid",post.event_guid},
                            {"@big_setting", post.big_setting},
                            {"@step_setting",post.step_setting},
                            {"@created_by",myUserInfo.Userinfo_guid }
                        };
                        await backendRepository.AddOneByCustomTable(dictionary, "emergency_item");
                        Emergency_Setting_tables.emergency_item_guid = newguid.ToString();
                    }
                    else
                    {
                        Emergency_Setting_tables.emergency_item_guid = haveguid;
                    }
                }

                apiResult.Code = "0000";
                apiResult.Data = Emergency_Setting_tables;
            }
            catch (Exception exception)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                string json = System.Text.Json.JsonSerializer.Serialize(post);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + json);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
            }
            return apiResult;
        }

        [HttpPost]
        public async Task<ApiResult<string>> NextStep (Itempost item)
        {
            ApiResult<string> apiResult = new ApiResult<string>();
            byte finish = 0;
            if(item.choose == 0)
            {
                finish = 1;
            }else
            {
                finish = 2;
            }
            try
            {
                var dictionary = new Dictionary<string, object>()
                {
                    {"@finished",finish},
                    {"@updated_by", myUserInfo.Userinfo_guid},
                    {"@updated_at", DateTime.Now}
                };
                if(item.choose == 1)
                {
                    dictionary.Add("@reason", item.reason );
                }
                await backendRepository.UpdateOneByCustomTable(dictionary, "emergency_item", $"emergency_item_guid = '{item.eventguid}'");
                apiResult.Code = "0000";
                apiResult.Msg = "更新成功";
            }
            catch (Exception ex)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                string json = System.Text.Json.JsonSerializer.Serialize(item);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + json);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + ex.Message);
            }
            return apiResult;
        }

        [HttpPost]
        public async Task<ActionResult> Dohistorytotable (string eventguid)
        {
            List<Eventitem> eventitems = new List<Eventitem>();
            ApiResult<List<Eventitem>> apiResult = new ApiResult<List<Eventitem>>();
            try 
            {
                eventitems = await backendRepository.GetAllAsync<Eventitem>($"select * from emergency_item where event_guid = @Guid",new { Guid = $"{eventguid}" });
                apiResult.Data = eventitems;
                apiResult.Code = "0000";
            }
            catch (Exception ex) 
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + eventguid);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + ex.Message);
            }
            var result = Json(new
            {
                data = apiResult
            });
            return result;
        }

        [HttpPost]
        public async Task<ApiResult<bool>> CheckVerifybool(string pass)
        {
            ApiResult<bool> apiResult = new ApiResult<bool>();
            try
            {
                EDFunction edFunction = new EDFunction();
                string passto = "";
                if (pass != null)
                {
                    passto = edFunction.GetSHA256Encryption(pass);
                }
                var Verify = await backendRepository.GetAllAsync<string>("userinfo", $" role_guid = 'B0556AD7-C1E1-47A1-A1F1-802E22714B33' and password = '{passto}'");

                if(Verify.Count == 0)
                {
                    apiResult.Data = false;
                }
                else
                {
                    apiResult.Data = true;
                }
                apiResult.Code = "0000";
            }
            catch (Exception ex)
            {
                apiResult.Code = "9999";
                apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + pass);
                Logger.LogError("【" + controllerName + "/" + actionName + "】" + ex.Message);
            }
            return apiResult;
        }
    }
}