using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using NLog;
using backstage.Helpers;
using backstage.Models;
using backstage.Models.Users;
using Newtonsoft.Json.Linq;
using System.Linq;

using backstage.Models.TokenVault;
using Microsoft.AspNetCore.Routing;
using System.Text.Json;
using System.Dynamic;
using TokenVault_management.Models;

namespace backstage.Controllers
{
    public class TokenVaultController : Controller
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IConfiguration _config;
        private readonly ICallApi _callApi;

        private static Logger logger = LogManager.GetCurrentClassLogger();
        /// <summary>
        /// 讀取組態用
        /// </summary>

        public TokenVaultController(IConfiguration config, ICallApi callApi, IHttpContextAccessor httpContextAccessor)
        {
            _config = config;
            _callApi = callApi;
            _httpContextAccessor = httpContextAccessor;
        }



        [HttpGet]
        public async Task<IActionResult> List(int merchantId)
        {
            var TokenVaultResponse = new TokenVaultResponse();

            // 確認使用者是否已經登入
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Login", "User");


            }
            ViewBag.Merchant_id = merchantId;

            #region 取得部門列表
            var DepartmentsResponse = new DepartmentsResponse();
            var url = _config["IP"] + "/merchant/list";
            var httpMethod = HttpMethod.Post;
            // 取得使用者的 "token" Claim 值
            string token = User.FindFirstValue("token");

            var parameters = new Dictionary<string, string>
              {
                    { "token", token }

                };

