/*
 * 优惠券发放记录
 */

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


            string Condition = "";
            Condition += "UserGroupId:\"" + data.UserGroupId + "\",";
            Condition += "Mobile:\"" + data.Mobile + "\",";

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

        #endregion

        #region 根据条件查询优惠券发放记录列表

        /// <summary>
        /// 优惠券发放记录列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(CouponAssignRecords data, int page = 1, int limit = 30)
        {
            Dictionary<string, string> UserLevelSetDic = new UserDictionary().getUserLevelSet();
            Dictionary<string, string> UserGroupDic = new UserDictionary().getUserGroupDic();

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

            Fields.Add("CreateDate", "3"); //时间
            Fields.Add("UserGroupId", "2"); //创客分组
            Fields.Add("Mobile", "2"); //手机号

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("CouponAssignRecords", 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["UserMinLevel"] = new DictionaryClass().getDictionaryNameByKey(UserLevelSetDic, dic["UserMinLevel"].ToString());
                dic["UserMaxLevel"] = new DictionaryClass().getDictionaryNameByKey(UserLevelSetDic, dic["UserMaxLevel"].ToString());
                dic["UserGroupId"] = new DictionaryClass().getDictionaryNamesByKeys(UserGroupDic, dic["UserGroupId"].ToString());
            }
            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(CouponAssignRecords data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();

            Fields.Add("UserMinLevel", data.UserMinLevel); //创客最低等级
            Fields.Add("UserMaxLevel", data.UserMaxLevel); //创客最高等级
            Fields.Add("TotalOrderMoneyMin", data.TotalOrderMoneyMin); //最小消费总额
            Fields.Add("TotalOrderMoneyMax", data.TotalOrderMoneyMax); //最大消费总额
            Fields.Add("TotalUseIntegralMin", data.TotalUseIntegralMin); //最小消耗积分总额
            Fields.Add("TotalUseIntegralMax", data.TotalUseIntegralMax); //最大消耗积分总额
            Fields.Add("CurMoneyMin", data.CurMoneyMin); //当前最低余额
            Fields.Add("CurMoneyMax", data.CurMoneyMax); //当前最高余额
            Fields.Add("UserGroupId", data.UserGroupId); //创客分组
            Fields.Add("Areas", data.Areas); //创客所在地区
            Fields.Add("Mobile", data.Mobile); //手机号
            Fields.Add("CouponIds", data.CouponIds); //优惠券

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

            return "success";
        }

        #endregion

        #region 修改优惠券发放记录

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


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

        #endregion

        #region 修改优惠券发放记录

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

            Fields.Add("UserMinLevel", data.UserMinLevel); //创客最低等级
            Fields.Add("UserMaxLevel", data.UserMaxLevel); //创客最高等级
            Fields.Add("TotalOrderMoneyMin", data.TotalOrderMoneyMin); //最小消费总额
            Fields.Add("TotalOrderMoneyMax", data.TotalOrderMoneyMax); //最大消费总额
            Fields.Add("TotalUseIntegralMin", data.TotalUseIntegralMin); //最小消耗积分总额
            Fields.Add("TotalUseIntegralMax", data.TotalUseIntegralMax); //最大消耗积分总额
            Fields.Add("CurMoneyMin", data.CurMoneyMin); //当前最低余额
            Fields.Add("CurMoneyMax", data.CurMoneyMax); //当前最高余额
            Fields.Add("UserGroupId", data.UserGroupId); //创客分组
            Fields.Add("Areas", data.Areas); //创客所在地区
            Fields.Add("Mobile", data.Mobile); //手机号
            Fields.Add("CouponIds", data.CouponIds); //优惠券

            Fields.Add("SeoKeyword", SysUserName);
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("CouponAssignRecords", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "CouponAssignRecords", "update");
            db.SaveChanges();
            AssignCoupon(data);

            return "success";
        }

        #endregion

        #region 删除优惠券发放记录信息

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

            return "success";
        }

        #endregion

        #region 开启

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

            AddSysLog(Id.ToString(), "CouponAssignRecords", "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];
                int UserMinLevel = int.Parse(dr["创客最低等级"].ToString());
                int UserMaxLevel = int.Parse(dr["创客最高等级"].ToString());
                decimal TotalOrderMoneyMin = decimal.Parse(dr["最小消费总额"].ToString());
                decimal TotalOrderMoneyMax = decimal.Parse(dr["最大消费总额"].ToString());
                decimal TotalUseIntegralMin = decimal.Parse(dr["最小消耗积分总额"].ToString());
                decimal TotalUseIntegralMax = decimal.Parse(dr["最大消耗积分总额"].ToString());
                decimal CurMoneyMin = decimal.Parse(dr["当前最低余额"].ToString());
                decimal CurMoneyMax = decimal.Parse(dr["当前最高余额"].ToString());
                string UserGroupId = dr["创客分组"].ToString();
                string Areas = dr["创客所在地区"].ToString();
                string Mobile = dr["手机号"].ToString();

                db.CouponAssignRecords.Add(new CouponAssignRecords()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,
                    UserMinLevel = UserMinLevel,   //创客最低等级
                    UserMaxLevel = UserMaxLevel,   //创客最高等级
                    TotalOrderMoneyMin = TotalOrderMoneyMin,   //最小消费总额
                    TotalOrderMoneyMax = TotalOrderMoneyMax,   //最大消费总额
                    TotalUseIntegralMin = TotalUseIntegralMin,   //最小消耗积分总额
                    TotalUseIntegralMax = TotalUseIntegralMax,   //最大消耗积分总额
                    CurMoneyMin = CurMoneyMin,   //当前最低余额
                    CurMoneyMax = CurMoneyMax,   //当前最高余额
                    UserGroupId = UserGroupId,   //创客分组
                    Areas = Areas,   //创客所在地区
                    Mobile = Mobile,   //手机号

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(CouponAssignRecords data)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("CreateDate", "3"); //时间
            Fields.Add("UserGroupId", "2"); //创客分组
            Fields.Add("Mobile", "2"); //手机号

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("CouponAssignRecords", Fields, "Id desc", "False", 1, 20000, "", "UserMinLevel,UserMaxLevel,TotalOrderMoneyMin,TotalOrderMoneyMax,TotalUseIntegralMin,TotalUseIntegralMax,CurMoneyMin,CurMoneyMax,UserGroupId,Areas,Mobile", 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("UserMinLevel", "创客最低等级");
            ReturnFields.Add("UserMaxLevel", "创客最高等级");
            ReturnFields.Add("TotalOrderMoneyMin", "最小消费总额");
            ReturnFields.Add("TotalOrderMoneyMax", "最大消费总额");
            ReturnFields.Add("TotalUseIntegralMin", "最小消耗积分总额");
            ReturnFields.Add("TotalUseIntegralMax", "最大消耗积分总额");
            ReturnFields.Add("CurMoneyMin", "当前最低余额");
            ReturnFields.Add("CurMoneyMax", "当前最高余额");
            ReturnFields.Add("UserGroupId", "创客分组");
            ReturnFields.Add("Areas", "创客所在地区");
            ReturnFields.Add("Mobile", "手机号");

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

        #endregion




        #region 发放优惠券

        private void AssignCoupon(CouponAssignRecords data)
        {
            IQueryable<Users> users = db.Users.Where(m => m.Status == 1);
            if (data.UserMinLevel > 0)
            {
                users = users.Where(m => m.UserLevel >= data.UserMinLevel);
            }
            if (data.UserMaxLevel > 0)
            {
                users = users.Where(m => m.UserLevel <= data.UserMaxLevel);
            }
            if (!string.IsNullOrEmpty(data.Areas))
            {
                users = users.Where(m => m.Areas.StartsWith(data.Areas));
            }
            if (!string.IsNullOrEmpty(data.Mobile))
            {
                users = users.Where(m => m.Mobile.Contains(data.Mobile));
            }
            IQueryable<UserData> userDatas = db.UserData;
            if (data.TotalOrderMoneyMin > 0)
            {
                userDatas = userDatas.Where(m => m.TotalOrderMoney >= data.TotalOrderMoneyMin);
            }
            if (data.TotalOrderMoneyMax > 0)
            { 
                userDatas = userDatas.Where(m => m.TotalOrderMoney <= data.TotalOrderMoneyMax);
            }
            if (data.TotalUseIntegralMin > 0)
            {
                userDatas = userDatas.Where(m => m.TotalUseIntegral >= data.TotalUseIntegralMin);
            }
            if (data.TotalUseIntegralMax > 0)
            { 
                userDatas = userDatas.Where(m => m.TotalUseIntegral <= data.TotalUseIntegralMax);
            }
            if (data.CurMoneyMin > 0)
            {
                userDatas = userDatas.Where(m => m.CurMoney >= data.CurMoneyMin);
            }
            if (data.CurMoneyMax > 0)
            { 
                userDatas = userDatas.Where(m => m.CurMoney <= data.CurMoneyMax);
            }
            List<int> uids = new List<int>();
            foreach (UserData udata in userDatas)
            {
                uids.Add(udata.UserId);
            }
            if (uids.Count > 0)
            {
                users = users.Where(m => uids.Contains(m.Id));
            }
            string[] UserGroupId = { };
            if (!string.IsNullOrEmpty(data.UserGroupId))
            {
                UserGroupId = data.UserGroupId.Split(new char[] { ',' });
            }
            string[] CouponIdList = { };
            if (!string.IsNullOrEmpty(data.CouponIds))
            {
                CouponIdList = data.CouponIds.Split(new char[] { ',' });
            }
            foreach (Users user in users.ToList())
            {
                bool op = true;
                string[] groupIds = function.CheckNull(user.GroupId).Split(new char[] { ',' });
                if (UserGroupId.Intersect(groupIds).Count() < 1)
                {
                    op = false;
                }
                if (op)
                {
                    foreach (string CouponId in CouponIdList)
                    {
                        int CouponIdNumber = int.Parse(CouponId);
                        db.CouponsForUser.Add(new CouponsForUser() { 
                            CreateDate = DateTime.Now,
                            UpdateDate = DateTime.Now,
                            UserId = user.Id,
                            CouponId = CouponIdNumber,
                        });
                    }
                }
            }
            db.SaveChanges();
        }

        #endregion
    }
}
