/*
 * 商品信息
 */

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 ProductsController : BaseController
    {
        public ProductsController(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(Products data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;
            return View();
        }

        #endregion

        #region 根据条件查询商品信息列表

        /// <summary>
        /// 商品信息列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(Products data, string ColId, int page = 1, int limit = 30)
        {
            // Dictionary<string, string> ProductFareTempDic = new ProductDictionary().getProductFareTempDic(data.MerchantId);
            // Dictionary<string, string> MerchantClassDic = new MerchantDictionary().getMerchantClassDic(data.MerchantId);

            Dictionary<string, string> Fields = new Dictionary<string, string>();
            // Fields.Add("ColId", "1"); //分类
            Fields.Add("ProductName", "2"); //商品名称
            // Fields.Add("MerchantClassId", "1"); //商家分类
            string condition = "";
            // if (SysRealRole == 3)
            // {
            //     condition += " and MerchantId=" + SysId;
            // }
            if (!string.IsNullOrEmpty(ColId))
            {
                condition += " and ColId like '%" + ColId + "%'";
            }
            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("Products", Fields, "Sort", "False", page, limit, condition);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                // dic["FareTemplateId"] = new DictionaryClass().getDictionaryNameByKey(ProductFareTempDic, dic["FareTemplateId"].ToString());
                // dic["MerchantClassId"] = new DictionaryClass().getDictionaryNameByKey(MerchantClassDic, dic["MerchantClassId"].ToString());
                dic["Status"] = dic["Status"].ToString() == "1" ? "已上架" : "已下架";
            }
            return Json(obj);
        }

        #endregion

        #region 增加商品信息

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

            return View();
        }

        #endregion

        #region 增加商品信息

        /// <summary>
        /// 增加或修改商品信息信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Add(Products data)
        {
            Products product = db.Products.FirstOrDefault(m => m.ProductName == data.ProductName);
            if (product != null)
            {
                return "商品名称已存在";
            }
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            Fields.Add("MerchantId", data.MerchantId);
            Fields.Add("ProductName", data.ProductName); //商品名称
            Fields.Add("Details", data.Details); //简介
            Fields.Add("Contents", data.Contents); //内容
            Fields.Add("Stock", data.Stock); //库存
            Fields.Add("BuyCount", data.BuyCount); //已购买数
            Fields.Add("DetailPicPath", data.DetailPicPath); //图集
            // Fields.Add("ColId", data.ColId); //商品类型
            Fields.Add("CommentCount", data.CommentCount); //评价数
            Fields.Add("GoodPercent", data.GoodPercent); //好评率
            Fields.Add("IsRecommend", data.IsRecommend); //推荐
            Fields.Add("IsRecommend2", data.IsRecommend2);
            Fields.Add("IsRecommend3", data.IsRecommend3);
            Fields.Add("StartDate", data.StartDate); //上架时间
            Fields.Add("EndDate", data.EndDate); //下架时间
            // Fields.Add("EndDate", data.EndDate); //下架时间
            Fields.Add("IsLimit", data.IsLimit); //限时抢购
            Fields.Add("IsBanner", data.IsBanner); //是否Banner推荐
            Fields.Add("BannerPhoto", data.BannerPhoto); //Banner图
            Fields.Add("LinkUrl", data.LinkUrl); //外链
            Fields.Add("BannerSort", data.BannerSort); //排序
            Fields.Add("SourcePrice", data.SourcePrice); //原价
            Fields.Add("Price", data.Price); //价格
            Fields.Add("Integral", data.Integral); //抵扣积分
            Fields.Add("MemberPrice", data.MemberPrice); //创客价
            Fields.Add("UserIntegral", data.UserIntegral); //创客抵扣积分
            // Fields.Add("PublishDate", data.PublishDate); //上架时间
            Fields.Add("CostPrice", data.CostPrice); //成本价
            Fields.Add("FareTemplateId", data.FareTemplateId); //运费模板Id
            Fields.Add("StartBuyCount", data.StartBuyCount); //起购数量
            Fields.Add("LimitCount", data.LimitCount); //限购数量
            Fields.Add("KeyWord", data.KeyWord); //关键词
            Fields.Add("MerchantClassId", data.MerchantClassId); //商家分类
            Fields.Add("ShareDetail", data.ShareDetail); //分享描述
            Fields.Add("ListPicPath", data.ListPicPath); //缩略图
            Fields.Add("MerchantColId", data.MerchantColId); //商品分类
            Fields.Add("Title", data.Title);
            Fields.Add("Title2", data.Title2);
            Fields.Add("ColId", data.ColId);//分类
            Fields.Add("ProductKind", data.ProductKind);//商品类型

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

            SetRedis(Id, true);

            return "success";
        }

        #endregion

        #region 修改商品信息

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

            Products editData = db.Products.FirstOrDefault(m => m.Id == Id) ?? new Products();
            ViewBag.data = editData;
            return View();
        }

        #endregion

        #region 修改商品信息

        /// <summary>
        /// 增加或修改商品信息信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(Products data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            Fields.Add("MerchantId", data.MerchantId);
            Fields.Add("ProductName", data.ProductName); //商品名称
            Fields.Add("Details", data.Details); //简介
            Fields.Add("Contents", data.Contents); //内容
            Fields.Add("Stock", data.Stock); //库存
            Fields.Add("BuyCount", data.BuyCount); //已购买数
            Fields.Add("DetailPicPath", data.DetailPicPath); //图集
            // Fields.Add("ColId", data.ColId); //商品类型
            Fields.Add("CommentCount", data.CommentCount); //评价数
            Fields.Add("GoodPercent", data.GoodPercent); //好评率
            Fields.Add("IsRecommend", data.IsRecommend); //推荐
            Fields.Add("IsRecommend2", data.IsRecommend2);
            Fields.Add("IsRecommend3", data.IsRecommend3);
            Fields.Add("StartDate", data.StartDate); //上架时间
            Fields.Add("EndDate", data.EndDate); //下架时间
            Fields.Add("IsLimit", data.IsLimit); //限时抢购
            Fields.Add("IsBanner", data.IsBanner); //是否Banner推荐
            Fields.Add("BannerPhoto", data.BannerPhoto); //Banner图
            Fields.Add("LinkUrl", data.LinkUrl); //外链
            Fields.Add("BannerSort", data.BannerSort); //排序
            Fields.Add("SourcePrice", data.SourcePrice); //原价
            Fields.Add("Price", data.Price); //价格
            Fields.Add("Integral", data.Integral); //抵扣积分
            Fields.Add("MemberPrice", data.MemberPrice); //创客价
            Fields.Add("UserIntegral", data.UserIntegral); //创客抵扣积分
            // Fields.Add("PublishDate", data.PublishDate); //上架时间
            Fields.Add("CostPrice", data.CostPrice); //成本价
            Fields.Add("FareTemplateId", data.FareTemplateId); //运费模板Id
            Fields.Add("StartBuyCount", data.StartBuyCount); //起购数量
            Fields.Add("LimitCount", data.LimitCount); //限购数量
            Fields.Add("KeyWord", data.KeyWord); //关键词
            Fields.Add("MerchantClassId", data.MerchantClassId); //商家分类
            Fields.Add("ShareDetail", data.ShareDetail); //分享描述
            Fields.Add("ListPicPath", data.ListPicPath); //缩略图
            Fields.Add("MerchantColId", data.MerchantColId); //商品分类
            Fields.Add("Title", data.Title);
            Fields.Add("Title2", data.Title2);
            Fields.Add("ColId", data.ColId);//分类
            Fields.Add("ProductKind", data.ProductKind);//商品类型

            Fields.Add("SeoTitle", data.SeoTitle);
            Fields.Add("SeoKeyword", data.SeoKeyword);
            Fields.Add("SeoDescription", data.SeoDescription);
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("Products", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "Products", "update");
            db.SaveChanges();

            SetRedis(data.Id, true);

            return "success";
        }

        #endregion

        #region 删除商品信息信息

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

            SetRedis(0, true);

            return "success";
        }

        #endregion

        #region 开启

        /// <summary>
        /// 开启
        /// </summary>
        /// <returns></returns>
        public string Open(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "Products", "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("Products", Fields, id);
            }
            db.SaveChanges();
            SetRedis(0, true);
            return "success";
        }

        #endregion

        #region 关闭

        /// <summary>
        /// 关闭
        /// </summary>
        /// <returns></returns>
        public string Close(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "Products", "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("Products", Fields, id);
            }
            db.SaveChanges();
            SetRedis(0, true);
            return "success";
        }

        #endregion

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

            AddSysLog(Id.ToString(), "Products", "sort");

            SetRedis(0, true);
            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.Products.Add(new Products()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(Products data)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("ProductName", "2"); //商品名称
            Fields.Add("MerchantClassId", "1"); //商家分类

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("Products", 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", "Products", "ExportExcel");
            return Json(result);
        }

        #endregion





        #region 根据分类获取商品列表

        public List<Dictionary<string, object>> GetProductByCol(string ColIds, string MerchantIds)
        {
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            IQueryable<Products> products = db.Products;
            if (!string.IsNullOrEmpty(ColIds))
            {
                List<string> colidlist = ColIds.Split(',').ToList();
                products = products.Where(m => colidlist.Contains(m.ColId));
            }
            List<int> meridlist = new List<int>();
            if (!string.IsNullOrEmpty(MerchantIds))
            {
                List<string> merchantidlist = MerchantIds.Split(',').ToList();
                foreach (string merid in merchantidlist)
                {
                    meridlist.Add(int.Parse(merid));
                }
                products = products.Where(m => meridlist.Contains(m.MerchantId));
            }
            products = products.OrderByDescending(m => m.Id);
            foreach (Products product in products.ToList())
            {
                Dictionary<string, object> row = new Dictionary<string, object>();
                row.Add("title", product.ProductName);
                row.Add("value", product.Id);
                list.Add(row);
            }
            return list;
        }

        #endregion




        #region 设置缓存

        private void SetRedis(int Id, bool All)
        {
            if (All)
            {
                RedisDbconn.Instance.Clear("ProductsList");
                var products = db.Products.Select(m => new { m.Id, m.Status, m.Sort }).Where(m => m.Status > 0).OrderByDescending(m => m.Sort).ThenByDescending(m => m.Id).ToList();
            }
            if (Id > 0)
            {
                Products edit = db.Products.FirstOrDefault(m => m.Id == Id);
                if (edit != null)
                {
                    RedisDbconn.Instance.Clear("Products:" + Id);
                    RedisDbconn.Instance.Clear("ProductNormItem:" + Id);
                    RedisDbconn.Instance.Clear("ProductNorms:" + Id);
                    List<ProductNorm> ProductNorms = db.ProductNorm.Where(m => m.ProductId == Id).ToList();
                    foreach (ProductNorm Item in ProductNorms)
                    {
                        RedisDbconn.Instance.Clear("ProductNorm:" + Item.Id);
                    }
                }
            }
        }

        #endregion


    }
}
