using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authorization;

using System.Web;
using MySystem.MainModels;
using LitJson;
using Library;

namespace MySystem.Areas.Api.Controllers.v1
{
    [Area("Api")]
    [Route("Api/v1/[controller]/[action]")]
    public class ProductsController : BaseController
    {
        public ProductsController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
        }




        #region 创客-商城-商品详情
        [Authorize]
        public JsonResult Detail(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = DetailDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> DetailDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            Products query = ProductsDbconn.Instance.Get(Id) ?? new Products();
            KqProducts brand = maindb.KqProducts.FirstOrDefault(m => m.QueryCount == Id) ?? new KqProducts();
            Obj.Add("BrandId", brand.Id);
            Obj.Add("ProductName", query.ProductName); //商品名称
            Obj.Add("Details", query.Details); //简介
            Obj.Add("Contents", CheckContentImage(query.Contents)); //内容
            List<Dictionary<string, string>> DetailPicPath = new List<Dictionary<string, string>>();
            if (!string.IsNullOrEmpty(query.DetailPicPath))
            {
                string[] DetailPicPathList = query.DetailPicPath.Split(new string[] { "#cut#" }, StringSplitOptions.RemoveEmptyEntries)[0].Split('|');
                foreach (string sub in DetailPicPathList)
                {
                    Dictionary<string, string> item = new Dictionary<string, string>();
                    item.Add("Photo", DefaultPic(sub));
                    DetailPicPath.Add(item);
                }
            }
            Obj.Add("DetailPicPath", DetailPicPath); //图集
            Obj.Add("Price", query.Price); //价格
            Dictionary<string, object> NormJson = new Dictionary<string, object>();

            int collection_id = 0;
            List<Dictionary<string, object>> tree = new List<Dictionary<string, object>>();
            List<ProductNormItem> productNormItems = ProductNormItemDbconn.Instance.GetList(Id);
            if (productNormItems.Count > 0)
            {
                int i = 0;
                foreach (ProductNormItem productNormItem in productNormItems.Where(m => m.ParentId == 0).ToList())
                {
                    i += 1;
                    Dictionary<string, object> treeitem = new Dictionary<string, object>();
                    treeitem.Add("k", productNormItem.ColName);
                    treeitem.Add("k_s", "s" + i.ToString());
                    List<Dictionary<string, object>> subtreeitems = new List<Dictionary<string, object>>();
                    foreach (ProductNormItem subProductNormItem in productNormItems.Where(m => m.ParentId == productNormItem.Id).ToList())
                    {
                        Dictionary<string, object> subtreeitem = new Dictionary<string, object>();
                        subtreeitem.Add("id", subProductNormItem.Id.ToString());
                        subtreeitem.Add("name", subProductNormItem.ColName);
                        subtreeitems.Add(subtreeitem);
                    }
                    treeitem.Add("v", subtreeitems);
                    treeitem.Add("largeImageMode", true);
                    tree.Add(treeitem);
                }
                NormJson.Add("tree", tree);

                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                List<int> productNorms = ProductNormDbconn.Instance.GetList(Id);
                i = 0;
                foreach (int NormId in productNorms)
                {
                    ProductNorm productNorm = ProductNormDbconn.Instance.Get(NormId) ?? new ProductNorm();
                    i += 1;
                    if (i == 1)
                    {
                        collection_id = productNorm.Id;
                    }
                    Dictionary<string, object> item = new Dictionary<string, object>();
                    item.Add("id", productNorm.Id);
                    string[] idlist = function.CheckNull(productNorm.IdList).Split(',');
                    int j = 0;
                    foreach (string sub in idlist)
                    {
                        j += 1;
                        item.Add("s" + j, sub);
                    }
                    item.Add("price", productNorm.Price);
                    item.Add("stock_num", productNorm.Stock);
                    list.Add(item);
                }
                NormJson.Add("list", list);

                NormJson.Add("collection_id", collection_id);
                NormJson.Add("none_sku", false);
            }
            else
            { 
                NormJson.Add("collection_id", query.Id);
                NormJson.Add("none_sku", true);
            }
            NormJson.Add("price", query.Price);
            NormJson.Add("stock_num", query.Stock);

            NormJson.Add("hide_stock", true);
            Obj.Add("NormJson", NormJson); //规格
            Obj.Add("MinBuyCount", 1); //最小购买数量
            return Obj;
        }
        #endregion



        #region 创客-商城-商城主界面列表
        [Authorize]
        public JsonResult List(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            List<Dictionary<string, object>> dataList = ListDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList });
        }
        public List<Dictionary<string, object>> ListDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int PageSize = int.Parse(function.CheckInt(data["PageSize"].ToString()));
            int PageNum = int.Parse(function.CheckInt(data["PageNum"].ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            List<int> query = ProductsDbconn.Instance.GetList(PageNum, PageSize);
            foreach (int ProductId in query)
            {
                Products subdata = ProductsDbconn.Instance.Get(ProductId) ?? new Products();
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("ProductName", subdata.ProductName); //商品名称
                curData.Add("Details", subdata.Details); //简介
                curData.Add("ListPicPath", DefaultPic(subdata.ListPicPath)); //列表图片
                curData.Add("Price", subdata.Price); //价格
                curData.Add("Id", subdata.Id); //Id
                dataList.Add(curData);
            }
            return dataList;
        }
        #endregion



        #region 检查签名是否合法，合法返回1，不合法返回提示信息

        /// <summary>
        /// 检查签名是否合法，合法返回1，不合法返回提示信息
        /// </summary>
        /// <param name="value">请求的参数(json字符串)</param>
        /// <param name="signField">要签名的字段</param>
        /// <returns></returns>
        private string CheckSign(string value, string[] signField)
        {
            JsonData json = JsonMapper.ToObject(value);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            for (int i = 0; i < signField.Length; i++)
            {
                dic.Add(signField[i], json[signField[i]].ToString());
            }
            string sign = json["sign"].ToString(); //客户端签名字符串
            return new Sign().sign(dic, sign);
        }

        #endregion

    }
}
