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

        public ActionResult Main()
        {
            var companyid = -1;
            var departmentname = "";
            var username = "";
            var userid = 0;
            var isAllCompany = 0;

            //var user = Common.HttpHelper.NetHelper.Request("http://sso.bailuntec.com/GetUserResource");
            var cookie = HttpContext.Request.Cookies["token"];
            var user = Common.HttpHelper.NetHelper.Request("http://sso.bailuntec.com/GetUserResource",new string[] { "Authorization" },new string[] { (cookie != null ? 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();
                isAllCompany = json["result"]["AllCompany"].ToStr().ToLower() == "false" ? 0 : 1;
                int.TryParse(json["result"]["Company"]["Id"].ToString(), out companyid);
                if (json["result"]["Department"].ToString() != "null")
                {
                    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>
        /// <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);
        }

    }
}