using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bailun.ServiceFabric.Authorize;
using Bailun.ServiceFabric.Core.Extension;
using Bailun.ServiceFabric.Core.Extension.HttpContext;
using Bailun.ServiceFabric.Extension;
using Microsoft.AspNetCore.Mvc;

namespace Bailun.DC.Web.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            //var users = new List<int> { 681,690,691,693,720,731,2346};
            //var codes = new List<Tuple<string, string>>() {
            //    new Tuple<string, string>("ExportLogicWarehouse","逻辑仓库"),
            //    new Tuple<string, string>("ExportInventoryAging","库龄"),
            //    new Tuple<string, string>("ExportListOrderDetail","订单明细导出"),
            //    new Tuple<string, string>("ExportPlatformCost","平台费导出"),
            //    new Tuple<string, string>("ExportListReturn","退款流水导出"),
            //    new Tuple<string, string>("ExportAmazonAD","亚马逊广告费"),
            //    new Tuple<string, string>("ExportEbayInnerCodeProfit","Ebay内部商品编码利润"),
            //    new Tuple<string, string>("ExportEbayAdFee","Ebay广告费"),
            //    new Tuple<string, string>("ExportIndex","资产负债表"),
            //    new Tuple<string, string>("ExportListInterestExpense","管理成本"),
            //    new Tuple<string, string>("ExportAdministrativeCost","管理成本明细"),
            //    new Tuple<string, string>("ExportUnReasonable","进销存差异明细"),
            //    new Tuple<string, string>("ExportSkuDiffWeigh","Sku发货差异")
            //};


            //var list = new List<Bailun.DC.Models.dc_base_user_authoritys>();
            //foreach (var u in users)
            //{
            //    foreach (var code in codes)
            //    {
            //        var m = new Bailun.DC.Models.dc_base_user_authoritys {
            //            code = code.Item1,
            //            notes = code.Item2,
            //            createtime = DateTime.Now,
            //            has_export = 1,
            //            userid = u
            //        };

            //        list.Add(m);
            //    }
            //}

            //new Services.UserAuthorityServices().Add(list);

            
            return View();
        }

        [HttpPost]
        public JsonResult SetCookie(string token)
        {
            if (!string.IsNullOrEmpty(token))
            {
                HttpContext.Response.Cookies.Append("BailunToken", token, new Microsoft.AspNetCore.Http.CookieOptions() { Expires = DateTime.Now.AddDays(1) });

                return Json(new {
                    success = true,
                    msg = "",
                });
            }
            

            return Json(new {
                success = false,
                msg = "请重新登录"
            });
        }

        public ActionResult Main()
        {


#if DEBUG
            var cookie = "Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjdhZDA5MjQ5ZDk0ZDgxN2VhNmI5ZThhMTc1MzlmNmY3IiwidHlwIjoiSldUIn0.eyJuYmYiOjE2MDAwNTAwNDcsImV4cCI6MTYwMDA4NjA0NywiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAxIiwiYXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6NTAwMS9yZXNvdXJjZXMiLCJiYWlsdW5BcGkiXSwiY2xpZW50X2lkIjoiYmFpbHVuQ2xpZW50Iiwic3ViIjoi5YWz5oyv5bGxIiwiYXV0aF90aW1lIjoxNjAwMDUwMDQ3LCJpZHAiOiJsb2NhbCIsIlVzZXJJZCI6IjIzNDYiLCJzdWNlc3NzIjoidHJ1ZSIsIkNvbXBhbnkiOiJ7XCJJZFwiOjEsXCJDb21wYW55Q29kZVwiOlwiYmFpbHVuXCIsXCJDb21wYW55TmFtZVwiOlwi5bm_5bee55m-5Lym5L6b5bqU6ZO-5pyJ6ZmQ5YWs5Y-4XCJ9IiwiQWxsQ29tcGFueSI6IkZhbHNlIiwiVXNlckNvZGVOZXciOiJCTDExNjkiLCJVc2VyQ29kZSI6IkJMMTE3MCIsIk9hVXNlcklkIjoiMjM0NiIsIkRlcGFydG1lbnQiOiJ7XCJEZXBhcnRtZW50SWRcIjoyNTgsXCJOYW1lXCI6XCLmlbDmja7kuK3lv4NcIixcIkNvZGVcIjpcIlwifSIsInNjb3BlIjpbIm9wZW5pZCIsInByb2ZpbGUiLCJiYWlsdW5BcGkiXSwiYW1yIjpbImN1c3RvbSJdfQ.M2S1aNkyns2yQPt-itQZhNYhhJI4vSfMtfmV9kH-0ufOW9xGnNvf0j949p_zi3JkCejVAKoR1yO7luHkiolfvwtwAlX0yzWeiX41myHo3f8eAH42lnmfUB7CuKkDFVn9wc0sgRbHPIYO3E1Xhd3colgblF6T-9XC9Xvau46-pZw8uvoeIo-FC79aBX8LoDgsamxN2tDKTuE0fjuFosXtPHQgm2oZUdsTpyHyLYAlGO6a6DUB3ZpjoUVu6SGi3NRxuX7jEzCoMkr4XM5soRDRgjIZq9TgGEehr4en3MRHRdQ03KaxR_sgpGip0dNvm0kWARlvh049Yn6tjCJ2jzVQTw";
#else
            //var user = Common.HttpHelper.NetHelper.Request("http://sso.bailuntec.com/GetUserResource");
            var cookie = HttpContext.Request.Cookies["BailunToken"];
#endif
            
            //var companyid = -1;
            //var departmentname = "";
            //var username = "";
            //var userid = 0;
            //var isAllCompany = 0;


            //var user = Common.HttpHelper.NetHelper.Request("http://sso.bailuntec.com/GetUserResource", new string[] { "Authorization" }, new string[] { (cookie != null ? System.Net.WebUtility.UrlDecode(cookie) : "") });

            //var json = Newtonsoft.Json.Linq.JObject.Parse(user);
            //if (json["statusCode"].ToStr() == "200" && json["result"]["success"].ToString().ToLower() == "true")
            //{
            //    username = json["result"]["Account"].ToString();
            //    //userid = json["result"]["UserId"].ToInt32();
            //    userid = json["result"]["OaUserId"].ToInt32();
            //    isAllCompany = json["result"]["AllCompany"].ToStr().ToLower() == "false" ? 0 : 1;
            //    int.TryParse(json["result"]["Company"]["Id"].ToString(), out companyid);
            //    if (json["result"]["Department"].ToString() != "null" && json["result"]["Department"].ToString() != "")
            //    {
            //        departmentname = json["result"]["Department"]["Name"].ToStr();
            //    }
            //}
            //else
            //{
            //    //HttpContext.Response.Cookies["token"].Expires.AddDays(-1);
            //}

            //ViewBag.companyid = companyid;
            //ViewBag.allcompany = isAllCompany;
            //ViewBag.username = username;
            //ViewBag.departmentname = departmentname;

            //HttpContext.Response.Cookies.Append("companyid", companyid + "", new Microsoft.AspNetCore.Http.CookieOptions
            //{
            //    Expires = DateTime.Now.AddDays(1)
            //});


            ////var listMenu = new Services.MenuServices().ListMenu(username);
            //var listMenu = new Services.MenuServices().ListMenu(userid);
            //ViewBag.menus = listMenu;

            return View();
        }

        /// <summary>
        /// 获取用户菜单
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListMenu(int userid)
        {
            var listMenu = new Services.MenuServices().ListMenu(userid);

            return Json(listMenu);
        }
        
        /// <summary>
        /// 无权访问提示页面
        /// </summary>
        /// <returns></returns>
        public ActionResult NoPermission()
        {
            return View();
        }

        [HttpPost]
        public JsonResult ListWarehouseType()
        {
            var result = new Services.WareHouseServices().ListWareHouseType().Where(a=>!string.IsNullOrEmpty(a));
            return Json(result);
        }

        /// <summary>
        /// 获取仓库列表
        /// </summary>
        /// <param name="warehousetype"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListWareHouse(string warehousetype,int? areaid)
        {
            var result = new Services.WareHouseServices().List(warehousetype,areaid);

            var list = result.Select(p => new {
                p.warehouse_code,
                p.warehouse_name
            });

            return Json(list);
        }

        /// <summary>
        /// 获取sku分类列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListSkuCategory()
        {
            var result = new Services.SkuInfoServices().ListSkuCategory();
            return Json(result);
        }

        /// <summary>
        /// 根据仓库自设置属性获取仓库列表
        /// </summary>
        /// <param name="type">自发货仓或第三方仓</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListWarehouseByExtType(string type)
        {
            var result = new Services.WareHouseServices().ListWarehouseByExtType(type);

            var list = result.Select(p => new {
                code = p.warehouse_code,
                name =  p.warehouse_name
            });

            return Json(list);
        }

        /// <summary>
        /// 获取仓库所在国家列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListWarehouseArea()
        {
            var result = new Services.WareHouseServices().ListWarehouseArea().Where(a=>a.id>0);

            return Json(result);
        }

        /// <summary>
        /// 数据仓分组列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListGroupName()
        {
            var result = new Services.WareHouseServices().ListGroupName().Where(a=>!string.IsNullOrEmpty(a));
            return Json(result);
        }

        [HttpPost]
        public JsonResult ListWarehouseFromStockAndSales(string warehousetype)
        {
            var result = new Services.WareHouseServices().ListWarehouseFromStockAndSales(warehousetype);
            return Json(result);
        }

        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult GetUserInfo()
        {
            var userid = HttpContextHelper.Current?.User?.GetUid().ToStr();
            var username = HttpContextHelper.Current.User.GetUserName();
            var jobs = ""; //HttpContextHelper.Current.User.GetRolesCode();
            var companyid = HttpContextHelper.Current.User.GetCompanyId();

            return Json(new
            {
                success = true,
                userid = userid,
                username = username,
                jobs = jobs,
                companyid = companyid
            });

        }

        /// <summary>
        /// 获取简单百伦一二级分类
        /// </summary>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult ListSimpleCategory()
        {
            var companyid = HttpContextHelper.Current.User.GetCompanyId().ToInt32();

            if (companyid != 1)
            {
                return Json("{}");
            }

            var obj = new Services.SkuInfoServices().ListSimpleCategory12(companyid);
            return Json(obj);
        }

    }
}