/*
 * 商户返利明细
 */

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

            return View();
        }

        #endregion

        #region 根据条件查询商户返利明细列表

        /// <summary>
        /// 商户返利明细列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(MerchantRebateDetail data, string MerchantNo, string MerchantName, string TradeMonthSelect, string SyncStatusSelect, int page = 1, int limit = 30)
        {

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

            Fields.Add("BrandId", "1"); //品牌
            Fields.Add("CreateDate", "3"); //时间
            Fields.Add("SnNo", "2"); //渠道SN号

            string condition = " and Status>-1";
            //商户编号
            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(TradeMonthSelect))
            {
                condition += " and TradeMonth=" + TradeMonthSelect.Replace("-", "");
            }
            //同步状态
            if (!string.IsNullOrEmpty(SyncStatusSelect))
            {
                condition += " and SyncStatus=" + SyncStatusSelect;
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("MerchantRebateDetail", 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 MerchantId = int.Parse(dic["MerchantId"].ToString());
                MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new MerchantInfo();
                dic["MerchantNo"] = "";
                dic["MerchantName"] = merchant.Name;
                dic["MerchantRealName"] = "";

                // int SyncStatus = int.Parse(dic["SyncStatus"].ToString());
                // if (SyncStatus == 0) dic["SyncStatus"] = "初始";
                // if (SyncStatus == 1) dic["SyncStatus"] = "已验证和同步";
            }
            Dictionary<string, object> other = new Dictionary<string, object>();
            string CreditTradeAmt = "0.00", DebitTradeAmt = "0.00", CreditPrizeAmt = "0.00", DebitPrizeAmt = "0.00";
            DataTable dt = OtherMySqlConn.dtable("select sum(CreditTradeAmt),sum(DebitTradeAmt),sum(CreditPrizeAmt),sum(DebitPrizeAmt) from MerchantRebateDetail where 1=1" + condition);
            if(dt.Rows.Count > 0)
            {
                CreditTradeAmt = dt.Rows[0][0].ToString();
                DebitTradeAmt = dt.Rows[0][1].ToString();
                CreditPrizeAmt = dt.Rows[0][2].ToString();
                DebitPrizeAmt = dt.Rows[0][3].ToString();
            }
            other.Add("CreditTradeAmt", CreditTradeAmt);
            other.Add("DebitTradeAmt", DebitTradeAmt);
            other.Add("CreditPrizeAmt", CreditPrizeAmt);
            other.Add("DebitPrizeAmt", DebitPrizeAmt);
            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(MerchantRebateDetail 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("MerchantRebateDetail", Fields, 0);
            AddSysLog(data.Id.ToString(), "MerchantRebateDetail", "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;


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

        #endregion

        #region 修改商户返利明细

        /// <summary>
        /// 增加或修改商户返利明细信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(MerchantRebateDetail 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("MerchantRebateDetail", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "MerchantRebateDetail", "update");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 删除商户返利明细信息

        /// <summary>
        /// 删除商户返利明细信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "MerchantRebateDetail", "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("MerchantRebateDetail", 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, "MerchantRebateDetail", "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("MerchantRebateDetail", 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, "MerchantRebateDetail", "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("MerchantRebateDetail", 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("MerchantRebateDetail", Sort, Id);

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

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

        #region 导出Excel

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

            Fields.Add("BrandId", "1"); //品牌
            Fields.Add("CreateDate", "3"); //时间
            Fields.Add("SnNo", "2"); //渠道SN号

            string condition = " and Status>-1";
            //商户编号
            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(TradeMonthSelect))
            {
                condition += " and TradeMonth=" + TradeMonthSelect.Replace("-", "");
            }
            //同步状态
            if (!string.IsNullOrEmpty(SyncStatusSelect))
            {
                condition += " and SyncStatus=" + SyncStatusSelect;
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("MerchantRebateDetail", Fields, "Id desc", "0", 1, 20000, condition, "BrandId,TradeMonth,TradeDate,MerNo,SnNo,MerRegTime,MerStandardDate,MerchantId,MmpUserNo,MmpUserName,CreditTradeAmt,DebitTradeAmt,CreditRewardAmount,DebitRewardAmount,SyncStatus,RewardDesc", 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 MerchantId = int.Parse(dic["MerchantId"].ToString());
                MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new MerchantInfo();
                dic["MerchantNo"] = "";
                dic["MerchantName"] = merchant.Name;
                dic["MerchantRealName"] = "";

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

                dic.Remove("MerchantId");
            }

            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("BrandId", "产品类型");
            ReturnFields.Add("TradeDate", "达标日期");
            ReturnFields.Add("MerNo", "快钱商户编号");
            ReturnFields.Add("SnNo", "快钱SN号");
            ReturnFields.Add("TradeMonth", "交易月");
            ReturnFields.Add("MerRegTime", "快钱注册时间");
            ReturnFields.Add("MerStandardDate", "商户激活时间");
            ReturnFields.Add("MerchantName", "商户名称");
            ReturnFields.Add("MerchantMobile", "商户手机号");
            ReturnFields.Add("MerchantRealName", "商户真实姓名");
            ReturnFields.Add("MmpUserNo", "KYS刷APP用户编号");
            ReturnFields.Add("MmpUserName", "KYS商户真实姓名");
            ReturnFields.Add("CreditTradeAmt", "贷记卡交易总金额（元）");
            ReturnFields.Add("DebitTradeAmt", "借记卡交易总金额（元）");
            ReturnFields.Add("CreditRewardAmount", "贷记卡交易奖励金额（元）");
            ReturnFields.Add("DebitRewardAmount", "借记卡交易奖励金额（元）");
            ReturnFields.Add("SyncStatus", "同步MMP");
            ReturnFields.Add("RewardDesc", "奖励描述");
            ReturnFields.Add("CreateDate", "创建时间");
            result.Add("Fields", ReturnFields);
            AddSysLog("0", "MerchantRebateDetail", "ExportExcel");
            return Json(result);
        }

        #endregion

    }
}
