/*
 * 开机奖励明细
 */

using System;
using System.Web;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Data;
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 OpenRewardDetailController : BaseController
    {
        public OpenRewardDetailController(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(OpenRewardDetail data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            return View();
        }

        #endregion

        #region 根据条件查询开机奖励明细列表

        /// <summary>
        /// 开机奖励明细列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(OpenRewardDetail data, string MakerCode, string RealName, string MerchantNo, string MerchantName, string TradeDateData, int page = 1, int limit = 30)
        {

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

            Fields.Add("BrandId", "0"); //品牌
            Fields.Add("SnNo", "1"); //SN号
            Fields.Add("MerNo", "1"); //渠道商户号
            Fields.Add("TopUserId", "0"); //顶级创客

            string condition = " and Status>-1";
            //创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            //创客名称
            if (!string.IsNullOrEmpty(RealName))
            {
                condition += " and UserId in (select UserId from UserForRealName where RealName='" + RealName + "')";
            }
            //商户编号
            if (!string.IsNullOrEmpty(MerchantNo))
            {
                condition += " and MerchantId in (select MerchantId from MerchantForCode where Code='" + MerchantNo + "')";
            }
            //商户名称
            if (!string.IsNullOrEmpty(MerchantName))
            {
                condition += " and MerchantId in (select MerchantId from MerchantForName where Name='" + MerchantName + "')";
            }
            // 交易时间
            if(!string.IsNullOrEmpty(TradeDateData))
            {
                string[] datelist = TradeDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and TradeDate>='" + start + " 00:00:00' and TradeDate<='" + end + " 23:59:59'";
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("OpenRewardDetail", Fields, "Id desc", "0", page, limit, condition);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                dic["BrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["BrandId"].ToString()));

                int UserId = int.Parse(dic["UserId"].ToString());
                Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["MakerCode"] = user.MakerCode;
                dic["RealName"] = user.RealName;

                int TopUserId = int.Parse(dic["TopUserId"].ToString());
                Users tuser = db.Users.FirstOrDefault(m => m.Id == TopUserId) ?? new Users();
                dic["TopMakerCode"] = tuser.MakerCode;
                dic["TopRealName"] = tuser.RealName;
                
                int DirectUserId = int.Parse(dic["DirectUserId"].ToString());
                Users duser = db.Users.FirstOrDefault(m => m.Id == DirectUserId) ?? new Users();
                dic["DirectMakerCode"] = duser.MakerCode;
                dic["DirectRealName"] = duser.RealName;

                int SnApplyUserId = int.Parse(dic["SnApplyUserId"].ToString());
                Users auser = db.Users.FirstOrDefault(m => m.Id == SnApplyUserId) ?? new Users();
                dic["SnApplyMakerCode"] = auser.MakerCode;
                dic["SnApplyRealName"] = auser.RealName;

                int MerchantId = int.Parse(dic["MerchantId"].ToString());
                MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new MerchantInfo();
                dic["MerchantNo"] = "";
                dic["MerchantName"] = merchant.Name;

                int SnStoreId = int.Parse(dic["SnStoreId"].ToString());
                StoreHouse store = db.StoreHouse .FirstOrDefault(m => m.Id == SnStoreId) ?? new StoreHouse ();
                dic["StoreNo"] = store.StoreNo;
                dic["StoreName"] = store.StoreName;

                int SnType = int.Parse(dic["SnType"].ToString());
                if (SnType == 0) dic["SnType"] = "兑换机具";
                if (SnType == 1) dic["SnType"] = "循环机具";

                int MerBuddyType = int.Parse(dic["MerBuddyType"].ToString());
                if (MerBuddyType == 0) dic["MerBuddyType"] = "非商户型创客";
                if (MerBuddyType == 1) dic["MerBuddyType"] = "商户型创客";

                int RewardType = int.Parse(dic["RewardType"].ToString());
                if (RewardType == 0) dic["RewardType"] = "无开机奖励";
                if (RewardType == 1) dic["RewardType"] = "开机直接奖励";
                if (RewardType == 2) dic["RewardType"] = "开机间接奖励";

                int CheckStatus = int.Parse(dic["CheckStatus"].ToString());
                if (CheckStatus == 0) dic["CheckStatus"] = "初始";
                if (CheckStatus == 1) dic["CheckStatus"] = "已验证和同步";
                
            }
            Dictionary<string, object> other = new Dictionary<string, object>();
            string CreditTradeAmt = "0.00", DebitTradeAmt = "0.00", CreditRewardAmount = "0.00", DebitRewardAmount = "0.00";//贷记卡交易总额 借记卡交易总额 贷记卡交易奖励金额 借记记卡交易奖励金额
            DataTable dt = OtherMySqlConn.dtable("select sum(CreditTradeAmt),sum(DebitTradeAmt),sum(CreditRewardAmount),sum(DebitRewardAmount) from OpenRewardDetail where 1=1" + condition);
            if(dt.Rows.Count > 0)
            {
                CreditTradeAmt = dt.Rows[0][0].ToString();
                DebitTradeAmt = dt.Rows[0][1].ToString();
                CreditRewardAmount = dt.Rows[0][2].ToString();
                DebitRewardAmount = dt.Rows[0][3].ToString();

            }
            other.Add("CreditTradeAmt", CreditTradeAmt);
            other.Add("DebitTradeAmt", DebitTradeAmt);
            other.Add("CreditRewardAmount", CreditRewardAmount);
            other.Add("DebitRewardAmount", DebitRewardAmount);
            obj.Add("other", other);
            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(OpenRewardDetail data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();


            Fields.Add("SeoTitle", data.SeoTitle);
            Fields.Add("SeoKeyword", data.SeoKeyword);
            Fields.Add("SeoDescription", data.SeoDescription);
            int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Add("OpenRewardDetail", Fields, 0);
            AddSysLog(data.Id.ToString(), "OpenRewardDetail", "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;


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

        #endregion

        #region 修改开机奖励明细

        /// <summary>
        /// 增加或修改开机奖励明细信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(OpenRewardDetail data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();


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

            return "success";
        }

        #endregion

        #region 删除开机奖励明细信息

        /// <summary>
        /// 删除开机奖励明细信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "OpenRewardDetail", "del");
            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("OpenRewardDetail", Fields, id);
            }
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 开启

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

            AddSysLog(Id.ToString(), "OpenRewardDetail", "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.OpenRewardDetail.Add(new OpenRewardDetail()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(OpenRewardDetail data, string MakerCode, string RealName, string MerchantNo, string MerchantName)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();

            Fields.Add("TradeDate", "3"); //达标日期
            Fields.Add("BrandId", "0"); //品牌
            Fields.Add("SnNo", "1"); //SN号
            Fields.Add("MerNo", "1"); //渠道商户号
            Fields.Add("TopUserId", "0"); //顶级创客

            string condition = " and Status>-1";
            //创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            //创客名称
            if (!string.IsNullOrEmpty(RealName))
            {
                condition += " and UserId in (select UserId from UserForRealName where RealName='" + RealName + "')";
            }
            //商户编号
            if (!string.IsNullOrEmpty(MerchantNo))
            {
                condition += " and MerchantId in (select MerchantId from MerchantForCode where Code='" + MerchantNo + "')";
            }
            //商户名称
            if (!string.IsNullOrEmpty(MerchantName))
            {
                condition += " and MerchantId in (select MerchantId from MerchantForName where Name='" + MerchantName + "')";
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("OpenRewardDetail", Fields, "Id desc", "0", 1, 20000, condition, "TradeDate,UserId,TopUserId,BrandId,MerchantId,DirectUserId,SnNo,MerNo,SnType,SnApplyUserId,StandardDate,SnStoreId,MerBuddyType,RewardType,CreditTradeAmt,DebitTradeAmt,CreditRewardAmount,DebitRewardAmount,OpenRewardNo,RewardDesc,CheckStatus", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                dic["BrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["BrandId"].ToString()));

                int UserId = int.Parse(dic["UserId"].ToString());
                Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["MakerCode"] = user.MakerCode;
                dic["RealName"] = user.RealName;

                int TopUserId = int.Parse(dic["TopUserId"].ToString());
                Users tuser = db.Users.FirstOrDefault(m => m.Id == TopUserId) ?? new Users();
                dic["TopMakerCode"] = tuser.MakerCode;
                dic["TopRealName"] = tuser.RealName;
                
                int DirectUserId = int.Parse(dic["DirectUserId"].ToString());
                Users duser = db.Users.FirstOrDefault(m => m.Id == DirectUserId) ?? new Users();
                dic["DirectMakerCode"] = duser.MakerCode;
                dic["DirectRealName"] = duser.RealName;

                int SnApplyUserId = int.Parse(dic["SnApplyUserId"].ToString());
                Users auser = db.Users.FirstOrDefault(m => m.Id == SnApplyUserId) ?? new Users();
                dic["SnApplyMakerCode"] = auser.MakerCode;
                dic["SnApplyRealName"] = auser.RealName;

                int MerchantId = int.Parse(dic["MerchantId"].ToString());
                MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new MerchantInfo();
                dic["MerchantNo"] = "";
                dic["MerchantName"] = merchant.Name;

                int SnStoreId = int.Parse(dic["SnStoreId"].ToString());
                StoreHouse store = db.StoreHouse .FirstOrDefault(m => m.Id == SnStoreId) ?? new StoreHouse ();
                dic["StoreNo"] = store.StoreNo;
                dic["StoreName"] = store.StoreName;

                int SnType = int.Parse(dic["SnType"].ToString());
                if (SnType == 0) dic["SnType"] = "兑换机具";
                if (SnType == 1) dic["SnType"] = "循环机具";

                int MerBuddyType = int.Parse(dic["MerBuddyType"].ToString());
                if (MerBuddyType == 0) dic["MerBuddyType"] = "非商户型创客";
                if (MerBuddyType == 1) dic["MerBuddyType"] = "商户型创客";

                int RewardType = int.Parse(dic["RewardType"].ToString());
                if (RewardType == 0) dic["RewardType"] = "无开机奖励";
                if (RewardType == 1) dic["RewardType"] = "开机直接奖励";
                if (RewardType == 2) dic["RewardType"] = "开机间接奖励";

                int CheckStatus = int.Parse(dic["CheckStatus"].ToString());
                if (CheckStatus == 0) dic["CheckStatus"] = "初始";
                if (CheckStatus == 1) dic["CheckStatus"] = "已验证和同步";

                dic.Remove("UserId");
                dic.Remove("TopUserId");
                dic.Remove("DirectUserId");
                dic.Remove("SnApplyUserId");
                dic.Remove("MerchantId");
                dic.Remove("SnStoreId");
            }

            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("MakerCode", "奖励创客编号");
            ReturnFields.Add("RealName", "奖励创客名称");
            ReturnFields.Add("TradeDate", "达标日期");
            ReturnFields.Add("TopMakerCode", "顶级创客编号");
            ReturnFields.Add("TopRealName", "顶级创客名称");
            ReturnFields.Add("BrandId", "产品名称");
            ReturnFields.Add("MerchantNo", "商户编号");
            ReturnFields.Add("MerchantName", "商户名称");
            ReturnFields.Add("DirectMakerCode", "商户直属创客编号");
            ReturnFields.Add("DirectRealName", "商户直属创客名称");
            ReturnFields.Add("MerNo", "快钱商户编号");
            ReturnFields.Add("SnNo", "快钱SN号");
            ReturnFields.Add("SnType", "机具类型");
            ReturnFields.Add("SnApplyMakerCode", "机具申请创客编号");
            ReturnFields.Add("SnApplyRealName", "机具申请创客姓名");
            ReturnFields.Add("StandardDate", "商户的激活日期");
            ReturnFields.Add("SnStoreNo", "SN仓库编号");
            ReturnFields.Add("SnStoreName", "SN仓库名称");
            ReturnFields.Add("MerBuddyType", "商户创客类型");
            ReturnFields.Add("RewardType", "奖励类型");
            ReturnFields.Add("CreditTradeAmt", "贷记卡交易总金额元)'");
            ReturnFields.Add("DebitTradeAmt", "借记卡交易总金额元)'");
            ReturnFields.Add("CreditRewardAmount", "贷记卡交易奖励金额元)'");
            ReturnFields.Add("DebitRewardAmount", "借记记卡交易奖励金额元)'");
            ReturnFields.Add("OpenRewardNo", "开机奖励单号");
            ReturnFields.Add("CheckStatus", "同步状态");
            ReturnFields.Add("RewardDesc", "奖励描述");
            ReturnFields.Add("CreateDate", "创建时间");

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

        #endregion

    }
}
