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;
using Microsoft.Extensions.Localization;
using Microsoft.AspNetCore.Localization;
using DocumentFormat.OpenXml.Spreadsheet;
using Microsoft.EntityFrameworkCore.Internal;

namespace backstage.Controllers
{
    public class TokenVaultController : Controller
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IConfiguration _config;
        private readonly ICallApi _callApi;
        private readonly IStringLocalizer<UserController> _localizer;

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

        public TokenVaultController(IConfiguration config, ICallApi callApi, IHttpContextAccessor httpContextAccessor, IStringLocalizer<UserController> localizer)
        {
            _config = config;
            _callApi = callApi;
            _httpContextAccessor = httpContextAccessor;
            _localizer = localizer;
            var requestCultureFeature = _httpContextAccessor.HttpContext.Features.Get<IRequestCultureFeature>();
            var currentCulture = requestCultureFeature.RequestCulture.Culture;
            _currentLanguage = currentCulture.TwoLetterISOLanguageName;
        }


        [Authorize(Policy = "AdminOnly")]
        [HttpGet]
        public async Task<IActionResult> List(int merchantId)
        {
            var TokenVaultResponse = new TokenVaultResponse();
            string msg = string.Empty;
            ViewBag.Merchant_id = merchantId;
            logger.Info("merchantId=" + 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
											   where o.enabled == 1
											   select new SelectListItem
                                               {
                                                   Value = o.merchant_id.ToString(),
                                                   Text = o.merchant_id + "_" + o.name
                                               }).ToList();
                }
            }

            #endregion
            return View();




        }



        [Authorize(Policy = "AdminOnly")]
        [HttpGet]
        public async Task<IActionResult> Permission(int merchant_id, int vault_id)
        {

            string msg = string.Empty;
            ViewBag.Merchant_id = merchant_id;
            ViewBag.vault_id = vault_id;


            #region 取得使用者權限列表

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

            var parameters = new Dictionary<string, string>
              {
                    { "token", token },
                    { "vault_id", vault_id.ToString() },
                    { "merchant_id", merchant_id.ToString() }

                };

            var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            var permissionList = new List<Permission>();
            if (apiResult.IsSuccess)
            {
                var Response = JsonConvert.DeserializeObject<Response>(apiResult.Data.ToString());
                if (Response.r == 0)
                {
                    try
                    {
                        permissionList = JsonConvert.DeserializeObject<List<Permission>>(Response.data.ToString());
                        ViewBag.permissionList = permissionList;
                    
                    }
                    catch (Exception e)
                    {
                        TempData["IsSuccess"] = false;
                        TempData["msg"] = e.Message + e.InnerException?.Message;
                        return RedirectToAction("List");
                    }
                   
                }

                else
                {
                    TempData["IsSuccess"] = false;
                    TempData["msg"] = Response;
                    return RedirectToAction("List");
                }
            }
            else
            {
                TempData["IsSuccess"] = false;
                TempData["msg"] = apiResult.Message;
                return RedirectToAction("List");
            }

            #endregion

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

                { "Merchant_id",merchant_id.ToString()},
                { "id",vault_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)
                    {
                        ViewBag.VaultInfo = TokenVaultResponse.info[0];
                    }
                    else
                    {
                        RedirectToAction("List");
                    }

                }
            }
            #endregion

            #region 處理使用者選單

            #region user/list
            var UserResponse = new UserResponse();
             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)
            {
                UserResponse = JsonConvert.DeserializeObject<UserResponse>(apiResult.Data.ToString());

            }
            #endregion
            var newUser = new List<User>();
          
            if (UserResponse.r == 0)
            {
                if (UserResponse.userCount > 0)
                {
                    foreach (var a in UserResponse.Users)
                    {
                        if (a.enabled == 1)
                        {
                            var existUser = permissionList.Where(u => u.user_id == a.uid).FirstOrDefault();
                            if (existUser == null)
                            {
                                newUser.Add(a);
                            }
                        }
                    }
                    ViewBag.newUser= (from o in newUser
                     select new SelectListItem
                     {
                         Value = o.uid.ToString(),
                         Text = o.uid + "_" + o.username
                     }).ToList();

                }
            }
            #endregion

            return View();

        }


        /// <summary>
        /// ajax權限增加使用者
        /// /tokenvault/Permission
        /// </summary>
        /// <param name="merchant_id"></param>
        /// <param name="vault_id"></param>
        /// <param name="mask_id"></param>
        /// <returns></returns>
        [Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<ResultModel> AddUserPermission (int merchant_id, int vault_id, int user_id, int access_code)
        {
            var result = new ResultModel();
            // 取得使用者的 "token" Claim 值
            string token = User.FindFirstValue("token");
            string msg;
         
            var url = _config["IP"] + "/merchant/vault/access";
            var httpMethod = HttpMethod.Post;
          
            var parameters = new Dictionary<string, string>
            {
                 { "vault_id",vault_id.ToString()},
                 { "merchant_id",merchant_id.ToString()},
                 { "token",token},
                 { "user_id",user_id.ToString()},
                { "access_code",access_code.ToString()}
            };

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

                        switch (_currentLanguage)
                        {

                            case "en":
                                msg = "Create user permission success.";
                                break;
                            case "zh":
                                msg = "新增使用者權限成功";
                                break;
                            default:
                                msg = "新增使用者權限成功";
                                break;

                        }
                        result.IsSuccess = true;
                        result.Message = msg;
                        return result;
                    }
                    else
                    {

                        result.IsSuccess = false;
                        result.Message = System.Text.RegularExpressions.Regex.Unescape(string.Join(", ", Response.failInfo));
                        return result;
                    }
                }
                catch (Exception e)
                {
                    result.IsSuccess = false;
                    result.Message = e.Message + e.InnerException?.Message;
                    return result;
                }

            }
            result.IsSuccess = false;
            result.Message = apiResult.Message;
            return result;
      

        }


        /// <summary>
        /// ajax 編輯 權限使用者
        /// </summary>
        /// <param name="merchant_id"></param>
        /// <param name="vault_id"></param>
        /// <param name="mask_id"></param>
        /// <returns></returns>
        [Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<ResultModel> ModUserPermission(int merchant_id, int vault_id, int access_id, int access_code, int enabled)
        {
            var result = new ResultModel();
            // 取得使用者的 "token" Claim 值
            string token = User.FindFirstValue("token");
            string msg;

            var url = _config["IP"] + "/merchant/vault/access";
            var httpMethod = HttpMethod.Put;

            var parameters = new Dictionary<string, string>
            {
                 { "vault_id",vault_id.ToString()},
                 { "merchant_id",merchant_id.ToString()},
                 { "token",token},
                 { "id",access_id.ToString()},
                { "access_code",access_code.ToString()},
                { "enabled",enabled.ToString()}
            };

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

                        switch (_currentLanguage)
                        {

                            case "en":
                                msg = "Edit user permission success.";
                                break;
                            case "zh":
                                msg = "編輯使用者權限成功";
                                break;
                            default:
                                msg = "編輯使用者權限成功";
                                break;

                        }
                        result.IsSuccess = true;
                        result.Message = msg;
                        return result;
                    }
                    else
                    {

                        result.IsSuccess = false;
                        result.Message = System.Text.RegularExpressions.Regex.Unescape(string.Join(", ", Response.failInfo));
                        return result;
                    }
                }
                catch (Exception e)
                {
                    result.IsSuccess = false;
                    result.Message = e.Message + e.InnerException?.Message;
                    return result;
                }

            }
            result.IsSuccess = false;
            result.Message = apiResult.Message;
            return result;


        }

        [Authorize(Policy = "AdminOnly")]
        [HttpGet]
        public async Task<IActionResult> ListFields([FromQuery] int Merchant_id, int vault_id)
        {
            string msg;
            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");

            #region 取得vault info
            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");
                    }

                }
            }
            #endregion


            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();
        }
        [Authorize(Policy = "AdminOnly")]
        [HttpGet]
        public async Task<IActionResult> ListUsers(int Merchant_id, int vault_id, int field_id)
        {
            var TokenVaultResponse = new TokenVaultResponse();


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


            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>();
                        if (UserResponse.userCount > 0)
                        {
                            foreach (var u in UserResponse.Users)
                            {
                                var existUser = field.users.Where(uu => uu.id == 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

                    #region 處理遮罩tooltip

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


                    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)
                    {
                        FieldsResponse = JsonConvert.DeserializeObject<FieldsResponse>(apiResult.Data.ToString());
                        var existField = FieldsResponse.fields.FirstOrDefault(f => f.id == field_id);

                        ViewBag.masks = (from o in existField.masks
                                         select new SelectListItem
                                         {
                                             Value = o.id.ToString(),
                                             Text = o.id + "_" + o.name 
                                         }).ToList();
                        foreach (var u in field.users)
                        {
                            if (u.masks.Count > 0)
                            {
                                var maskTextList = new List<string>();
                              
                                foreach (var maskId in u.masks)
                                {
                                    var matchingMask = existField.masks.FirstOrDefault(m => m.id == maskId);
                                    if (matchingMask != null)
                                    {
                                        string maskText = $"[{matchingMask.id}] - {matchingMask.name} - {matchingMask.setting}<br/>";
                                        maskTextList.Add(maskText);
                                    }
                                }

                                u.masksSettingText = string.Join(", ", maskTextList);
                            }
                        }

                    }
                    #endregion

                


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

        /// <summary>
        /// 欄位添加使用者 ajax
        /// /tokenvault/ListFields
        /// </summary>
        /// <param name="requestData"></param>
        /// <returns></returns>
        [Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<ResultModel> AddUsers(IFormCollection form)
        {
            string msg;
            var result = new ResultModel();
         
            if (!form.ContainsKey("allow_decrypt") ||
               !form.ContainsKey("allow_new") ||
               !form.ContainsKey("allow_update") ||
               !form.ContainsKey("allow_del") ||
               !form.ContainsKey("allow_masks") ||
               !form.ContainsKey("default_mask_id")||
                  !form.ContainsKey("allow_masks") ||
                       !form.ContainsKey("vault_id") ||
                          !form.ContainsKey("field_id") ||
                            
                                   !form.ContainsKey("merchant_id") 
               )
            {
                // 至少有一個鍵不存在，處理這種情況
                switch (_currentLanguage)
                {

                    case "en":
                        msg = "All fields are required.";
                        break;
                    case "zh":
                        msg = "所有欄位必填";
                        break;
                    default:
                        msg = "所有欄位必填";
                        break;

                }
                result.IsSuccess = false;
                result.Message = msg;
                return result;
            }
            int merchant_id = Convert.ToInt32(form["merchant_id"]);
            int vault_id = Convert.ToInt32(form["vault_id"]);
            int field_id = Convert.ToInt32(form["field_id"]);
            int user_id = Convert.ToInt32(form["id"]);

            // 取得使用者的 "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)
                    {
                        switch (_currentLanguage)
                        {

                            case "en":
                                msg = "User is not exist.";
                                break;
                            case "zh":
                                msg = "使用者不存在";
                                break;
                            default:
                                msg = "使用者不存在";
                                break;

                        }
                        result.IsSuccess = false;
                        result.Message = msg;
                        return result;
                    }
                }
                else
                {
                    switch (_currentLanguage)
                    {

                        case "en":
                            msg = "User is not exist.";
                            break;
                        case "zh":
                            msg = "使用者不存在";
                            break;
                        default:
                            msg = "使用者不存在";
                            break;

                    }
                    result.IsSuccess = false;
                    result.Message = msg;
                    return result;
                }
            }
            else
            {
                switch (_currentLanguage)
                {

                    case "en":
                        msg = "Check field_id failed.";
                        break;
                    case "zh":
                        msg = "檢查field_id失敗";
                        break;
                    default:
                        msg = "檢查field_id失敗";
                        break;

                }
                result.IsSuccess = false;
                result.Message = msg;
                return result;
            }

            //檢查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)
                    {
                        switch (_currentLanguage)
                        {

                            case "en":
                                msg = "Merchint_id is not exist.";
                                break;
                            case "zh":
                                msg = "merchant_id不存在";
                                break;
                            default:
                                msg = "merchant_id不存在";
                                break;

                        }
                        result.IsSuccess = false;
                        result.Message = msg;
                        return result;
                    }

                }
                else
                {
                    switch (_currentLanguage)
                    {

                        case "en":
                            msg = "Merchint_id is not exist.";
                            break;
                        case "zh":
                            msg = "merchant_id不存在";
                            break;
                        default:
                            msg = "merchant_id不存在";
                            break;

                    }
                    result.IsSuccess = false;
                    result.Message = msg;
                    return result;
                }

            }
            else
            {
                switch (_currentLanguage)
                {

                    case "en":
                        msg = "Check merchint_id failed.";
                        break;
                    case "zh":
                        msg = "檢查merchant_id失敗";
                        break;
                    default:
                        msg = "檢查merchant_id失敗";
                        break;

                }
                result.IsSuccess = false;
                result.Message = msg;
                return result;
            }

            //檢查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)
                    {
                        switch (_currentLanguage)
                        {

                            case "en":
                                msg = "Field_id is not exist.";
                                break;
                            case "zh":
                                msg = "field_id不存在";
                                break;
                            default:
                                msg = "field_id不存在";
                                break;

                        }
                        result.IsSuccess = false;
                        result.Message = msg;
                    }
                }
                else
                {
                    switch (_currentLanguage)
                    {

                        case "en":
                            msg = "Field_id is not exist.";
                            break;
                        case "zh":
                            msg = "field_id不存在";
                            break;
                        default:
                            msg = "field_id不存在";
                            break;

                    }
                    result.IsSuccess = false;
                    result.Message = msg;
                }

            }
            else
            {
                switch (_currentLanguage)
                {

                    case "en":
                        msg = "Field_id is not exist.";
                        break;
                    case "zh":
                        msg = "field_id不存在";
                        break;
                    default:
                        msg = "field_id不存在";
                        break;

                }
                result.IsSuccess = false;
                result.Message = msg;
                return result;
            }

            //加入部門

            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)
                {
                    switch (_currentLanguage)
                    {

                        case "en":
                            msg = "Add user into department failed.";
                            break;
                        case "zh":
                            msg = "加入部門失敗";
                            break;
                        default:
                            msg = "加入部門失敗";
                            break;

                    }
                    result.IsSuccess = false;
                    result.Message = msg + apiResult.Data.ToString();
                    return result;
                }
            }
            //加入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)
            {
                switch (_currentLanguage)
                {

                    case "en":
                        msg = "Field_id is not exist.";
                        break;
                    case "zh":
                        msg = "加入vault失敗";
                        break;
                    default:
                        msg = "加入vault失敗";
                        break;

                }
                result.IsSuccess = false;
                result.Message = msg;
                return result;
            }

            //加入欄位

            var FieldsResponse2 = new FieldsResponse();
            url = _config["IP"] + "/v2/vault";
            httpMethod = HttpMethod.Post;
            try
            {
                var x = form["allow_masks"].ToString().Split(',').Select(int.Parse).ToArray();
                string numberString = form["allow_masks"].ToString();
                int[] allow_masks = Array.ConvertAll(numberString.Split(','), int.Parse);
                var addUserToField_data = new[]
                {

                    new
                    {
                        action = "ADD",
                        id = user_id,
                        field_id = field_id,
                        allow_decrypt = Convert.ToInt32(form["allow_decrypt"].ToString()),
                        allow_new = Convert.ToInt32(form["allow_new"].ToString()),
                        allow_update = Convert.ToInt32(form["allow_update"].ToString()),
                        allow_del = Convert.ToInt32(form["allow_del"].ToString()),
                        allow_masks=allow_masks,
                        default_mask_id = Convert.ToInt32( form["default_mask_id"])
                    }

                };

                parameters = new Dictionary<string, string>
                  {

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

            }
            catch (Exception e)
            {
                return result;
            }
          
            apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                var response = JsonConvert.DeserializeObject<Response>(apiResult.Data.ToString());
                if (response.r!=0)
                {
                    switch (_currentLanguage)
                    {

                        case "en":
                            msg = "Add user into Field_id failed.";
                            break;
                        case "zh":
                            msg = "加入Fields失敗";
                            break;
                        default:
                            msg = "加入Fields失敗";
                            break;

                    }
                    result.IsSuccess = false;
                    result.Message = msg + response.r+","+response.m;
                    return result;
                }
                else
                {
                    switch (_currentLanguage)
                    {

                        case "en":
                            msg = "Add user into fields Success.";
                            break;
                        case "zh":
                            msg = "加入Fields成功";
                            break;
                        default:
                            msg = "加入Fields成功";
                            break;

                    }
                    result.IsSuccess = true;
                    result.Message = msg;
                    return result;
                }


            }
            else
            {
                switch (_currentLanguage)
                {

                    case "en":
                        msg = "Add user into Field_id failed.";
                        break;
                    case "zh":
                        msg = "加入Fields失敗";
                        break;
                    default:
                        msg = "加入Fields失敗";
                        break;

                }
                result.IsSuccess = false;
                result.Message = msg + apiResult.Data.ToString();
                return result;
            }




        }

        /// <summary>
        /// 欄位移除'使用者 ajax
        /// </summary>
        /// <param name="requestData"></param>
        /// <returns></returns>
        [Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<ResultModel> DelUsers([FromBody] JsonElement requestData)
        {
            string msg;
            var result = new ResultModel();
            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();


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

            //檢查user_id是否存在
            var url = _config["IP"] + "/v2/vault";
            var httpMethod = HttpMethod.Post;

            var data = new[]{ new {
                action="DEL",
                id=user_id,
                field_id
            } };
            var parameters = new Dictionary<string, string>
                      {
                            { "id", vault_id.ToString() },
                            { "data", JsonConvert.SerializeObject(data)},
                        { "info","USERS"},
                        { "Merchant_id",Merchant_id.ToString()}

                        };

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

                        case "en":
                            msg = "Remove user success.";
                            break;
                        case "zh":
                            msg = "移除使用者成功";
                            break;
                        default:
                            msg = "移除使用者成功";
                            break;
                    }
                    result.IsSuccess = true;
                    result.Message = msg;
                    return result;

                }
                else
                {

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

                result.IsSuccess = false;
                result.Message = apiResult.Message;
                return result;
            }




        }




        [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);
        }

        private int GetValidIntegerValue(string input)
        {
            if (int.TryParse(input, out int value))
            {
                return value;
            }
            else
            {
                return 0;
            }
        }

        //新增or編輯 MASK ajax
        [Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<ResultModel> CreateMask(IFormCollection form)
        {
            var result = new ResultModel();
            string msg;
            //判斷非null就是編輯 反之新增
            var mask_id = form.ContainsKey("mask_id") && int.TryParse(form["mask_id"], out int id) ? id : (int?)null;
            try
            {

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

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

                        case "en":
                            msg = "Name is empty.";
                            break;
                        case "zh":
                            msg = "名稱不能為空";
                            break;
                        default:
                            msg = "名稱不能為空";
                            break;

                    }
                    result.IsSuccess = false;
                    result.Message = msg;
                    return result;
                }


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

                var setting = new
                {
                    mask = GetValidIntegerValue(form["mask"]),
                    size_init = GetValidIntegerValue(form["size_init"]),
                    size_end = GetValidIntegerValue(form["size_end"]),
                };

                string action = "ADD";
                if (mask_id != null)
                {
                    action = "MOD";
                }
                var fieldData = new[]
                  {
                        new
                        {
                            action = action,
                            field_id=Convert.ToInt32(form["field_id"]),
                           name=form["name"].ToString(),
                            type = Convert.ToInt32(form["type"]),
                            setting = System.Text.Json.JsonSerializer.Serialize(setting),
                                //編輯功能 mask_id要帶上
      
                                    id = mask_id

                    }
                 };


                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)
                        {
                            if (mask_id == null)
                            {
                                switch (_currentLanguage)
                                {

                                    case "en":
                                        msg = "Create mask success.";
                                        break;
                                    case "zh":
                                        msg = "新增遮罩成功";
                                        break;
                                    default:
                                        msg = "新增遮罩成功";
                                        break;

                                }
                                result.IsSuccess = true;
                                result.Message = msg;
                            }
                            else
                            {
                                switch (_currentLanguage)
                                {

                                    case "en":
                                        msg = "Revise mask success.";
                                        break;
                                    case "zh":
                                        msg = "編輯遮罩成功";
                                        break;
                                    default:
                                        msg = "編輯遮罩成功";
                                        break;

                                }
                                result.IsSuccess = true;
                                result.Message = msg;
                            }

                            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;
                    }


                }
                else
                {
                    result.IsSuccess = false;
                    result.Message = apiResult.Message;
                    return result;
                }

            }
            catch (Exception e)
            {

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



            //return View();
        }


        //刪除MASK ajax
        [Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<ResultModel> DeleteMask(int merchant_id, int vault_id, int mask_id)
        {
            var result = new ResultModel();
            string msg;
            #region key/list
            var url = _config["IP"] + "/v2/vault";
            var httpMethod = HttpMethod.Post;
            var data = new[]{
            new {
                action="DEL",
                id=mask_id
            }
            };
            var parameters = new Dictionary<string, string>
            {
                 { "id",vault_id.ToString()},
                 { "Merchant_id",merchant_id.ToString()},
                 { "info","MASKS"},
                 { "data",JsonConvert.SerializeObject(data)}
            };

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

                        switch (_currentLanguage)
                        {

                            case "en":
                                msg = "Delete mask success.";
                                break;
                            case "zh":
                                msg = "遮罩刪除成功";
                                break;
                            default:
                                msg = "遮罩刪除成功";
                                break;

                        }
                        result.IsSuccess = true;
                        result.Message = msg;
                        return result;
                    }
                    else
                    {

                        result.IsSuccess = false;
                        result.Message = System.Text.RegularExpressions.Regex.Unescape(string.Join(", ", Response.failInfo));
                        return result;
                    }
                }
                catch (Exception e)
                {
                    result.IsSuccess = false;
                    result.Message = e.Message + e.InnerException?.Message;
                    return result;
                }

            }
            result.IsSuccess = false;
            result.Message = apiResult.Message;
            return result;
            #endregion




        }


        //編輯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;


        }


        [Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<IActionResult> ListTokenVaultAjax(int merchantId)
        {
            string msg;

            // 取得使用者的 "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.Where(a => a.enabled == 1).OrderBy(a => a.vault_id);
                        switch (_currentLanguage)
                        {

                            case "en":
                                msg = "Disable";
                                break;
                            case "zh":
                                msg = "停用";
                                break;
                            default:
                                msg = "停用";
                                break;

                        }
                        string enabletext = msg;
                        // 轉出html
                        string outputHtml = "";
                        string permission;
                        string Fields;
						string backup;
						string restitute;
						switch (_currentLanguage)
                        {

                            case "en":
                                permission = "Permission";
                                Fields = "Fields";
								backup = "Backup";
								restitute = "Restore";
								break;
                            case "zh":
                                permission = "權限";
                                Fields = "欄位";
								backup = "備份";
								restitute = "還原";
								break;
                            default:
                                permission = "權限";
                                Fields = "欄位";
								backup = "備份";
								restitute = "還原";
								break;

                        }
                        foreach (var vault in sortedData)
                        {
                            if (vault.enabled == 1)
                            {
                                switch (_currentLanguage)
                                {

                                    case "en":
                                        msg = "Enable";
                                        break;
                                    case "zh":
                                        msg = "啟用";
                                        break;
                                    default:
                                        msg = "啟用";
                                        break;
                                }
                                enabletext = msg;
                            }

                            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 permissionBtn"" data-merchant_id=""{merchantId}"" data-vault_id=""{vault.vault_id}"">{permission}</button>
                                                        <button class=""btn btnPermission btn-sm fieldsBtn"" data-merchant_id=""{merchantId}"" data-vault_id=""{vault.vault_id}"" >{Fields}</button>
                                                        <button class=""btn btnPermission btn-sm backupBtn"" data-toggle=""modal"" data-target=""#backup-modal"" data-merchant_id=""{merchantId}"" data-vault_id=""{vault.vault_id}"" data-vault_name=""{vault.name}"">{backup}</button>
							                            <button class=""btn btnPermission btn-sm restituteBtn"" data-toggle=""modal"" data-target=""#restitute-modal"" data-merchant_id=""{merchantId}"" data-vault_id=""{vault.vault_id}"" >{restitute}</button>
                                                      </td>
													<td>{vault.tokenCount}</td>
													<td>{vault.userCount}</td>
												    <td>
													    <a class=""delVaultBtn"" data-merchant_id=""{merchantId}"" data-vault_id=""{vault.vault_id}"" data-toggle=""modal"" data-target=""#delModal"" title=""Delete"">
														    <i class=""fa-solid fa-trash-can""></i>
													    </a>
												    </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
											   where o.enabled == 1
											   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
                                               where o.enabled == 1
                                               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)
                    {
                        TokenVaultResponse.info[0].merchant_id = merchantid;
						return View(TokenVaultResponse.info[0]);
                    }
                    else
                    {
                        RedirectToAction("List");
                    }

                }
            }


            return View();
        }

		[Authorize(Policy = "AdminOnly")]
		[HttpPost("/TokenVault/Edit/{id}")]
		public async Task<IActionResult> Edit(int id, TokenVault tokenVault)
        {
			string msg = string.Empty;
			// 取得使用者的 "token" Claim 值
			string token = User.FindFirstValue("token");

            //get此部門的全部vault api
			var url = _config["IP"] + "/v2/vault/get";
			var httpMethod = HttpMethod.Post;
			var parameters = new Dictionary<string, string>
			{
			    { "Merchant_id", tokenVault.merchant_id.ToString()},
            };
			var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);

            if (apiResult.IsSuccess)
            {
                var tokenVaultResponse = JsonConvert.DeserializeObject<TokenVaultResponse>(apiResult.Data.ToString());
                if (tokenVaultResponse.info != null)
                {
                    var existVault = tokenVaultResponse.info.Where(x => x.vault_id == id).FirstOrDefault();
                    if (existVault != null)
                    {
						if (string.IsNullOrEmpty(tokenVault.name))
						{
							switch (_currentLanguage)
							{

								case "en":
									msg = " can't be empty.";
									break;
								case "zh":
									msg = "不得空白";
									break;
								default:
									msg = "不得空白";
									break;

							}
							ModelState.AddModelError("name", msg);
						}
                        else
                        {
							var nameRepeat = tokenVaultResponse.info.Where(x => x.vault_id != id && x.name == tokenVault.name).FirstOrDefault();
                            if(nameRepeat != null)
                            {
								switch (_currentLanguage)
								{
									case "en":
										msg = " can't be repeated.";
										break;
									case "zh":
										msg = "不得重複";
										break;
									default:
										msg = "不得重複";
										break;
								}
								ModelState.AddModelError("name", msg);
							}
						}
                        if (string.IsNullOrEmpty(tokenVault.desc))
						{
							switch (_currentLanguage)
							{
								case "en":
									msg = " can't be empty.";
									break;
								case "zh":
									msg = "不得空白";
									break;
								default:
									msg = "不得空白";
									break;

							}
							ModelState.AddModelError("desc", msg);
						}
						if (!ModelState.IsValid)
						{
							return View(tokenVault);
						}

						//修改vault
						existVault.name = tokenVault.name.Trim();
						existVault.desc = tokenVault.desc;
                        existVault.merchant_id = tokenVault.merchant_id;

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

                        var editDataJson = new
                        {
							name = existVault.name,
							desc = existVault.desc,
							type = existVault.type,
							enabled =existVault.enabled
						};
						parameters = new Dictionary<string, string>
				        {
					        { "token", token },
							{ "info", "INFO" },
							{ "id", existVault.vault_id.ToString() },
							{ "Merchant_id", existVault.merchant_id.ToString() },
							{ "data", JsonConvert.SerializeObject(editDataJson)}
				        };
						apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
						if (apiResult.IsSuccess)
						{
							var response = JsonConvert.DeserializeObject<Response>(apiResult.Data.ToString());
                            if (response.r == 0)
                            {
							    switch (_currentLanguage)
							    {

								    case "en":
									    msg = "Edit success.";
									    break;
								    case "zh":
									    msg = "編輯成功";
									    break;
								    default:
									    msg = "編輯成功";
									    break;

							    }
							    TempData["IsSuccess"] = true;
							    TempData["msg"] = msg;
							    return RedirectToAction("List");
                            }

						}
					}
                }
            }

			switch (_currentLanguage)
			{
				case "en":
					msg = "Edit fail.";
					break;
				case "zh":
					msg = "編輯失敗";
					break;
				default:
					msg = "編輯失敗";
					break;

			}
			TempData["IsSuccess"] = false;
			TempData["msg"] = msg;
			return RedirectToAction("List");


		}


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

            #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
											   where o.enabled == 1
											   select new SelectListItem
                                               {
                                                   Value = o.merchant_id.ToString(),
                                                   Text = o.merchant_id + "_" + o.name
                                               }).ToList();
                }
            }

            #endregion

            if (string.IsNullOrEmpty(tokenVault.name))
            {
                switch (_currentLanguage)
                {

                    case "en":
                        msg = " can't be empty.";
                        break;
                    case "zh":
                        msg = "不能為空";
                        break;
                    default:
                        msg = "不能為空";
                        break;
                }
                ModelState.AddModelError("name", msg);
            }
            if (tokenVault.merchant_id == 0)
            {
                switch (_currentLanguage)
                {

                    case "en":
                        msg = " can't be empty.";
                        break;
                    case "zh":
                        msg = "部門不能為空";
                        break;
                    default:
                        msg = "部門不能為空";
                        break;
                }
                ModelState.AddModelError("merchant_id", msg);

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

            tokenVault.name = tokenVault.name.Trim();

			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)
                {
                    switch (_currentLanguage)
                    {

                        case "en":
                            msg = "Create Token Vault success.";
                            break;
                        case "zh":
                            msg = "新增Token Vault成功";
                            break;
                        default:
                            msg = "新增Token Vault成功";
                            break;
                    }
                    TempData["IsSuccess"] = true;
                    TempData["msg"] = msg;
                    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
													   where o.enabled == 1
													   select new SelectListItem
                                                       {
                                                           Value = o.merchant_id.ToString(),
                                                           Text = o.merchant_id + "_" + o.name
                                                       }).ToList();
                        }
                    }

                    #endregion
                    return View(tokenVault);
                }


            }



            return View();
        }


		/// <summary>
		/// 備份vault ajax
		/// </summary>
		/// <param name="vault_id"></param>
		/// <param name="merchant_id"></param>
		/// <returns></returns>
		[Authorize(Policy = "AdminOnly")]
		[HttpGet]
		public async Task<ResultModel> Backup(int vault_id, int merchant_id)
        {

			var result = new ResultModel();
			// 取得使用者的 "token" Claim 值
			string token = User.FindFirstValue("token");
			string msg;
            string fileName;


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

			var parameters = new Dictionary<string, string>
			{
				 { "id", vault_id.ToString()},
				 { "Merchant_id", merchant_id.ToString()},
                 { "info", "INFO"}
            };
            var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                try
                {
                    var response = JsonConvert.DeserializeObject<Response>(apiResult.Data.ToString());
                    if (response.r == 0)
                    {
                        var vaultInfoList = JsonConvert.DeserializeObject<List<TokenVault>>(response.info.ToString());
                        fileName = vaultInfoList[0].name;
                    }
                    else
                    {
                        result.IsSuccess = false;
                        result.Message = response.m.ToString();
                        return result;
                    }
                }
                catch (Exception e)
                {
                    result.IsSuccess = false;
                    result.Message = e.Message;
                    return result;
                }
            }
            else
            {
                result.IsSuccess = false;
                result.Message = apiResult.Message;
                return result;
            }

            url = _config["IP"] + "/v2/vault/entry/backup";
            parameters = new Dictionary<string, string>
            {
                 { "vault_id", vault_id.ToString()},
                 { "merchant_id", merchant_id.ToString()}
            };
            apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
				try
				{
					var response = JsonConvert.DeserializeObject<Response>(apiResult.Data.ToString());
                    if(response.r == 0)
                    {
                        var jsonRe = JsonConvert.SerializeObject(response.d);

					    var resultData = new
                        {
                            fileName = fileName,
                            json = jsonRe
					    };

					    result.IsSuccess = true;
                        result.Message = "Success.";
                        result.Data = resultData;
                        return result;
                    }
                    else
                    {
						result.IsSuccess = false;
						result.Message = response.m.ToString();
                        return result;
					}
				}
				catch (Exception e)
				{
					result.IsSuccess = false;
					result.Message = e.Message;
					return result;
				}
            }
            else
            {
				result.IsSuccess = false;
				result.Message = apiResult.Message;
				return result;
			}
        }


        /// <summary>
        /// 備份vault ajax
        /// </summary>
        /// <param name="vault_id"></param>
        /// <param name="merchant_id"></param>
        /// <returns></returns>
        [Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<ResultModel> Restitute(int vault_id, int merchant_id, string json)
        {
			var result = new ResultModel();
			// 取得使用者的 "token" Claim 值
			string token = User.FindFirstValue("token");
			string msg;

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

			var parameters = new Dictionary<string, string>
			{
				{ "vault_id", vault_id.ToString()},
				{ "merchant_id", merchant_id.ToString()},
			    { "data", json}
			};
			var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                try
                {
					var response = JsonConvert.DeserializeObject<Response>(apiResult.Data.ToString());
                    if(response.r == 0)
                    {
                        result.IsSuccess = true;
                        result.Message = "Success.";
                        result.Data = response.error;
                        return result;
                    }
                    else
                    {
						result.IsSuccess = false;
						result.Message = "error.";
						return result;
					}
				}
				catch(Exception ex)
                {
					result.IsSuccess = false;
					result.Message = "error.";
					return result;
				}
            }
            else
            {
				result.IsSuccess = false;
				result.Message = "error.";
				return result;
			}

		}


		/// <summary>
		/// 刪除欄位 ajax
		/// </summary>
		/// <param name="vault_id"></param>
		/// <param name="merchant_id"></param>
		/// <param name="field_id"></param>
		/// <returns></returns>
		[Authorize(Policy = "AdminOnly")]
		[HttpPost]
		public async Task<ResultModel> DelField(int vault_id, int merchant_id, int field_id)
        {
            var result = new ResultModel();
			// 取得使用者的 "token" Claim 值
			//string token = User.FindFirstValue("token");
			string msg;

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

			var data = new[]{ new {
				action = "DEL",
				id = field_id,
			}};
			var parameters = new Dictionary<string, string>
			{
				{ "info", "FIELDS" },
				{ "id", vault_id.ToString() },
				{ "Merchant_id", merchant_id.ToString() },
				{ "data", JsonConvert.SerializeObject(data)}
			};
			var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
			if (apiResult.IsSuccess)
			{
				try
				{
					var response = JsonConvert.DeserializeObject<Response>(apiResult.Data.ToString());
					if (response.r == 0)
					{
						result.IsSuccess = true;
					}
					else
					{
						result.IsSuccess = false;
					}
				}
				catch (Exception ex)
				{
					result.IsSuccess = false;
				}
			}
			else
			{
				result.IsSuccess = false;
			}

            if (result.IsSuccess)
            {
				switch (_currentLanguage)
				{
					case "en":
						msg = "Delete field success.";
						break;
					case "zh":
						msg = "欄位刪除成功";
						break;
					default:
						msg = "欄位刪除成功";
						break;
				}
			}
            else
            {
				switch (_currentLanguage)
				{
					case "en":
						msg = "Delete field Fail.";
						break;
					case "zh":
						msg = "欄位刪除失敗";
						break;
					default:
						msg = "欄位刪除失敗";
						break;
				}
			}

            result.Message = msg;
            return result;
		}


		/// <summary>
		/// 刪除儲存庫,實際隱藏 ajax
		/// </summary>
		/// <param name="vault_id"></param>
		/// <param name="merchant_id"></param>
		/// <param name="field_id"></param>
		/// <returns></returns>
		[Authorize(Policy = "AdminOnly")]
		[HttpPost]
		public async Task<ResultModel> DelVault(int vault_id, int merchant_id)
        {
			var result = new ResultModel();
			var vault = new TokenVault();
			var msg = "";
			string token = User.FindFirstValue("token");
			var httpMethod = HttpMethod.Post;

			#region call api /v2/vault/get 取的要刪除的vault
			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)
			{
				try
				{
					var response = JsonConvert.DeserializeObject<Response>(apiResult.Data.ToString());
					if (response.r == 0)
					{
						var vaultInfoList = JsonConvert.DeserializeObject<List<TokenVault>>(response.info.ToString());
                        vault = vaultInfoList[0];
					}
					else
					{
						result.IsSuccess = false;
						result.Message = response.m.ToString();
						return result;
					}
				}
				catch (Exception ex)
				{
					result.IsSuccess = false;
					result.Message = ex.Message;
					return result;
				}
			}
			else
			{
				result.IsSuccess = false;
				result.Message = apiResult.Message;
				return result;
			}
			#endregion

			#region call api /v2/vault 編輯商家儲存庫
			url = _config["IP"] + "/v2/vault";
			var currentUnix = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
			var modData = new
			{
				name = vault.name + "_DeleteOn" + currentUnix,
				desc = vault.desc??"",
				type = vault.type,
				enabled = 0
			};
			parameters = new Dictionary<string, string>
			{
				{ "Merchant_id", merchant_id.ToString()},
				{ "id", vault_id.ToString()},
				{ "info", "INFO"},
				{ "data", JsonConvert.SerializeObject(modData)},
			};
			apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
			if (apiResult.IsSuccess)
			{
				try
				{
					var response = JsonConvert.DeserializeObject<Response>(apiResult.Data.ToString());
					if (response.r == 0)
					{
						switch (_currentLanguage)
						{
							case "zh":
								msg = "存儲庫刪除成功";
								break;
							case "en":
								msg = "Delete vault success.";
								break;
							default:
								msg = "Delete vault success.";
								break;
						}
						result.IsSuccess = true;
						result.Message = msg;
						return result;
					}
					else
					{
						result.IsSuccess = false;
						result.Message = response.m.ToString();
						return result;
					}
				}
				catch (Exception ex)
				{
					result.IsSuccess = false;
					result.Message = ex.Message;
					return result;
				}
			}
			else
			{
				result.IsSuccess = false;
				result.Message = apiResult.Message;
				return result;
			}
			#endregion
		}
	}


}


