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.IO;

namespace Backend.Controllers
{
    public class VariableController : MybaseController<VariableController>
    {
        private readonly IBackendRepository backendRepository;
        private string variableFilePath = "";
        public VariableController(IBackendRepository backendRepository)
        {
            this.backendRepository = backendRepository;
            variableFilePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "img");
        }


        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// SystemType列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<List<KeyValue>>> SystemTypeList()
        {
            ApiResult<List<KeyValue>> apiResult = new ApiResult<List<KeyValue>>();
            try
            {
                var sqlString = @$"SELECT DISTINCT system_type as Name, system_type as Value FROM variable v WHERE v.deleted = 0 ORDER BY v.system_type";
                var KeyValue = await backendRepository.GetAllAsync<KeyValue>(sqlString);

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

            return apiResult;
        }

        /// <summary>
        /// 系統變數資料列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<List<VariableInfo>>> VariableInfoList(PostVariableInfoFilter post)
        {
            ApiResult<List<VariableInfo>> apiResult = new ApiResult<List<VariableInfo>>();

            try
            {
                var sWhere = "deleted = 0";

                if (!string.IsNullOrEmpty(post.SelectedSystemType))
                {
                    sWhere += " AND system_type = @SystemType";
                }

                var variableInfos = await backendRepository.GetAllAsync<VariableInfo>("variable", sWhere, new { SystemType = post.SelectedSystemType }, "system_type, system_priority");

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

            return apiResult;
        }


        /// <summary>
        /// 系統變數資料列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<VariableInfo>> GetOneVariable(int id)
        {
            ApiResult<VariableInfo> apiResult = new ApiResult<VariableInfo>();

            try
            {
                string sWhere = @$"deleted = 0 AND id = @Id";

                object param = new { Id = id };

                var variableInfo = await backendRepository.GetOneAsync<VariableInfo>("variable", sWhere, param);

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

            return apiResult;
        }

        /// <summary>
        /// 新增 / 修改 系統變數資料
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<string>> SaveVariable([FromForm] VariableInfo post)
        {
            ApiResult<string> apiResult = new ApiResult<string>();

            try
            {
                string sWhere = @$"deleted = 0 AND id = @Id";

                object param = new { Id = post.id };

                var variableInfo = await backendRepository.GetOneAsync<VariableInfo>("variable", sWhere, param);
                Guid file_guid = Guid.Empty;
                if (post.file != null)
                {
                    file_guid = Guid.NewGuid();
                    var fileName = file_guid + "." + post.extName;

                    var fullPath = Path.Combine(variableFilePath, fileName);

                    if (!System.IO.Directory.Exists(variableFilePath))
                        System.IO.Directory.CreateDirectory(variableFilePath);

                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        post.file.CopyTo(stream);
                    }
                }
                
                if (variableInfo == null)
                {
                    //新增

                    Dictionary<string, object> variableInfoDic = new Dictionary<string, object>()
                    {
                        { "@system_type", post.System_type},
                        { "@system_key", post.System_key},
                        { "@system_value", file_guid != Guid.Empty ? file_guid.ToString() + "." + post.extName : post.system_value},
                        { "@system_remark", post.system_remark},
                        { "@system_priority", post.system_priority},
                        { "@system_parent_id", post.system_parent_id},
                        { "@created_by", myUserInfo.Userinfo_guid},
                    };
                    await backendRepository.AddOneByCustomTable(variableInfoDic, "variable");

                    apiResult.Code = "0000";
                    apiResult.Msg = "新增成功";
                }
                else
                {
                    Dictionary<string, object> variableInfoDic = new Dictionary<string, object>()
                    {
                        { "@system_type", post.System_type},
                        { "@system_key", post.System_key},
                        { "@system_value", file_guid != Guid.Empty ? file_guid.ToString() + "." + post.extName : post.system_value},
                        { "@system_remark", post.system_remark},
                        { "@system_priority", post.system_priority},
                        { "@system_parent_id", post.system_parent_id},
                        { "@updated_by", myUserInfo.Userinfo_guid},
                        { "@updated_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},
                    };

                    await backendRepository.UpdateOneByCustomTable(variableInfoDic, "variable", "id=" + variableInfo.id);

                    apiResult.Code = "0000";
                    apiResult.Msg = "修改成功";
                }
            }
            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;
        }

        /// <summary>
        /// 刪除單一系統變數
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<string>> DeleteOneVariable(int id)
        {
            ApiResult<string> apiResult = new ApiResult<string>();

            try
            {
                string sWhere = @$"deleted = 0 AND id = @Id";

                object param = new { Id = id };

                var variableInfo = await backendRepository.GetOneAsync<VariableInfo>("variable", sWhere, param);

                if (variableInfo == null)
                {
                    apiResult.Code = "9998";
                    apiResult.Msg = "查無該系統變數";
                    return apiResult;
                }

                await backendRepository.DeleteOne(id.ToString(), "variable", "id");

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

            return apiResult;
        }
    }
}