/*
 * 优惠券
 */

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 CouponsController : BaseController
    {
        public CouponsController(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(Coupons data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;


            string Condition = "";
            Condition += "Name:\"" + data.Name + "\",";
            Condition += "IsNewUser:\"" + data.IsNewUser + "\",";
            Condition += "IsPublic:\"" + data.IsPublic + "\",";
            Condition += "Kind:\"" + data.Kind + "\",";
            Condition += "MerchantId:\"" + data.MerchantId + "\",";
            Condition += "ProductColId:\"" + data.ProductColId + "\",";
            Condition += "ProductId:\"" + data.ProductId + "\",";
            Condition += "UserMaxLevel:\"" + data.UserMaxLevel + "\",";
            Condition += "UserMinLevel:\"" + data.UserMinLevel + "\",";
            Condition += "IsRepeat:\"" + data.IsRepeat + "\",";
            Condition += "RepeatType:\"" + data.RepeatType + "\",";
            Condition += "IsReUse:\"" + data.IsReUse + "\",";

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

        #endregion

        #region 根据条件查询优惠券列表

        /// <summary>
        /// 优惠券列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(Coupons data, int page = 1, int limit = 30)
        {
            Dictionary<string, string> MerchantsDic = new MerchantDictionary().getMerchantsDic();
            Dictionary<string, string> ColDic = new DictionaryClass().getColDic("");
            Dictionary<string, string> ProductsDic = new ProductDictionary().getProductsDic();
            Dictionary<string, string> UserLevelSetDic = new UserDictionary().getUserLevelSet();

            Dictionary<string, string> Fields = new Dictionary<string, string>();

            Fields.Add("Name", "2"); //名称
            Fields.Add("CreateDate", "3"); //时间
            Fields.Add("IsNewUser", "1"); //新创客使用
            Fields.Add("IsPublic", "1"); //是否公开领取
            Fields.Add("Kind", "1"); //优惠券类型
            Fields.Add("MerchantId", "2"); //商家
            Fields.Add("ProductColId", "1"); //商品分类
            Fields.Add("ProductId", "1"); //商品
            Fields.Add("UserMaxLevel", "1"); //创客最高等级
            Fields.Add("UserMinLevel", "1"); //创客最低等级
            Fields.Add("IsRepeat", "1"); //是否重复
            Fields.Add("RepeatType", "1"); //重复类型
            Fields.Add("IsReUse", "1"); //是否一次性使用

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("Coupons", Fields, "Id desc", "False", page, limit);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                dic["IsPublic"] = dic["IsPublic"].ToString() == "1" ? "是" : "否";
                dic["Status"] = dic["Status"].ToString() == "1" ? "正常" : "关闭";
                dic["MerchantId"] = new DictionaryClass().getDictionaryNamesByKeys(MerchantsDic, dic["MerchantId"].ToString());
                dic["ProductColId"] = new DictionaryClass().getDictionaryNameByKey(ColDic, dic["ProductColId"].ToString());
                dic["ProductId"] = new DictionaryClass().getDictionaryNameByKey(ProductsDic, dic["ProductId"].ToString());
                dic["UserMaxLevel"] = new DictionaryClass().getDictionaryNameByKey(UserLevelSetDic, dic["UserMaxLevel"].ToString());
                dic["UserMinLevel"] = new DictionaryClass().getDictionaryNameByKey(UserLevelSetDic, dic["UserMinLevel"].ToString());
                string Kind = dic["Kind"].ToString();
                if (Kind == "1")
                {
                    dic["Kind"] = "现金抵扣券";
                }
                else if (Kind == "2")
                {
                    dic["Kind"] = "满减券";
                }
                else if (Kind == "3")
                {
                    dic["Kind"] = "满折券";
                }
                else if (Kind == "4")
                {
                    dic["Kind"] = "折扣券";
                }
                else if (Kind == "5")
                {
                    dic["Kind"] = "运费券";
                }
            }
            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(Coupons data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();

            Fields.Add("Name", data.Name); //名称
            Fields.Add("Explanation", data.Explanation); //说明
            Fields.Add("IsNewUser", data.IsNewUser); //新创客使用
            Fields.Add("IsPublic", data.IsPublic); //是否公开领取
            Fields.Add("Stock", data.Stock); //库存
            Fields.Add("Kind", data.Kind); //优惠券类型
            Fields.Add("MerchantId", data.MerchantId); //商家
            Fields.Add("ProductColId", data.ProductColId); //商品分类
            Fields.Add("ProductId", data.ProductId); //商品
            Fields.Add("UserMaxLevel", data.UserMaxLevel); //创客最高等级
            Fields.Add("UserMinLevel", data.UserMinLevel); //创客最低等级
            Fields.Add("UseStartDate", data.UseStartDate); //开始使用时间
            Fields.Add("UseEndDate", data.UseEndDate); //结束使用时间
            Fields.Add("IsRepeat", data.IsRepeat); //是否重复
            Fields.Add("RepeatType", data.RepeatType); //重复类型
            Fields.Add("RepeatCondition", data.RepeatCondition); //重复条件值
            Fields.Add("IsReUse", data.IsReUse); //是否一次性使用
            Fields.Add("PublicStartDate", data.PublicStartDate); //公开领取开始时间
            Fields.Add("PublicEndDate", data.PublicEndDate); //公开领取结束时间
            Fields.Add("PublicMax", data.PublicMax); //公开每人领取数量
            Fields.Add("PublicMaxByDay", data.PublicMaxByDay); //公开每人每天领取数量
            Fields.Add("IsSuperpose", data.IsSuperpose); //是否叠加使用
            Fields.Add("AndPromotion", data.AndPromotion); //是否与促销活动同时使用
            Fields.Add("FullReduceMoney", data.FullReduceMoney); //满多少可用
            Fields.Add("FullReduceData", data.FullReduceData); //满减数据
            Fields.Add("ExpireStartDate", data.ExpireStartDate); //过期开始时间
            Fields.Add("ExpireEndDate", data.ExpireEndDate); //过期结束时间

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

            return "success";
        }

        #endregion

        #region 修改优惠券

        /// <summary>
        /// 增加或修改优惠券信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit(string right, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;


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

        #endregion

        #region 修改优惠券

        /// <summary>
        /// 增加或修改优惠券信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(Coupons data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();

            Fields.Add("Name", data.Name); //名称
            Fields.Add("Explanation", data.Explanation); //说明
            Fields.Add("IsNewUser", data.IsNewUser); //新创客使用
            Fields.Add("IsPublic", data.IsPublic); //是否公开领取
            Fields.Add("Stock", data.Stock); //库存
            Fields.Add("Kind", data.Kind); //优惠券类型
            Fields.Add("MerchantId", data.MerchantId); //商家
            Fields.Add("ProductColId", data.ProductColId); //商品分类
            Fields.Add("ProductId", data.ProductId); //商品
            Fields.Add("UserMaxLevel", data.UserMaxLevel); //创客最高等级
            Fields.Add("UserMinLevel", data.UserMinLevel); //创客最低等级
            Fields.Add("UseStartDate", data.UseStartDate); //开始使用时间
            Fields.Add("UseEndDate", data.UseEndDate); //结束使用时间
            Fields.Add("IsRepeat", data.IsRepeat); //是否重复
            Fields.Add("RepeatType", data.RepeatType); //重复类型
            Fields.Add("RepeatCondition", data.RepeatCondition); //重复条件值
            Fields.Add("IsReUse", data.IsReUse); //是否一次性使用
            Fields.Add("PublicStartDate", data.PublicStartDate); //公开领取开始时间
            Fields.Add("PublicEndDate", data.PublicEndDate); //公开领取结束时间
            Fields.Add("PublicMax", data.PublicMax); //公开每人领取数量
            Fields.Add("PublicMaxByDay", data.PublicMaxByDay); //公开每人每天领取数量
            Fields.Add("IsSuperpose", data.IsSuperpose); //是否叠加使用
            Fields.Add("AndPromotion", data.AndPromotion); //是否与促销活动同时使用
            Fields.Add("FullReduceMoney", data.FullReduceMoney); //满多少可用
            Fields.Add("FullReduceData", data.FullReduceData); //满减数据
            Fields.Add("ExpireStartDate", data.ExpireStartDate); //过期开始时间
            Fields.Add("ExpireEndDate", data.ExpireEndDate); //过期结束时间

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

            return "success";
        }

        #endregion

        #region 删除优惠券信息

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

            return "success";
        }

        #endregion

        #region 开启

        /// <summary>
        /// 开启
        /// </summary>
        /// <returns></returns>
        public string Open(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "Coupons", "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("Coupons", 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, "Coupons", "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("Coupons", 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("Coupons", Sort, Id);

            AddSysLog(Id.ToString(), "Coupons", "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];
                string Name = dr["名称"].ToString();
                string Explanation = dr["说明"].ToString();
                ulong IsNewUser = ulong.Parse(dr["新创客使用"].ToString());
                ulong IsPublic = ulong.Parse(dr["是否公开领取"].ToString());
                decimal Stock = decimal.Parse(dr["库存"].ToString());
                int Kind = int.Parse(dr["优惠券类型"].ToString());
                string MerchantId = dr["商家"].ToString();
                string ProductColId = dr["商品分类"].ToString();
                string ProductId = dr["商品"].ToString();
                int UserMaxLevel = int.Parse(dr["创客最高等级"].ToString());
                int UserMinLevel = int.Parse(dr["创客最低等级"].ToString());
                string UseStartDate = dr["开始使用时间"].ToString();
                string UseEndDate = dr["结束使用时间"].ToString();
                ulong IsRepeat = ulong.Parse(dr["是否重复"].ToString());
                int RepeatType = int.Parse(dr["重复类型"].ToString());
                ulong IsReUse = ulong.Parse(dr["是否一次性使用"].ToString());
                string PublicStartDate = dr["公开领取开始时间"].ToString();
                string PublicEndDate = dr["公开领取结束时间"].ToString();
                int PublicMax = int.Parse(dr["公开每人领取数量"].ToString());
                int PublicMaxByDay = int.Parse(dr["公开每人每天领取数量"].ToString());
                ulong IsSuperpose = ulong.Parse(dr["是否叠加使用"].ToString());
                ulong AndPromotion = ulong.Parse(dr["是否与促销活动同时使用"].ToString());
                decimal FullReduceMoney = decimal.Parse(dr["满多少可用"].ToString());
                decimal FullReduceData = decimal.Parse(dr["满减数据"].ToString());
                string ExpireStartDate = dr["过期开始时间"].ToString();
                string ExpireEndDate = dr["过期结束时间"].ToString();

                db.Coupons.Add(new Coupons()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,
                    Name = Name,   //名称
                    Explanation = Explanation,   //说明
                    IsNewUser = IsNewUser,   //新创客使用
                    IsPublic = IsPublic,   //是否公开领取
                    Stock = Stock,   //库存
                    Kind = Kind,   //优惠券类型
                    MerchantId = MerchantId,   //商家
                    ProductColId = ProductColId,   //商品分类
                    ProductId = ProductId,   //商品
                    UserMaxLevel = UserMaxLevel,   //创客最高等级
                    UserMinLevel = UserMinLevel,   //创客最低等级
                    UseStartDate = DateTime.Parse(UseStartDate),   //开始使用时间
                    UseEndDate = DateTime.Parse(UseEndDate),   //结束使用时间
                    IsRepeat = IsRepeat,   //是否重复
                    RepeatType = RepeatType,   //重复类型
                    IsReUse = IsReUse,   //是否一次性使用
                    PublicStartDate = DateTime.Parse(PublicStartDate),   //公开领取开始时间
                    PublicEndDate = DateTime.Parse(PublicEndDate),   //公开领取结束时间
                    PublicMax = PublicMax,   //公开每人领取数量
                    PublicMaxByDay = PublicMaxByDay,   //公开每人每天领取数量
                    IsSuperpose = IsSuperpose,   //是否叠加使用
                    AndPromotion = AndPromotion,   //是否与促销活动同时使用
                    FullReduceMoney = FullReduceMoney,   //满多少可用
                    FullReduceData = FullReduceData,   //满减数据
                    ExpireStartDate = DateTime.Parse(ExpireStartDate),   //过期开始时间
                    ExpireEndDate = DateTime.Parse(ExpireEndDate),   //过期结束时间

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(Coupons data)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("Name", "2"); //名称
            Fields.Add("CreateDate", "3"); //时间
            Fields.Add("IsNewUser", "1"); //新创客使用
            Fields.Add("IsPublic", "1"); //是否公开领取
            Fields.Add("Kind", "1"); //优惠券类型
            Fields.Add("MerchantId", "2"); //商家
            Fields.Add("ProductColId", "1"); //商品分类
            Fields.Add("ProductId", "1"); //商品
            Fields.Add("UserMaxLevel", "1"); //创客最高等级
            Fields.Add("UserMinLevel", "1"); //创客最低等级
            Fields.Add("IsRepeat", "1"); //是否重复
            Fields.Add("RepeatType", "1"); //重复类型
            Fields.Add("IsReUse", "1"); //是否一次性使用

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("Coupons", Fields, "Id desc", "False", 1, 20000, "", "Name,Explanation,IsNewUser,IsPublic,Stock,Kind,MerchantId,ProductColId,ProductId,UserMaxLevel,UserMinLevel,UseStartDate,UseEndDate,IsRepeat,RepeatType,IsReUse,PublicStartDate,PublicEndDate,PublicMax,PublicMaxByDay,IsSuperpose,AndPromotion,FullReduceMoney,FullReduceData,ExpireStartDate,ExpireEndDate", 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>();
            ReturnFields.Add("Name", "名称");
            ReturnFields.Add("Explanation", "说明");
            ReturnFields.Add("IsNewUser", "新创客使用");
            ReturnFields.Add("IsPublic", "是否公开领取");
            ReturnFields.Add("Stock", "库存");
            ReturnFields.Add("Kind", "优惠券类型");
            ReturnFields.Add("MerchantId", "商家");
            ReturnFields.Add("ProductColId", "商品分类");
            ReturnFields.Add("ProductId", "商品");
            ReturnFields.Add("UserMaxLevel", "创客最高等级");
            ReturnFields.Add("UserMinLevel", "创客最低等级");
            ReturnFields.Add("UseStartDate", "开始使用时间");
            ReturnFields.Add("UseEndDate", "结束使用时间");
            ReturnFields.Add("IsRepeat", "是否重复");
            ReturnFields.Add("RepeatType", "重复类型");
            ReturnFields.Add("IsReUse", "是否一次性使用");
            ReturnFields.Add("PublicStartDate", "公开领取开始时间");
            ReturnFields.Add("PublicEndDate", "公开领取结束时间");
            ReturnFields.Add("PublicMax", "公开每人领取数量");
            ReturnFields.Add("PublicMaxByDay", "公开每人每天领取数量");
            ReturnFields.Add("IsSuperpose", "是否叠加使用");
            ReturnFields.Add("AndPromotion", "是否与促销活动同时使用");
            ReturnFields.Add("FullReduceMoney", "满多少可用");
            ReturnFields.Add("FullReduceData", "满减数据");
            ReturnFields.Add("ExpireStartDate", "过期开始时间");
            ReturnFields.Add("ExpireEndDate", "过期结束时间");

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

        #endregion

    }
}