            var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                DepartmentsResponse = JsonConvert.DeserializeObject<DepartmentsResponse>(apiResult.Data.ToString());
                if (DepartmentsResponse.r == 0)
                {

                    ViewBag.DepartmentsList = (from o in DepartmentsResponse.merchants
                                               select new SelectListItem
                                               {
                                                   Value = o.merchant_id.ToString(),
                                                   Text = o.merchant_id + "_" + o.name
                                               }).ToList();
                }
            }

            #endregion
            return View();




        }


        [HttpGet]
        public async Task<IActionResult> ListFields([FromQuery] int Merchant_id, int vault_id)
        {
            var TokenVaultResponse = new TokenVaultResponse();
            // 確認使用者是否已經登入
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Login", "User");
            }
            ViewBag.Merchant_id = Merchant_id;
            ViewBag.vault_id = vault_id;

            // 取得使用者的 "token" Claim 值
            string token = User.FindFirstValue("token");

            var httpMethod = HttpMethod.Post;
            var url = _config["IP"] + "/v2/vault/get";
            var parameters = new Dictionary<string, string>
              {

                { "Merchant_id",Merchant_id.ToString()},
                { "id",vault_id.ToString()},
                { "info","INFO"}

            };
            var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                TokenVaultResponse = JsonConvert.DeserializeObject<TokenVaultResponse>(apiResult.Data.ToString());
                if (TokenVaultResponse.r == 0)
                {
                    if (TokenVaultResponse.info.Count > 0)
                    {
                        ViewBag.VaultInfo = TokenVaultResponse.info[0];
                    }
                    else
                    {
                        RedirectToAction("List");
                    }

                }
            }


            url = _config["IP"] + "/v2/vault/get";
            httpMethod = HttpMethod.Post;


            parameters = new Dictionary<string, string>
              {
                    { "Merchant_id", Merchant_id.ToString() },
                    { "id", vault_id.ToString() },
                    { "info", "FIELDS" }

                };

            apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                var FieldsResponse = JsonConvert.DeserializeObject<FieldsResponse>(apiResult.Data.ToString());
                if (FieldsResponse.r == 0)
                {

                    return View(FieldsResponse);
                }
            }
            return View();
        }

        [HttpGet]
        public async Task<IActionResult> ListUsers(int Merchant_id, int vault_id, int field_id)
        {
            var TokenVaultResponse = new TokenVaultResponse();
            // 確認使用者是否已經登入
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Login", "User");
            }

            ViewBag.Merchant_id = Merchant_id;
            ViewBag.vault_id = vault_id;
            ViewBag.field_id = field_id;

            var DepartmentsResponse = new DepartmentsResponse();
            var url = _config["IP"] + "/v2/vault/get";
            var httpMethod = HttpMethod.Post;
            // 取得使用者的 "token" Claim 值
            string token = User.FindFirstValue("token");

            var parameters = new Dictionary<string, string>
              {
                    { "Merchant_id", Merchant_id.ToString() },
                    { "id", vault_id.ToString() },
                    { "info", "USERS" }

                };

            var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                var FieldsResponse = JsonConvert.DeserializeObject<FieldsResponse>(apiResult.Data.ToString());
                if (FieldsResponse.r == 0)
                {
                    //處理遮罩
                    var field = FieldsResponse.fields.Where(f => f.id == field_id).FirstOrDefault();
                    foreach (var u in field.users)
                    {
                        u.masksText = "[" + string.Join(", ", u.masks) + "]";
                    }

                    #region 處理使用者選單
                    url = _config["IP"] + "/user/list";
                    httpMethod = HttpMethod.Post;
                    var types = new[] { "all" };
                    var types_data = new { inc = types };
                    parameters = new Dictionary<string, string>
                      {
                            { "token", token },
                            { "types", JsonConvert.SerializeObject(types_data)},
                        { "email","1"},
                        { "phone","1"}
                            //{ "types", "{\"inc\":[\"all\"]}"}

                        };

                    apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
                    if (apiResult.IsSuccess)
                    {
                        var UserResponse = JsonConvert.DeserializeObject<UserResponse>(apiResult.Data.ToString());
                        var newUsers = new List<User>();
                        foreach (var u in UserResponse.Users)
                        {
                            var existUser = field.users.Where(uu => uu.uid == u.uid).Any();
                            if (!existUser)
                                newUsers.Add(u);

                        }
                        ViewBag.users = (from o in newUsers
                                         select new SelectListItem
                                         {
                                             Value = o.uid.ToString(),
                                             Text = o.uid + "_" + o.name + ", " + o.username
                                         }).ToList();

                    }
                    #endregion




                    return View(field.users);
                }
            }
            return View();
        }

        [Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<IActionResult> AddUsers([FromBody] JsonElement requestData)
        {
            int Merchant_id = requestData.GetProperty("Merchant_id").GetInt32();
            int vault_id = requestData.GetProperty("vault_id").GetInt32();
            int field_id = requestData.GetProperty("field_id").GetInt32();
            int user_id = requestData.GetProperty("user_id").GetInt32();


            // 構建包含參數的查詢字串
            var queryString = new RouteValueDictionary {
        { "Merchant_id", Merchant_id },
        { "vault_id", vault_id },
        { "field_id", field_id },
    };

            // 確認使用者是否已經登入
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Login", "User");
            }
            // 取得使用者的 "token" Claim 值
            string token = User.FindFirstValue("token");

            //檢查user_id是否存在
            var url = _config["IP"] + "/user/list";
            var httpMethod = HttpMethod.Post;
            var types = new[] { "all" };
            var types_data = new { inc = types };
            var parameters = new Dictionary<string, string>
                      {
                            { "token", token },
                            { "types", JsonConvert.SerializeObject(types_data)},
                        { "email","1"},
                        { "phone","1"}

                        };

            var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                var UserResponse = JsonConvert.DeserializeObject<UserResponse>(apiResult.Data.ToString());
                if (UserResponse.userCount > 0)
                {
                    var existUser = UserResponse.Users.Where(u => u.uid == user_id).FirstOrDefault();
                    if (existUser == null)
                    {
                        TempData["IsSuccess"] = false;
                        TempData["msg"] = "user_id不存在";
                        return RedirectToAction("ListUsers", queryString);
                    }
                }
                else
                {
                    TempData["IsSuccess"] = false;
                    TempData["msg"] = "user_id不存在";
                    return RedirectToAction("ListUsers", queryString);
                }
            }
            else
            {
                TempData["IsSuccess"] = false;
                TempData["msg"] = "檢查field_id失敗";
                return RedirectToAction("ListUsers", queryString);
            }

            //檢查merchant_id是否存在
            url = _config["IP"] + "/merchant/list";
            httpMethod = HttpMethod.Post;
            parameters = new Dictionary<string, string>
                      {
                            { "token", token },

                        };

            apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                var DepartmentsResponse = JsonConvert.DeserializeObject<DepartmentsResponse>(apiResult.Data.ToString());
                if (DepartmentsResponse.count > 0)
                {
                    var existDepartment = DepartmentsResponse.merchants.Where(m => m.merchant_id == Merchant_id).FirstOrDefault();
                    if (existDepartment == null)
                    {
                        TempData["IsSuccess"] = false;
                        TempData["msg"] = "merchant_id不存在";
                        return RedirectToAction("ListUsers", queryString);
                    }

                }
                else
                {
                    TempData["IsSuccess"] = false;
                    TempData["msg"] = "merchant_id不存在";
                    return RedirectToAction("ListUsers", queryString);
                }

            }
            else
            {
                TempData["IsSuccess"] = false;
                TempData["msg"] = "檢查merchant_id失敗";
                return RedirectToAction("ListUsers");
            }

            //檢查field_id是否存在
            url = _config["IP"] + "/v2/vault/get";
            httpMethod = HttpMethod.Post;
            parameters = new Dictionary<string, string>
                      {
                            { "Merchant_id", Merchant_id.ToString() },
                            { "id", vault_id.ToString() },
                            { "info", "FIELDS" },

                        };

            apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                var FieldsResponse = JsonConvert.DeserializeObject<FieldsResponse>(apiResult.Data.ToString());
                if (FieldsResponse.fields.Count > 0)
                {
                    var existField = FieldsResponse.fields.Where(m => m.id == field_id).FirstOrDefault();
                    if (existField == null)
                    {
                        TempData["IsSuccess"] = false;
                        TempData["msg"] = "field_id不存在";
                    }
                }
                else
                {
                    TempData["IsSuccess"] = false;
                    TempData["msg"] = "field_id不存在";
                }

            }
            else
            {
                TempData["IsSuccess"] = false;
                TempData["msg"] = "檢查field_id失敗";
                return RedirectToAction("ListUsers", queryString);
            }

            //加入部門

            url = _config["IP"] + "/merchant/adduser";
            httpMethod = HttpMethod.Post;

            var data = new[]
             {
                new {
                    userId = user_id.ToString(),
                    merchantId = Merchant_id.ToString()
                }
            };
            parameters = new Dictionary<string, string>
              {
                    { "token", token},
                    { "data", JsonConvert.SerializeObject(data)}
                                        //{ "data", """userId"":""1"",""merchantId"":""1""")
                };

            apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (!apiResult.IsSuccess)
            {
                var departmentResponse = JsonConvert.DeserializeObject<DepartmentsResponse>(apiResult.Data.ToString());
                if (departmentResponse.r != 0)
                {
                    TempData["IsSuccess"] = false;
                    TempData["msg"] = "加入部門失敗";
                    return RedirectToAction("ListUsers", queryString);
                }
            }
            //加入vault
            var TokenVaultResponse = new TokenVaultResponse();
            url = _config["IP"] + "/merchant/vault/access";
            httpMethod = HttpMethod.Post;

            parameters = new Dictionary<string, string>
              {
                    { "token", token},
                    { "vault_id", vault_id.ToString()},
                    { "access_code", "31"},
                    { "merchant_id", Merchant_id.ToString()},
                    { "user_id", user_id.ToString()},
                };

            apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (!apiResult.IsSuccess)
            {

                TempData["IsSuccess"] = false;
                TempData["msg"] = "加入vault失敗";
                return RedirectToAction("ListUsers", queryString);
            }

            //加入欄位

            var FieldsResponse2 = new FieldsResponse();
            url = _config["IP"] + "/v2/vault";
            httpMethod = HttpMethod.Post;
            var addUserToField_data = new
            {
                action = "ADD",
                id = user_id,
                field_id = field_id,
                allow_decrypt = 1,
                allow_new = 1,
                allow_update = 1,
                allow_del = 1,
                default_mask_id = 1
            };
            parameters = new Dictionary<string, string>
              {

                    { "id", vault_id.ToString()},
                    { "info", "USERS"},
                    { "Merchant_id", Merchant_id.ToString()},
                    { "data", JsonConvert.SerializeObject(addUserToField_data)},
                };

            apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                FieldsResponse2 = JsonConvert.DeserializeObject<FieldsResponse>(apiResult.Data.ToString());
                if (FieldsResponse2.r != 0)
                {
                    TempData["IsSuccess"] = false;
                    TempData["msg"] = "加入Fields失敗";
                    return RedirectToAction("ListUsers", queryString);
                }
                else
                {
                    TempData["IsSuccess"] = true;
                    TempData["msg"] = "加入Fields成功";
                    return RedirectToAction("ListFields", queryString);
                }


            }
            else
            {
                TempData["IsSuccess"] = false;
                TempData["msg"] = "加入Fields失敗";
                return RedirectToAction("ListUsers", queryString);
            }




        }


        [HttpGet]
        public async Task<IActionResult> ListMasks(int Merchant_id, int vault_id, int field_id)
        {

            // 確認使用者是否已經登入
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Login", "User");
            }

            ViewBag.Merchant_id = Merchant_id;
            ViewBag.vault_id = vault_id;
            ViewBag.field_id = field_id;

            // 構建包含參數的查詢字串
            var queryString = new RouteValueDictionary {
                { "Merchant_id", Merchant_id },
                { "vault_id", vault_id },
                { "field_id", field_id },
            };

            #region list mask
            var url = _config["IP"] + "/v2/vault/get";
            var httpMethod = HttpMethod.Post;
            // 取得使用者的 "token" Claim 值
            string token = User.FindFirstValue("token");

            var parameters = new Dictionary<string, string>
              {
                    { "Merchant_id", Merchant_id.ToString() },
                    { "id", vault_id.ToString() },
                    { "info", "INFO" }

                };

            var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                var TokenVaultResponse = JsonConvert.DeserializeObject<TokenVaultResponse>(apiResult.Data.ToString());
                if (TokenVaultResponse.r == 0)
                {
                    if (TokenVaultResponse.info.Count > 0)
                    {
                        ViewBag.VaultName = TokenVaultResponse.info[0].name;
                    }
                }
            }


            parameters = new Dictionary<string, string>
              {
                    { "Merchant_id", Merchant_id.ToString() },
                    { "id", vault_id.ToString() },
                    { "info", "MASKS" }

                };

            apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                var FieldsResponse = JsonConvert.DeserializeObject<FieldsResponse>(apiResult.Data.ToString());
                if (FieldsResponse.r == 0)
                {
                    if (FieldsResponse.fields.Count > 0)
                    {
                        var existField = FieldsResponse.fields.Where(f => f.id == field_id).FirstOrDefault();
                        if (existField != null)
                        {
                            ViewBag.FieldName = existField.name;
                            return View(existField.masks);
                        }

                    }


                }
            }
            #endregion
            return RedirectToAction("ListFields", queryString);
        }

        //新增欄位 
        [Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<IActionResult> CreateField(FieldForCreate FieldForCreate)
        {
            // 構建包含參數的查詢字串
            var queryString = new RouteValueDictionary {
                { "Merchant_id", FieldForCreate.merchant_id },
                { "vault_id", FieldForCreate.vault_id }
                      };
            try
            {


                var url = _config["IP"] + "/v2/vault";
                // 確認使用者是否已經登入
                if (!User.Identity.IsAuthenticated)
                {

                    return RedirectToAction("Login", "User");

                }
                if (string.IsNullOrEmpty(FieldForCreate.name))
                {

                    TempData["IsSuccess"] = false;
                    TempData["msg"] = "名稱不能為空";
                    return RedirectToAction("ListFields", queryString);
                }


                var httpMethod = HttpMethod.Post;
                // 取得使用者的 "token" Claim 值
                string token = User.FindFirstValue("token");
                //if (enabled == "on")
                //    enabled = "true";
                //else
                //    enabled = "false";
                var fieldData = new[]
                  {
                    new
                    {
                        action = "ADD",
                        name = FieldForCreate.name,
                        desc = FieldForCreate.name,
                        format_exp = FieldForCreate.format_exp,
                        enabled = true
                    }
                };


                var parameters = new Dictionary<string, string>
              {
                { "Merchant_id", FieldForCreate.merchant_id.ToString() },
                { "info","FIELDS"},
                { "id", FieldForCreate.vault_id.ToString() },
                    { "data",JsonConvert.SerializeObject(fieldData)}

                };
                var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
                if (apiResult.IsSuccess)
                {
                    var FieldsResponse = JsonConvert.DeserializeObject<FieldsResponse>(apiResult.Data.ToString());
                    if (FieldsResponse.r == 0)
                    {
                        if (FieldsResponse.failInfo == null)
                        {

                            TempData["IsSuccess"] = true;
                            TempData["msg"] = "Create success";
                            return RedirectToAction("ListFields", queryString);

                        }

                        TempData["IsSuccess"] = false;
                        TempData["msg"] = System.Text.RegularExpressions.Regex.Unescape(string.Join(", ", FieldsResponse.failInfo));
                        return RedirectToAction("ListFields", queryString);

                    }
                    else
                    {
                        TempData["IsSuccess"] = false;
                        TempData["msg"] = apiResult.Message;

                        return RedirectToAction("ListFields", queryString);
                    }


                }

            }
            catch (Exception e)
            {

                TempData["IsSuccess"] = false;
                TempData["msg"] = e.Message + e.InnerException?.Message;
                return RedirectToAction("ListFields", queryString);
            }


            TempData["IsSuccess"] = false;
            TempData["msg"] = "Create fail.";
            return RedirectToAction("ListFields", queryString);
        }


        //新增MASK ajax
        [Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<ResultModel> CreateMask(IFormCollection form)
        {
            var result = new ResultModel();


            try
            {

                var url = _config["IP"] + "/v2/vault";

                if (string.IsNullOrEmpty(form["name"]))
                {

                    result.IsSuccess = false;
                    result.Message = "名稱不能為空";
                    return result;
                }


                var httpMethod = HttpMethod.Post;
                // 取得使用者的 "token" Claim 值
                string token = User.FindFirstValue("token");
                var setting = new
                {
                    mask = Convert.ToInt32(form["mask"]),
                    size_init = Convert.ToInt32(form["size_init"]),
                    size_end = Convert.ToInt32(form["size_end"])
                };
                var fieldData = new[]
                  {
                        new
                        {
                            action = "ADD",
                            field_id=Convert.ToInt32(form["field_id"]),
                           name=form["name"].ToString(),
                            type = Convert.ToInt32(form["type"]),
                            setting = System.Text.Json.JsonSerializer.Serialize(setting)

            }
                    };
                string namstext = form["name"];

                var parameters = new Dictionary<string, string>
                  {
                    { "Merchant_id",form["merchant_id"] },
                    { "info","MASKS"},
                    { "id", form["vault_id"]},
                    { "data",JsonConvert.SerializeObject(fieldData)}

                    };
                var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
                if (apiResult.IsSuccess)
                {
                    var Response = JsonConvert.DeserializeObject<Response>(apiResult.Data.ToString());
                    if (Response.r == 0)
                    {
                        if (Response.failInfo == null)
                        {
                            result.IsSuccess = true;
                            result.Message = "Create success";
                            return result;

                        }

                        result.IsSuccess = false;
                        result.Message = System.Text.RegularExpressions.Regex.Unescape(string.Join(", ", Response.failInfo));
                        return result;

                    }
                    else
                    {
                        result.IsSuccess = false;
                        result.Message = Response.m.ToString();

                        return result;
                    }


                }

            }
            catch (Exception e)
            {

                result.IsSuccess = false;
                result.Message = e.Message + e.InnerException?.Message;
                return result;
            }


            result.IsSuccess = false;
            result.Message = "Create fail.";
            return result;
            //return View();
        }


        //刪除MASK ajax
        [Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<ResultModel> DeleteMask(IFormCollection form)
        {
            var result = new ResultModel();


            try
            {

                var url = _config["IP"] + "/v2/vault";

                if (string.IsNullOrEmpty(form["name"]))
                {

                    result.IsSuccess = false;
                    result.Message = "名稱不能為空";
                    return result;
                }


                var httpMethod = HttpMethod.Post;
                // 取得使用者的 "token" Claim 值
                string token = User.FindFirstValue("token");
                var setting = new
                {
                    mask = Convert.ToInt32(form["mask"]),
                    size_init = Convert.ToInt32(form["size_init"]),
                    size_end = Convert.ToInt32(form["size_end"])
                };
                var fieldData = new[]
                  {
                        new
                        {
                            action = "MOD",
                            id=Convert.ToInt32(form["mask_id"]),
                           name=form["name"].ToString(),
                            type = Convert.ToInt32(form["type"]),
                            setting = System.Text.Json.JsonSerializer.Serialize(setting)

            }
                    };
                string namstext = form["name"];

                var parameters = new Dictionary<string, string>
                  {
                    { "Merchant_id",form["merchant_id"] },
                    { "info","MASKS"},
                    { "id", form["vault_id"]},
                    { "data",JsonConvert.SerializeObject(fieldData)}

                    };
                var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
                if (apiResult.IsSuccess)
                {
                    var Response = JsonConvert.DeserializeObject<Response>(apiResult.Data.ToString());
                    if (Response.r == 0)
                    {
                        if (Response.failInfo == null)
                        {
                            result.IsSuccess = true;
                            result.Message = "Create success";
                            return result;

                        }

                        result.IsSuccess = false;
                        result.Message = System.Text.RegularExpressions.Regex.Unescape(string.Join(", ", Response.failInfo));
                        return result;

                    }
                    else
                    {
                        result.IsSuccess = false;
                        result.Message = Response.m.ToString();

                        return result;
                    }


                }

            }
            catch (Exception e)
            {

                result.IsSuccess = false;
                result.Message = e.Message + e.InnerException?.Message;
                return result;
            }


            result.IsSuccess = false;
            result.Message = "Create fail.";
            return result;
            
        }


        //編輯MASK ajax
        [Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<ResultModel> EditMask(IFormCollection form)
        {
            var result = new ResultModel();
           // var field_id = Convert.ToInt32(form["field_id"]);
           // #region list mask
           // var url = _config["IP"] + "/v2/vault/get";
           // var httpMethod = HttpMethod.Post;
           // // 取得使用者的 "token" Claim 值
           // string token = User.FindFirstValue("token");

           //var parameters = new Dictionary<string, string>
           //   {
           //         { "Merchant_id", form["Merchant_id"].ToString() },
           //         { "id", form["vault_id"].ToString() },
           //         { "info", "MASKS" }

           //     };

           // var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
           // if (apiResult.IsSuccess)
           // {
           //     var FieldsResponse = JsonConvert.DeserializeObject<FieldsResponse>(apiResult.Data.ToString());
           //     if (FieldsResponse.r == 0)
           //     {
           //         if (FieldsResponse.fields.Count > 0)
           //         {
           //             var existField = FieldsResponse.fields.Where(f => f.id == field_id).FirstOrDefault();
           //             if (existField != null)
           //             {
           //                 ViewBag.FieldName = existField.name;
           //                 return View(existField.masks);
           //             }

           //         }


           //     }
           // }
           // #endregion



           // try
           // {

           //     var url = _config["IP"] + "/v2/vault";

           //     if (string.IsNullOrEmpty(form["name"]))
           //     {

           //         result.IsSuccess = false;
           //         result.Message = "名稱不能為空";
           //         return result;
           //     }


           //     var httpMethod = HttpMethod.Post;
           //     // 取得使用者的 "token" Claim 值
           //     string token = User.FindFirstValue("token");
           //     var setting = new
           //     {
           //         mask = Convert.ToInt32(form["mask"]),
           //         size_init = Convert.ToInt32(form["size_init"]),
           //         size_end = Convert.ToInt32(form["size_end"])
           //     };
           //     var fieldData = new[]
           //       {
           //             new
           //             {
           //                 action = "ADD",
           //                 field_id=Convert.ToInt32(form["field_id"]),
           //                name=form["name"].ToString(),
           //                 type = Convert.ToInt32(form["type"]),
           //                 setting = System.Text.Json.JsonSerializer.Serialize(setting)

           // }
           //         };
           //     string namstext = form["name"];

           //     var parameters = new Dictionary<string, string>
           //       {
           //         { "Merchant_id",form["merchant_id"] },
           //         { "info","MASKS"},
           //         { "id", form["vault_id"]},
           //         { "data",JsonConvert.SerializeObject(fieldData)}

           //         };
           //     var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
           //     if (apiResult.IsSuccess)
           //     {
           //         var Response = JsonConvert.DeserializeObject<Response>(apiResult.Data.ToString());
           //         if (Response.r == 0)
           //         {
           //             if (Response.failInfo == null)
           //             {
           //                 result.IsSuccess = true;
           //                 result.Message = "Create success";
           //                 return result;

           //             }

           //             result.IsSuccess = false;
           //             result.Message = System.Text.RegularExpressions.Regex.Unescape(string.Join(", ", Response.failInfo));
           //             return result;

           //         }
           //         else
           //         {
           //             result.IsSuccess = false;
           //             result.Message = Response.m.ToString();

           //             return result;
           //         }


           //     }

           // }
           // catch (Exception e)
           // {

           //     result.IsSuccess = false;
           //     result.Message = e.Message + e.InnerException?.Message;
           //     return result;
           // }


           // result.IsSuccess = false;
           // result.Message = "Create fail.";
            return result;
            

        }



        [HttpPost]
        public async Task<IActionResult> ListTokenVaultAjax(int merchantId)
        {


            // 確認使用者是否已經登入
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Login", "User");


            }



            // 取得使用者的 "token" Claim 值
            string token = User.FindFirstValue("token");

            var url = _config["IP"] + "/v2/vault/get";
            var httpMethod = HttpMethod.Post;


            var parameters = new Dictionary<string, string>
              {
                    { "Merchant_id", merchantId.ToString()}
                };

            var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                var TokenVaultResponse = JsonConvert.DeserializeObject<TokenVaultResponse>(apiResult.Data.ToString());

                if (TokenVaultResponse.r == 0)
                {
                    if (TokenVaultResponse.info.Count > 0)
                    {
                        var sortedData = TokenVaultResponse.info.OrderBy(a => a.vault_id);
                        string enabletext = "關閉";
                        // 轉出html
                        string outputHtml = "";
                        foreach (var vault in sortedData)
                        {
                            if (vault.enabled == 1)
                                enabletext = "啟用";

                            string htmlCode = @$"<tr class=""expense-color"">
													<td><a asp-action=""Detail"" asp-route-Id=""{vault.vault_id}""> {vault.vault_id}</a></td>
													<td class=""tokenVaultRow"" data-merchantid=""{merchantId}""  data-vaultid=""{vault.vault_id}"" >{vault.name}</td>
													<td>{vault.desc}</td>
													<td>{vault.type}</td>
													<td>{vault.created}</td>
                                                    <td>{enabletext}</td>
                                                      <td>
                                                        <button class=""btn btnPermission btn-sm"" data-toggle=""modal"" data-target=""#permission"">權限</button>
                                                        <button class=""btn btnPermission btn-sm fieldsBtn"" data-Merchant_id=""{merchantId}"" data-vault_id=""{vault.vault_id}"" >欄位</button>
                                                      </td>
													<td>{vault.tokenCount}</td>
													<td>{vault.userCount}</td>
												
												</tr>";
                            outputHtml += htmlCode;
                        }
                        return Content(outputHtml);
                    }

                    else
                    {
                        return Ok();
                    }

                }
                else
                {
                    return Ok();
                }

            }
            else
            {
                return Ok();
            }

        }

        [Authorize(Policy = "AdminOnly")]
        [HttpGet]
        public async Task<IActionResult> CreateTokenVault()
        {
            #region 取得部門列表
            var DepartmentsResponse = new DepartmentsResponse();
            var url = _config["IP"] + "/merchant/list";
            var httpMethod = HttpMethod.Post;
            // 取得使用者的 "token" Claim 值
            string token = User.FindFirstValue("token");

            var parameters = new Dictionary<string, string>
              {
                    { "token", token }

                };

            var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                DepartmentsResponse = JsonConvert.DeserializeObject<DepartmentsResponse>(apiResult.Data.ToString());
                if (DepartmentsResponse.r == 0)
                {

                    ViewBag.DepartmentsList = (from o in DepartmentsResponse.merchants
                                               select new SelectListItem
                                               {
                                                   Value = o.merchant_id.ToString(),
                                                   Text = o.merchant_id + "_" + o.name
                                               }).ToList();
                }
            }

            #endregion
            return View();
        }

        [Authorize(Policy = "AdminOnly")]
        [HttpGet("/TokenVault/Edit/{id}")]
                public async Task<IActionResult> Edit(int id, [FromQuery] int merchantid)
        {
            #region 取得部門列表
            var DepartmentsResponse = new DepartmentsResponse();
            var url = _config["IP"] + "/merchant/list";
            var httpMethod = HttpMethod.Post;
            // 取得使用者的 "token" Claim 值
            string token = User.FindFirstValue("token");

            var parameters = new Dictionary<string, string>
              {
                    { "token", token }

                };

            var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                DepartmentsResponse = JsonConvert.DeserializeObject<DepartmentsResponse>(apiResult.Data.ToString());
                if (DepartmentsResponse.r == 0)
                {

                    ViewBag.DepartmentsList = (from o in DepartmentsResponse.merchants
                                               select new SelectListItem
                                               {
                                                   Value = o.merchant_id.ToString(),
                                                   Text = o.merchant_id + "_" + o.name
                                               }).ToList();
                }
            }

            #endregion

            httpMethod = HttpMethod.Post;
            url = _config["IP"] + "/v2/vault/get";
            parameters = new Dictionary<string, string>
              {

                { "Merchant_id",merchantid.ToString()},
                { "id",id.ToString()},
                { "info","INFO"}

            };
            apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                var TokenVaultResponse = JsonConvert.DeserializeObject<TokenVaultResponse>(apiResult.Data.ToString());
                if (TokenVaultResponse.r == 0)
                {
                    if (TokenVaultResponse.info.Count > 0)
                    {
                        return View(TokenVaultResponse.info[0]);
                    }
                    else
                    {
                        RedirectToAction("List");
                    }

                }
            }


            return View();
        }

        [Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<IActionResult> CreateTokenVault(TokenVaultForCreate tokenVault)
        {


            #region 取得部門列表
            var DepartmentsResponse = new DepartmentsResponse();
            var url = _config["IP"] + "/merchant/list";
            var httpMethod = HttpMethod.Post;
            // 取得使用者的 "token" Claim 值
            string token = User.FindFirstValue("token");

            var parameters = new Dictionary<string, string>
              {
                    { "token", token }

                };

            var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                DepartmentsResponse = JsonConvert.DeserializeObject<DepartmentsResponse>(apiResult.Data.ToString());
                if (DepartmentsResponse.r == 0)
                {

                    ViewBag.DepartmentsList = (from o in DepartmentsResponse.merchants
                                               select new SelectListItem
                                               {
                                                   Value = o.merchant_id.ToString(),
                                                   Text = o.merchant_id + "_" + o.name
                                               }).ToList();
                }
            }

            #endregion

            // 確認使用者是否已經登入
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Login", "User");

            }
            if (string.IsNullOrEmpty(tokenVault.name))
            {
                ModelState.AddModelError("name", "名稱不能為空");
            }
            if (tokenVault.merchant_id == 0)
            {
                ModelState.AddModelError("merchant_id", "部門不能為空");

            }
            if (!ModelState.IsValid)
            {
                return View(tokenVault);
            }



            url = _config["IP"] + "/tsp/merchant/vault/add";

            parameters = new Dictionary<string, string>
              {
                    { "token", token },
                    { "data",JsonConvert.SerializeObject(tokenVault)}

                };
            apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                var userAddResponse = JsonConvert.DeserializeObject<UserAddResponse>(apiResult.Data.ToString());
                if (userAddResponse.r == 0)
                {
                    TempData["IsSuccess"] = true;
                    TempData["msg"] = "新增Vault成功";
                    return RedirectToAction("List");
                }
                else
                {
                    TempData["IsSuccess"] = false;
                    TempData["msg"] = JsonConvert.SerializeObject(userAddResponse.m);
                    #region 取得部門列表
                    DepartmentsResponse = new DepartmentsResponse();
                    url = _config["IP"] + "/merchant/list";
                    httpMethod = HttpMethod.Post;
                    // 取得使用者的 "token" Claim 值

                    parameters = new Dictionary<string, string>
              {
                    { "token", token }

                };

                    apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
                    if (apiResult.IsSuccess)
                    {
                        DepartmentsResponse = JsonConvert.DeserializeObject<DepartmentsResponse>(apiResult.Data.ToString());
                        if (DepartmentsResponse.r == 0)
                        {

                            ViewBag.DepartmentsList = (from o in DepartmentsResponse.merchants
                                                       select new SelectListItem
                                                       {
                                                           Value = o.merchant_id.ToString(),
                                                           Text = o.merchant_id + "_" + o.name
                                                       }).ToList();
                        }
                    }

                    #endregion
                    return View(tokenVault);
                }


            }



            return View();
        }


    }


}


