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;

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

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

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



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

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


            }
            ViewBag.Merchant_id = merchantId;

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

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

                };

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

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

            #endregion
            return View();




        }


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

                };

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

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

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

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


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

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

                };

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

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

                        };

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

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

                    }
                    #endregion


                  

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


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

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


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

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

                };

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

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

                        };

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

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

                    }
                    #endregion




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


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


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


            }



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

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


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

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

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

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

                    else
                    {
                        return Ok();
                    }

                }
                else
                {
                    return Ok();
                }

            }
            else
            {
                return Ok();
            }

        }

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

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

                };

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

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

            #endregion
            return View();
        }

        [HttpGet("/TokenVault/Edit/{id}")]

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

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

                };

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

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

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

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

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

                }
            }


            return View();
        }

        [HttpPost]
        public async Task<IActionResult> CreateTokenVault(DepartmentForCreate department)
        {
            var url = _config["IP"] + "/tsp/merchant/vault/add";
            // 確認使用者是否已經登入
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Login");

            }
            if (string.IsNullOrEmpty(department.name))
            {
                ModelState.AddModelError("name", "名稱不能為空");
            }
            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);
                    #region 取得部門列表
                    var DepartmentsResponse = new DepartmentsResponse();
                    url = _config["IP"] + "/merchant/list";
                    httpMethod = HttpMethod.Post;
                    // 取得使用者的 "token" Claim 值

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

                };

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

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

                    #endregion
                    return View(department);
                }


            }



            return View();
        }


    }


}


