/*
 * 商品规格
 */

using System;
using System.Web;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MySystem.Models;
using Library;
using LitJson;
using MySystemLib;

namespace MySystem.Areas.Admin.Controllers
{
    [Area("Admin")]
    [Route("Admin/[controller]/[action]")]
    public class ProductNormController : BaseController
    {
        public ProductNormController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
            OtherMySqlConn.connstr = ConfigurationManager.AppSettings["SqlConnStr"].ToString();
        }

        #region 商品规格列表

        /// <summary>
        /// 根据条件查询商品规格列表
        /// </summary>
        /// <returns></returns>
        public IActionResult Index(ProductNorm data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            string Condition = "";
            Condition += "ColName:\"" + data.ColName + "\",";

            if (!string.IsNullOrEmpty(Condition))
            {
                Condition = Condition.TrimEnd(',');
                Condition = ", where: {" + Condition + "}";
            }
            ViewBag.Condition = Condition;
            return View();
        }

        #endregion

        #region 根据条件查询商品规格列表

        /// <summary>
        /// 商品规格列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(ProductNorm data, int page = 1, int limit = 30)
        {

            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("ColName", "2"); //名称

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("ProductNorm", Fields, "Id desc", "False", page, limit);

            return Json(obj);
        }

        #endregion

        #region 增加商品规格

