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.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 TokenVault_management.Models;
using Microsoft.Extensions.Localization;
using Microsoft.AspNetCore.Localization;
using System.Text.Json;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Spreadsheet;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace backstage.Controllers
{

    public class UserController : Controller
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IConfiguration _config;
        private readonly ICallApi _callApi;
        private readonly IStringLocalizer<UserController> _localizer;

        private readonly string _currentLanguage;

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

        public UserController(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;

        }



        [HttpGet]
        public async Task<IActionResult> Login()
        {

            return View();

        }



        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(User user, string returnUrl)
        {
            logger.Info("test");
            if (!ModelState.IsValid)
            {
                return View(user);
            }
            if (string.IsNullOrEmpty(user.username))
            {
                string msg;
                switch (_currentLanguage)
                {

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

                }

                ModelState.AddModelError("username", _localizer["username"] + msg);
            }
            if (string.IsNullOrEmpty(user.pwd))
            {
                string msg;
                switch (_currentLanguage)
                {

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

                }
                ModelState.AddModelError("pwd", _localizer["password"] + msg);
            }

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

            var u = new UserLogin();


            var url = _config["IP"];
            var parameters = new Dictionary<string, string>
              {
                    { "username", user.username },
                    { "pwd", user.pwd },
                    { "reqPermFlag[0]","admin-login"}
              };
            var httpMethod = HttpMethod.Post;
            int maxTry = 2;
            int currentTry = 0;

            while (currentTry < maxTry)
            {
                try
                {
                    var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);

                    if (apiResult.IsSuccess)
                    {
                        // API 呼叫成功，進行相應的處理

                        u = JsonConvert.DeserializeObject<UserLogin>(apiResult.Data.ToString());
                        if (u.r == 0 && !string.IsNullOrEmpty(u.token))
                        {
                            string role = "";
                            if (user.username == "theone")
                            {
                                role = "Admin";
                            }
                            else
                            {

                                #region admin/list
                                url = _config["IP"] + "/admin/list";
                                httpMethod = HttpMethod.Post;
                                var types = new[] { "admin" };
                                var types_data = new { inc = types };
                                role = "Merchant";

                                parameters = new Dictionary<string, string>
                              {
                                    { "token", u.token },
                                    { "types", JsonConvert.SerializeObject(types_data)},

                                };

                                apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
                                var adminResponse = new UserResponse();
                                if (apiResult.IsSuccess)
                                {

                                    adminResponse = JsonConvert.DeserializeObject<UserResponse>(apiResult.Data.ToString());
                                    if (adminResponse.r == 0)
                                    {
                                        var existAdmin = adminResponse.Users.Where(u => u.username == user.username).FirstOrDefault();
                                        if (existAdmin != null)
                                        {
                                            if (existAdmin.enabled == 1)
                                                role = "Admin";
                                        }
                                    }



                                }
                                #endregion
                            }

                            

                            #region 寫入TOKEN
                            int LoginExpireMinute = Convert.ToInt32(_config["LoginExpireMinute"]);
                            string key = _config["TokenKey"];

                            var Cookieoptions = new CookieOptions();
                            ////時間一到就會把Token從Cookie洗掉,如果Expires沒比API的Expires長,則每次Token過期都須重新登入
                            Cookieoptions.Expires = DateTime.Now.AddMinutes(LoginExpireMinute);
                            //Cookieoptions.SameSite = SameSiteMode.Strict;
                            Cookieoptions.HttpOnly = true;

                            var userClaims = new ClaimsIdentity(new[]
                                        {
                           new Claim("username", user.username),
                            new Claim("token", u.token),
                            new Claim(ClaimTypes.Role, role),

                             }, CookieAuthenticationDefaults.AuthenticationScheme);

                            //將 ClaimsIdentity 設定給 ClaimsPrincipal (持有者) 
                            ClaimsPrincipal principal = new ClaimsPrincipal(userClaims);
                            //登入動作
                            try
                            {

                                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties()
                                {
                                    //是否可以被刷新
                                    AllowRefresh = true,
                                    // 設置了一個 1 天 有效期的持久化 cookie
                                    IsPersistent = true, //IsPersistent = false，瀏覽器關閉即刻登出
                                                            //用戶頁面停留太久，逾期時間，在此設定的話會覆蓋Startup.cs裡的逾期設定
                                    ExpiresUtc = DateTime.Now.AddMinutes(LoginExpireMinute),


                                });
                                
                                return RedirectToAction("Index", "Home");
                            }
                            catch (Exception ex)
                            {
                                logger.Trace(ex.Message + ex.InnerException?.Message);
                            }
                            #endregion


                            
                        }
                        else if (u.r == 65796)
                        {

                            currentTry++;
                            parameters["reqPermFlag[0]"] = "merchant-login";
                            continue;
                        }
                        else
                        {


                            TempData["IsSuccess"] = false;
                            TempData["msg"] = u.m;

                            return View(apiResult.Message);
                        }

                    }
                    else
                    {
                        // API 呼叫失敗，進行相應的錯誤處理
                        logger.Debug(apiResult.Message);
                        return BadRequest(apiResult.Message);
                    }
                }
                catch (Exception ex)
                {
                    // 處理 API 呼叫發生的例外狀況
                    logger.Debug(ex.Message);
                    return StatusCode(500, $"API 呼叫發生錯誤：{ex.Message}");
                }
            }



            TempData["IsSuccess"] = false;
            TempData["msg"] = "發生錯誤";
            logger.Debug("login error");
            return View();


        }


        [Authorize(Policy = "AdminOnly")]
        [HttpGet]
        public async Task<IActionResult> ListUsers()
        {
            var UserResponse = new UserResponse();



            // 取得使用者的 "token" Claim 值
            string token = User.FindFirstValue("token");
            #region user/list
            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"}
                    //{ "types", "{\"inc\":[\"all\"]}"}

                };

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

            }
            #endregion

            #region admin/list
            url = _config["IP"] + "/admin/list";
            httpMethod = HttpMethod.Post;
            types = new[] { "admin" };
            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);
            var adminResponse = new UserResponse();
            if (apiResult.IsSuccess)
            {
                adminResponse = JsonConvert.DeserializeObject<UserResponse>(apiResult.Data.ToString());

            }
            #endregion

            var adminCount = 0;
            if (adminResponse.r == 0)
            {
                if (adminResponse.userCount > 0)
                {
                    foreach (var a in adminResponse.Users)
                    {
                        if (a.enabled == 1)
                        {
                            adminCount++;
                        }
           
						foreach (var v in UserResponse.Users)
                        {
                            if (v.uid == 1)
                                v.isAdmin = true;
                            if (a.uid == v.uid && a.enabled == 1)
                                v.isAdmin = true;

                        }
                    }
                }
            }
            ViewBag.adminCount = adminCount;
            ViewBag.userCount = UserResponse.userCount;
            return View(UserResponse);




        }

        [Authorize]
        [HttpGet("/User/GetUser/{uid}")]
        public async Task<IActionResult> GetUser(int uid)
        {
            var url = _config["IP"] + "/user/get";


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

            var types = new string[] { "merchant", "admin", "user" }; // 陣列中的不同 type 值
            var parameters = new Dictionary<string, string>
              {
                    { "token", token },
                { "type","merchant"},
                { "uid",uid.ToString()}

             };



            int maxRetries = types.Length; // 最大重試次數
            int currentRetry = 0; // 目前重試次數

            while (currentRetry < maxRetries)
            {
                var currentIndex = Array.IndexOf(types, parameters["type"]); // 取得當前 type 的索引
                var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
                if (apiResult.IsSuccess)
                {


                    try
                    {
                        var GetUserResponse = JsonConvert.DeserializeObject<GetUserResponse>(apiResult.Data.ToString());
                        if (GetUserResponse.r == 0)
                        {
                            if (!string.IsNullOrEmpty(GetUserResponse.user.username))
                            {
                                //var user = new User();
                                //user.name = GetUserResponse.user.name;
                                //user.username = GetUserResponse.user.username;
                                if (GetUserResponse.email != null)
                                    GetUserResponse.user.email = GetUserResponse.email;
                                // 使用 JSON 解析工具將 JSON 字串轉換為物件
                                //var jsonObject = JsonConvert.DeserializeObject<Dictionary<string, string>>(apiResult.Data.ToString());

                                GetUserResponse.user.uid = uid;

                                //user.created_date = DateTime.Parse(jsonObject["created_date"]);
                                return View(GetUserResponse.user);
                            }
                        }
                        else
                        {
                            string msg;
                            switch (_currentLanguage)
                            {

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

                            }
                            TempData["IsSuccess"] = false;
                            TempData["msg"] = "";
                            return RedirectToAction("ListUsers");
                        }
                    }
                    catch (Exception e)
                    {
                        currentRetry++; // 增加重試次數
                                        // 如果 type 不是最後一個陣列元素，則將 type 更改為下一個值
                        if (currentIndex < types.Length - 1)
                        {
                            parameters["type"] = types[currentIndex + 1];
                        }
                    }
                }
            }



            return View();
        }

        /// <summary>
        /// 修改密碼
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpGet]
        public async Task<IActionResult> ChangePassword(string username, string returnUrl)
        {
            string msg = string.Empty;
            var url = _config["IP"] + "/user/list";
            ViewBag.returnUrl = returnUrl;

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

            var types = new[] { "all" };
            var types_data = new { inc = types };
            var parameters = new Dictionary<string, string>
              {
                    { "token", token },
                { "types",JsonConvert.SerializeObject( types_data)}

             };


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


                try
                {
                    var UserResponse = JsonConvert.DeserializeObject<UserResponse>(apiResult.Data.ToString());
                    if (UserResponse.r == 0)
                    {
                        if (UserResponse.userCount > 0)
                        {
                            var existUser = UserResponse.Users.Where(u => u.username == username).FirstOrDefault();
                            if (existUser == null)
                            {

                                switch (_currentLanguage)
                                {

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

                                }
                                TempData["IsSuccess"] = false;
                                TempData["msg"] = msg;
                                return Redirect("~" + returnUrl);
                            }
                            else
                            {
                                return View(existUser);
                            }
                        }
                        switch (_currentLanguage)
                        {

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

                        }
                        TempData["IsSuccess"] = false;
                        TempData["msg"] = msg;
                        return Redirect("~" + returnUrl);


                    }
                    else if (UserResponse.r == 65537)
                    {

                    }
                    else
                    {
                        switch (_currentLanguage)
                        {

                            case "en":
                                msg = "Error.";
                                break;
                            case "zh":
                                msg = "發生錯誤";
                                break;
                            default:
                                msg = "發生錯誤";
                                break;

                        }
                        TempData["IsSuccess"] = false;
                        TempData["msg"] = msg;
                        return RedirectToAction(returnUrl);
                    }
                }
                catch (Exception e)
                {
                    TempData["IsSuccess"] = false;
                    TempData["msg"] = e.Message;
                    return Redirect("~" + returnUrl);
                }
            }

            switch (_currentLanguage)
            {

                case "en":
                    msg = "Error.";
                    break;
                case "zh":
                    msg = "發生錯誤";
                    break;
                default:
                    msg = "發生錯誤";
                    break;

            }
            TempData["IsSuccess"] = false;
            TempData["msg"] = msg;
            return Redirect("~" + returnUrl);


        }

        [Authorize]
        [HttpPost]
        public async Task<IActionResult> ChangePassword(User user, string returnUrl)
        {
            var url = _config["IP"] + "/admin/changepassword";
            string msg;
            if (string.IsNullOrEmpty(user.password))
            {
                switch (_currentLanguage)
                {

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

                }
                ModelState.AddModelError("Password", msg);
            }

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


            var parameters = new Dictionary<string, string>
              {
                    { "token", token },
                { "newpwd",user.newPassword}

                };
            var 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 = "Change password success.";
                            break;
                        case "zh":
                            msg = "更改密碼成功";
                            break;
                        default:
                            msg = "更改密碼成功";
                            break;

                    }
                    TempData["IsSuccess"] = true;
                    TempData["msg"] = msg;
                    return RedirectToAction("ListUsers");
                }
                else
                {
                    TempData["IsSuccess"] = false;
                    TempData["msg"] = JsonConvert.SerializeObject(userAddResponse.m);
                    return RedirectToAction("GetUser", new { uid = user.uid });
                }


            }



            return View();
        }

        [Authorize(Policy = "AdminOnly")]
        [HttpGet]
        public async Task<IActionResult> CreateUser()
        {
            return View();
        }

        [Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<IActionResult> CreateUser(User user)
        {
            var url = _config["IP"] + "/user/add";
            string msg;
            if (string.IsNullOrEmpty(user.password))
            {

                switch (_currentLanguage)
                {

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

                }
                ModelState.AddModelError("password", _localizer["password"] + msg);
            }
            if (string.IsNullOrEmpty(user.name))
            {

                switch (_currentLanguage)
                {

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

                }
                ModelState.AddModelError("name", _localizer["name"] + msg);
            }

            if (string.IsNullOrEmpty(user.username))
            {

                switch (_currentLanguage)
                {

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

                }
                ModelState.AddModelError("username", _localizer["username"] + msg);
            }

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


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

                };
            var 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 user success.";
                            break;
                        case "zh":
                            msg = "新增使用者成功";
                            break;
                        default:
                            msg = "新增使用者成功";
                            break;

                    }
                    TempData["IsSuccess"] = true;
                    TempData["msg"] = msg;
                    return RedirectToAction("ListUsers");
                }
                else
                {
                    TempData["IsSuccess"] = false;
                    TempData["msg"] = JsonConvert.SerializeObject(userAddResponse.m);
                    return View(user);
                }


            }



            return View();
        }

        /// <summary>
        /// 編輯使用者
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        public async Task<IActionResult> GetUser(User user)
        {

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

            #region user/list
            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"}
                    //{ "types", "{\"inc\":[\"all\"]}"}

                };

            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.uid).FirstOrDefault();
                    if (existUser == null)
                    {
                        return RedirectToAction("ListUsers");
                    }

                    //檢查name 
                    if (string.IsNullOrEmpty(user.name))
                    {

                        switch (_currentLanguage)
                        {

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

                        }
                        ModelState.AddModelError("name", msg);
                    }
                    var existName = UserResponse.Users.Where(u => u.name == user.name).FirstOrDefault();
                    if (existName != null)
                    {
                        if (existName.uid != user.uid)
                        {

                            switch (_currentLanguage)
                            {
                                case "en":
                                    msg = " exist.";
                                    break;
                                case "zh":
                                    msg = "重複";
                                    break;
                                default:
                                    msg = "重複";
                                    break;
                            }
                            ModelState.AddModelError("name", msg);
                        }
                    }
                    //檢查username 
                    if (string.IsNullOrEmpty(user.username))
                    {

                        switch (_currentLanguage)
                        {
                            case "en":
                                msg = " can't be empty.";
                                break;
                            case "zh":
                                msg = "不得空白";
                                break;
                            default:
                                msg = "不得空白";
                                break;
                        }
                        ModelState.AddModelError("username", msg);
                    }
                    var existUserName = UserResponse.Users.Where(u => u.username == user.username).FirstOrDefault();
                    if (existUserName != null)
                    {
                        if (existUserName.uid != user.uid)
                        {

                            switch (_currentLanguage)
                            {

                                case "en":
                                    msg = " exist.";
                                    break;
                                case "zh":
                                    msg = "重複";
                                    break;
                                default:
                                    msg = "重複";
                                    break;

                            }
                            ModelState.AddModelError("username", "");
                        }
                    }

                    if (!ModelState.IsValid)
                    {
                        return View(user);
                    }
                    //檢查通過
                    //修改基本資料
                    existUser.name = user.name;
                    existUser.username = user.username;

                    url = _config["IP"] + "/user/mod";


                    parameters = new Dictionary<string, string>
                      {
                            { "token", token },
                            { "data", JsonConvert.SerializeObject(existUser)}
                            //{ "types", "{\"inc\":[\"all\"]}"}

                        };

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

                        switch (_currentLanguage)
                        {

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

                        }
                        TempData["IsSuccess"] = true;
                        TempData["msg"] = msg;

                        //修改密碼
                        if (!string.IsNullOrEmpty(user.newPassword))
                        {
                            var u = new UserLogin();
                            string user_token = "";

                            url = _config["IP"];
                            parameters = new Dictionary<string, string>
                              {
                                    { "username", user.username },
                                    { "pwd", user.password },
                                    { "reqPermFlag[0]","merchant-login"}
                              };
                            apiResult = await _callApi.CallAPI(url, parameters, httpMethod);

                            if (apiResult.IsSuccess)
                            {
                                // API 呼叫成功，進行相應的處理

                                u = JsonConvert.DeserializeObject<UserLogin>(apiResult.Data.ToString());
                                if (u.r == 0 && !string.IsNullOrEmpty(u.token))
                                {
                                    user_token = u.token;
                                    existUser.password = user.newPassword;
                                    url = _config["IP"] + "/user/changepassword";

                                    parameters = new Dictionary<string, string>
                                    {
                                            { "token", user_token },
                                        { "oldpwd",user.password},
                                        { "newpwd",user.newPassword}

                                      };

                                    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;

                                        }
                                        else
                                        {


                                            TempData["IsSuccess"] = false;
                                            TempData["msg"] = response.r + "," + response.m;
                                            return RedirectToAction("GetUser", new { uid = user.uid });
                                        }
                                        return RedirectToAction("ListUsers");
                                    }
                                    TempData["IsSuccess"] = false;
                                    TempData["msg"] = apiResult.Message;
                                    return RedirectToAction("GetUser", new { uid = user.uid });
                                }
                                TempData["IsSuccess"] = false;
                                TempData["msg"] = u.r + "," + u.m.ToString();
                                return RedirectToAction("GetUser", new { uid = user.uid });
                            }
                            TempData["IsSuccess"] = false;
                            TempData["msg"] = apiResult.Message;
                            return RedirectToAction("GetUser", new { uid = user.uid });

                        }



                        return RedirectToAction("ListUsers");
                    }

                }

            }
            //查無使用者

            switch (_currentLanguage)
            {
                case "en":
                    msg = "User is not exist.";
                    break;
                case "zh":
                    msg = "查無使用者";
                    break;
                default:
                    msg = "查無使用者";
                    break;
            }
            TempData["IsSuccess"] = false;
            TempData["msg"] = "查無使用者";
            return RedirectToAction("ListUsers");
            #endregion



        }

        [Authorize]
        [HttpGet]
        public async Task<IActionResult> ListDepartments()
        {
            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)
                {
                    return View(DepartmentsResponse);
                }*/
                var merchants = new List<Department>();
                if(DepartmentsResponse.merchants != null)
                {
                    merchants = DepartmentsResponse.merchants?.Where(x => x.enabled == 1).ToList();
                }
                

                
				return View(merchants);

            }

            return Ok(apiResult.Data.ToString());


        }

        [Authorize(Policy = "AdminOnly")]
        [HttpGet("/User/GetDepartment/{id}")]
        public async Task<IActionResult> GetDepartment(int id)
        {
            var url = _config["IP"] + "/merchant/get";


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


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

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

                    return View(DepartmentsResponse.merchant);

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


            }



            return View();
        }

        [Authorize(Policy = "AdminOnly")]
        [HttpGet]
        public async Task<IActionResult> CreateDepartment()
        {
            return View();
        }

        [Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<IActionResult> CreateDepartment(DepartmentForCreate department)
        {
            var url = _config["IP"] + "/merchant/add";
            string msg;
            if (string.IsNullOrEmpty(department.name))
            {

                switch (_currentLanguage)
                {

                    case "en":
                        msg = "can't be empty.";
                        break;
                    case "zh":
                        msg = "部門名稱不能為空";
                        break;
                    default:
                        msg = "部門名稱不能為空";
                        break;

                }
                ModelState.AddModelError("name", msg);
            }
            if (string.IsNullOrEmpty(department.phone))
            {
                department.phone = "null";
            }

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



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

                };
            var 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"] = "新增部門成功";
                    return RedirectToAction("ListDepartments");
                }
                else
                {
                    TempData["IsSuccess"] = false;
                    TempData["msg"] = JsonConvert.SerializeObject(userAddResponse.m);
                    return View(department);
                }


            }



            return View();
        }


        [Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<IActionResult> EditDepartment(Department department)
        {
            var url = _config["IP"] + "/merchant/mod";
            string msg;
            if (string.IsNullOrEmpty(department.name))
            {

                switch (_currentLanguage)
                {

                    case "en":
                        msg = "can't be empty.";
                        break;
                    case "zh":
                        msg = "部門名稱不能為空";
                        break;
                    default:
                        msg = "部門名稱不能為空";
                        break;

                }
                ModelState.AddModelError("name", msg);
            }
            if (string.IsNullOrEmpty(department.phone))
            {
                department.phone = "null";
            }

            var httpMethod = HttpMethod.Post;
            // 取得使用者的 "token" Claim 值
            string token = User.FindFirstValue("token");
            var data = new
            {
                name = department.name,
                address = "null",
                countryid = "Taiwan",
                postcode = "123",
                phone = "null",
                name_en = "null",
                VATID_verify = "1",
                enabled = 1
            };


            var parameters = new Dictionary<string, string>
            {
                { "token", token },
                { "merchant",JsonConvert.SerializeObject(data)},
                { "uid",department.merchant_id.ToString()}

            };
            var 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 = "Edit department success.";
                            break;
                        case "zh":
                            msg = "編輯部門成功";
                            break;
                        default:
                            msg = "編輯部門成功";
                            break;

                    }


                    TempData["IsSuccess"] = true;
                    TempData["msg"] = msg;
                    return RedirectToAction("ListDepartments");
                }
                else
                {
                    TempData["IsSuccess"] = false;
                    TempData["msg"] = JsonConvert.SerializeObject(userAddResponse.m);
                    return RedirectToAction("ListDepartments");
                }

            }



            return RedirectToAction("ListDepartments");
        }

		/// <summary>
		/// 部門刪除，實際上是隱藏 ajax
		/// </summary>
		/// <param name="merchant_id"></param>
		/// <returns></returns>
		[Authorize(Policy = "AdminOnly")]
		[HttpPost]
		public async Task<ResultModel> DelDepartment(int merchant_id)
        {
            var result = new ResultModel();
            var merchant = new Department();
            var msg = "";
			string token = User.FindFirstValue("token");
			var httpMethod = HttpMethod.Post;

            #region call api get merchant
			var url = _config["IP"] + "/merchant/get";

			var parameters = new Dictionary<string, string>
			{
				{ "token", token },
				{ "merchant_id", merchant_id.ToString()}
			};
			var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
			if (apiResult.IsSuccess)
			{
                try
                {
					var departmentsResponse = JsonConvert.DeserializeObject<DepartmentsResponse>(apiResult.Data.ToString());
					if (departmentsResponse.r == 0)
					{
                        merchant = departmentsResponse.merchant;
					}
					else
					{
						result.IsSuccess = false;
						result.Message = departmentsResponse.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 mod merchant
			url = _config["IP"] + "/merchant/mod";
            var currentUnix = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
			var modData = new
            {
                name = merchant.name + "_DeleteOn" + currentUnix,
                name_en = merchant.name_en,
                address = merchant.address,
				countryid = merchant.country_id,
				postcode = merchant.postcode,
				phone = merchant.phone,
				enabled = 0
			};
			parameters = new Dictionary<string, string>
			{
				{ "token", token },
				{ "uid", merchant_id.ToString()},
				{ "merchant", 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 department success.";
								break;
							default:
								msg = "Delete department 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
		}


		/// <summary>
		/// enable做兩件事情,user加入admin,並且enable=true,
		/// disable做一件事情就是enable=false
		/// </summary>
		/// <param name="uid"></param>
		/// <param name="isAdmin"></param>
		/// <returns></returns>
		[Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<ResultModel> AdminAddAjax(int uid, int isAdmin)
        {
            var result = new ResultModel();
            string msg;
            if (uid == 1)
            {

                switch (_currentLanguage)
                {

                    case "en":
                        msg = "This user can't be remove from admin permission.";
                        break;
                    case "zh":
                        msg = "此帳號不得移除Admin";
                        break;
                    default:
                        msg = "此帳號不得移除Admin";
                        break;
                }
                result.IsSuccess = false;
                result.Message = msg;
                return result;
            }
            // 取得使用者的 "token" Claim 值
            string token = User.FindFirstValue("token");

            var url = _config["IP"] + "/admin/add";
            var httpMethod = HttpMethod.Post;
            var userData = new[] {

                new {
                    uid=uid,
                    desc="",
                    roles = new[] { 1 },
                    enabled=1

                }
            };
            //檢查是否在admin/list
            var existAdmin = new User();
            #region admin/list
            url = _config["IP"] + "/admin/list";
            httpMethod = HttpMethod.Post;
            var types = new[] { "admin" };
            var types_data = new { inc = types };

            var parameters = new Dictionary<string, string>
              {
                    { "token", token },
                    { "types", JsonConvert.SerializeObject(types_data)}


                };

            var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            var adminResponse = new UserResponse();
            if (apiResult.IsSuccess)
            {
                adminResponse = JsonConvert.DeserializeObject<UserResponse>(apiResult.Data.ToString());
                existAdmin = adminResponse.Users.Where(u => u.uid == uid).FirstOrDefault();

            }
            #endregion

            //加入admin list
            if (existAdmin == null)
            {
                if (isAdmin == 1)
                {
                    url = _config["IP"] + "/admin/add";
                    parameters = new Dictionary<string, string>
                    {
                        { "token", token},
                        { "user",JsonConvert.SerializeObject( userData)}
                    };

                    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 = "Set permission 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;
                    }
                }
                else
                {
                    switch (_currentLanguage)
                    {

                        case "en":
                            msg = "Not admin.";
                            break;
                        case "zh":
                            msg = "非admin";
                            break;
                        default:
                            msg = "非admin";
                            break;

                    }
                    result.IsSuccess = false;
                    result.Message = msg;
                    return result;
                }
            }
            else
            {
                url = _config["IP"] + "/admin/mod";
                httpMethod = HttpMethod.Post;
                existAdmin.enabled = isAdmin;
           
                var data = new { 
                uid= existAdmin.uid,
                admin_role_id= "1",
                enabled=isAdmin
                };
                parameters = new Dictionary<string, string>
                {
                    { "token", token },
                    { "data", JsonConvert.SerializeObject(data)}

                };
                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 = "Set permission 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;
                }

            }

        }



        [Authorize(Policy = "AdminOnly")]
        [HttpPost]
        public async Task<ResultModel> UserEnableAjax(int uid, int enabled)
        {
            var result = new ResultModel();

            // 取得使用者的 "token" Claim 值
            string token = User.FindFirstValue("token");
            string msg;
            if (uid == 1)
            {

                switch (_currentLanguage)
                {

                    case "en":
                        msg = "This user can't be disable.";
                        break;
                    case "zh":
                        msg = "此帳號不得disable";
                        break;
                    default:
                        msg = "此帳號不得disable";
                        break;
                }
                result.IsSuccess = false;
                result.Message = msg;
                return result;
            }
            #region user/list
            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"}
                    //{ "types", "{\"inc\":[\"all\"]}"}

                };

            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 == uid).FirstOrDefault();
                    if (existUser == null)
                    {
                        switch (_currentLanguage)
                        {

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

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


                    }


                    //檢查通過
                    url = _config["IP"] + "/user/mod";

                    var data = new
                    {
                        uid = uid,
                        enabled = enabled
                    };

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

                        };

                    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 = "Set permission success.";
                                    break;
                                case "zh":
                                    msg = "權限調整成功";
                                    break;
                                default:
                                    msg = "權限調整成功";
                                    break;

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

                    }

                    switch (_currentLanguage)
                    {

                        case "en":
                            msg = "Errors occoured.";
                            break;
                        case "zh":
                            msg = "發生錯誤";
                            break;
                        default:
                            msg = "發生錯誤";
                            break;

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



                }
                switch (_currentLanguage)
                {

                    case "en":
                        msg = "Errors occoured.";
                        break;
                    case "zh":
                        msg = "發生錯誤";
                        break;
                    default:
                        msg = "發生錯誤";
                        break;

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

            }


            switch (_currentLanguage)
            {

                case "en":
                    msg = "Errors occoured.";
                    break;
                case "zh":
                    msg = "發生錯誤";
                    break;
                default:
                    msg = "發生錯誤";
                    break;

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

            #endregion



        }

        [HttpGet]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync();

            HttpContext.Response.Cookies.Delete("backstage");

            return RedirectToAction(nameof(Login));
        }

		[Authorize(Policy = "AdminOnly")]
		[HttpGet]
		public async Task<IActionResult> UploadLicense()
		{
			var url = _config["IP"] + "/license/get";
			var httpMethod = HttpMethod.Post;
            var parameters = new Dictionary<string, string>();
			var apiResult = await _callApi.CallAPI(url, parameters, httpMethod);
            if (apiResult.IsSuccess)
            {
                try
                {
                    var licenseResponse = JsonConvert.DeserializeObject<LicenseResponse>(apiResult.Data.ToString());
                    if (licenseResponse.r == 0)
                    {
                        var license = licenseResponse.License;
                        return View(license);
                    }
                }
                catch
                {

                }
            }
			return View(new License());
		}


		[Authorize(Policy = "AdminOnly")]
		[HttpPost]
		public async Task<ResultModel> UploadLicenseAjax(string license)
		{
            var result = new ResultModel();
			var url = _config["IP"] + "/license";
			var httpMethod = HttpMethod.Post;
            var parameters = new Dictionary<string, string>
            {
                { "license", license }
            };
			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 = "License update completed.";
                        return result;
					}
				}
				catch
				{

				}
			}
			result.IsSuccess = false;
			result.Message = "License update fail.";
			return result;
		}

	}
}