        /// <summary>
        /// 增加或修改商品规格信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Add(string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            return View();
        }

        #endregion

        #region 增加商品规格

        /// <summary>
        /// 增加或修改商品规格信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Add(ProductNorm data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            Fields.Add("ColName", data.ColName); //名称
            Fields.Add("IdList", data.IdList); //Id集合
            Fields.Add("Price", data.Price); //价格
            Fields.Add("Integral", data.Integral); //抵扣积分
            Fields.Add("UserPrice", data.UserPrice); //创客价
            Fields.Add("UserIntegral", data.UserIntegral); //创客抵扣积分
            Fields.Add("Stock", data.Stock); //库存
            Fields.Add("BuyCount", data.BuyCount); //已购买数
            Fields.Add("CostPrice", data.CostPrice); //成本价
            Fields.Add("Code", data.Code); //编码
            Fields.Add("StartBuyCount", data.StartBuyCount); //起购数量
            Fields.Add("LimitCount", data.LimitCount); //限购数量

            Fields.Add("SeoTitle", data.SeoTitle);
            Fields.Add("SeoKeyword", data.SeoKeyword);
            Fields.Add("SeoDescription", data.SeoDescription);
            int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Add("ProductNorm", Fields, 0);
            AddSysLog(data.Id.ToString(), "ProductNorm", "add");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 修改商品规格

        /// <summary>
        /// 增加或修改商品规格信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit(string right, int Id, string MerchantId)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;
            ViewBag.Id = Id.ToString();
            ViewBag.MerchantId = MerchantId;

            string NormJson = "[]#cut#[]";
            Products edit = db.Products.FirstOrDefault(m => m.Id == Id);
            if (edit != null)
            {
                if (!string.IsNullOrEmpty(edit.NormJson))
                {
                    NormJson = edit.NormJson;
                }
            }
            string[] NormJsonArray = NormJson.Split(new string[] { "#cut#" }, StringSplitOptions.None);
            ViewBag.ItemList = NormJsonArray[0];
            ViewBag.DetailList = NormJsonArray[1];
            return View();
        }

        #endregion

        #region 修改商品规格

        /// <summary>
        /// 增加或修改商品规格信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string EditPost(string ItemList, string DetailList, int Id, int MerchantId)
        {
            Products edit = db.Products.FirstOrDefault(m => m.Id == Id);
            if (edit != null)
            {
                IQueryable<ProductNormItem> items = db.ProductNormItem.Where(m => m.ProductId == Id);
                foreach (ProductNormItem item in items)
                {
                    db.ProductNormItem.Remove(item);
                }
                db.SaveChanges();
                edit.NormJson = ItemList + "#cut#" + DetailList;
                Dictionary<string, string> ids = new Dictionary<string, string>();
                JsonData jsonItemObj = JsonMapper.ToObject(ItemList);
                for (int i = 0; i < jsonItemObj.Count; i++)
                {
                    JsonData item = jsonItemObj[i];
                    string name = item["name"].ToString();
                    ProductNormItem add = db.ProductNormItem.FirstOrDefault(m => m.ColName == name && m.MerchantId == MerchantId && m.ProductId == Id && m.ParentId == 0);
                    if (add == null)
                    {
                        add = db.ProductNormItem.Add(new ProductNormItem()
                        {
                            CreateDate = DateTime.Now,
                            UpdateDate = DateTime.Now,
                            ColName = name,
                            MerchantId = MerchantId,
                            ProductId = Id,
                        }).Entity;
                        db.SaveChanges();
                    }
                    JsonData subItemObj = item["vallist"];
                    for (int j = 0; j < subItemObj.Count; j++)
                    {
                        JsonData subitem = subItemObj[j];
                        string subname = subitem["name"].ToString();
                        ProductNormItem subadd = db.ProductNormItem.FirstOrDefault(m => m.ColName == subname && m.MerchantId == MerchantId && m.ProductId == Id && m.ParentId == add.Id);
                        if (subadd == null)
                        {
                            subadd = db.ProductNormItem.Add(new ProductNormItem()
                            {
                                CreateDate = DateTime.Now,
                                UpdateDate = DateTime.Now,
                                ColName = subname,
                                MerchantId = MerchantId,
                                ProductId = Id,
                                ParentId = add.Id,
                            }).Entity;
                            db.SaveChanges();
                        }
                        ids.Add(subname, subadd.Id.ToString());
                    }
                }
                string NormIds = "";
                JsonData jsonObj = JsonMapper.ToObject(DetailList);
                for (int i = 0; i < jsonObj.Count; i++)
                {
                    JsonData titles = jsonObj[i]["title"];
                    string idlist = "";
                    string namelist = "";
                    for (int j = 0; j < titles.Count; j++)
                    {
                        string name = titles[j]["name"].ToString();
                        idlist += ids[name] + ",";
                        namelist += name + ",";
                    }
                    decimal price = decimal.Parse(function.CheckNum(jsonObj[i]["price"].ToString()));
                    decimal integral = decimal.Parse(function.CheckNum(jsonObj[i]["integral"].ToString()));
                    decimal userprice = decimal.Parse(function.CheckNum(jsonObj[i]["userprice"].ToString()));
                    decimal userintegral = decimal.Parse(function.CheckNum(jsonObj[i]["userintegral"].ToString()));
                    int stock = int.Parse(function.CheckInt(jsonObj[i]["stock"].ToString()));
                    string code = jsonObj[i]["code"].ToString();
                    decimal costprice = decimal.Parse(function.CheckNum(jsonObj[i]["costprice"].ToString()));
                    int startbuycount = int.Parse(function.CheckInt(jsonObj[i]["startbuycount"].ToString()));
                    int limitcount = int.Parse(function.CheckInt(jsonObj[i]["limitcount"].ToString()));

                    idlist = idlist.TrimEnd(',');
                    namelist = namelist.TrimEnd(',');
                    ProductNorm check = db.ProductNorm.FirstOrDefault(m => m.MerchantId == MerchantId && m.ProductId == Id && m.ColName == namelist);
                    if (check == null)
                    {
                        check = db.ProductNorm.Add(new ProductNorm()
                        {
                            CreateDate = DateTime.Now,
                            UpdateDate = DateTime.Now,
                            ProductId = Id,
                            MerchantId = MerchantId,
                            ColName = namelist,
                            IdList = idlist,
                            Price = price,
                            Integral = integral,
                            UserPrice = userprice,
                            UserIntegral = userintegral,
                            Stock = stock,
                            CostPrice = costprice,
                            Code = code,
                            StartBuyCount = startbuycount,
                            LimitCount = limitcount,
                        }).Entity;
                        db.SaveChanges();
                        AddSysLog(check.Id, "ProductNorm", "add");
                    }
                    else
                    {
                        check.Price = price;
                        check.Integral = integral;
                        check.UserPrice = userprice;
                        check.UserIntegral = userintegral;
                        check.Stock = stock;
                        check.CostPrice = costprice;
                        check.Code = code;
                        check.StartBuyCount = startbuycount;
                        check.LimitCount = limitcount;
                        check.IdList = idlist;
                        AddSysLog(check.Id, "ProductNorm", "update");
                    }
                    NormIds += check.Id + ",";
                }
                edit.NormIds = NormIds.TrimEnd(',');
                db.SaveChanges();
                //检测多余的规格数，并清除
                if (!string.IsNullOrEmpty(edit.NormIds))
                {
                    List<int> nids = new List<int>();
                    string[] nidlist = edit.NormIds.Split(',');
                    foreach (string nidstring in nidlist)
                    {
                        nids.Add(int.Parse(nidstring));
                    }
                    var eidts = db.ProductNorm.Select(m => new { m.Id, m.ProductId }).Where(m => m.ProductId == Id && !nids.Contains(m.Id)).ToList();
                    foreach (var eidt in eidts)
                    {
                        ProductNorm del = db.ProductNorm.FirstOrDefault(m => m.Id == eidt.Id);
                        if (del != null)
                        {
                            db.ProductNorm.Remove(del);
                        }
                    }
                    db.SaveChanges();
                }
            }

            return "success";
        }

        #endregion

        #region 删除商品规格信息

        /// <summary>
        /// 删除商品规格信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "ProductNorm", "del");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Delete("ProductNorm", id);
            }
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 开启

        /// <summary>
        /// 开启
        /// </summary>
        /// <returns></returns>
        public string Open(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "ProductNorm", "open");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", 1);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("ProductNorm", Fields, id);
            }
            db.SaveChanges();
            return "success";
        }

        #endregion

        #region 关闭

        /// <summary>
        /// 关闭
        /// </summary>
        /// <returns></returns>
        public string Close(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "ProductNorm", "close");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", 0);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("ProductNorm", Fields, id);
            }
            db.SaveChanges();
            return "success";
        }

        #endregion

        #region 排序
        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="Id"></param>
        public string Sort(int Id, int Sort)
        {
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Sort("ProductNorm", Sort, Id);

            AddSysLog(Id.ToString(), "ProductNorm", "sort");
            return "success";
        }
        #endregion

        #region 导入数据
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="ExcelData"></param>
        public string Import(string ExcelData)
        {
            ExcelData = HttpUtility.UrlDecode(ExcelData);
            JsonData list = JsonMapper.ToObject(ExcelData);
            for (int i = 1; i < list.Count; i++)
            {
                JsonData dr = list[i];

                db.ProductNorm.Add(new ProductNorm()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,

                });
                db.SaveChanges();
            }
            AddSysLog("0", "ProductNorm", "Import");
            return "success";
        }
        #endregion

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(ProductNorm data)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("ColName", "2"); //名称

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("ProductNorm", Fields, "Id desc", "False", 1, 20000, "", "", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;

            Dictionary<string, object> result = new Dictionary<string, object>();
            result.Add("Status", "1");
            result.Add("Info", "Excel报表-" + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + ".xlsx");
            result.Add("Obj", diclist);
            Dictionary<string, object> ReturnFields = new Dictionary<string, object>();

            result.Add("Fields", ReturnFields);
            AddSysLog("0", "ProductNorm", "ExportExcel");
            return Json(result);
        }

        #endregion


        public JsonResult GetTemplate(int MerchantId)
        {
            List<ProductNormTemp> list = db.ProductNormTemp.Where(m => m.MerchantId == MerchantId).OrderByDescending(m => m.Sort).ThenByDescending(m => m.Id).ToList();
            return Json(list);
        }

        public JsonResult GetTemplateDetail(int Id)
        {
            ProductNormTemp detail = db.ProductNormTemp.FirstOrDefault(m => m.Id == Id) ?? new ProductNormTemp();
            return Json(detail);
        }
    }
}
