/*
 * 分润奖励记录
 */

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


            string Condition = "";
            Condition += "ProfitType:\"" + data.ProfitType + "\",";
            Condition += "CheckStatus:\"" + data.CheckStatus + "\",";
            Condition += "TradeMonth:\"" + data.TradeMonth + "\",";

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

        #endregion

        #region 根据条件查询分润奖励记录列表

        /// <summary>
        /// 分润奖励记录列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(ProfitRewardRecord data, string BrandId, string MakerCode, string RealName, string ProfitTypeSelect, string CheckStatusSelect, string CreateDateData, int page = 1, int limit = 30)
        {

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

            Fields.Add("BrandId", "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(ProfitTypeSelect))
            {
                condition += " and ProfitType=" + ProfitTypeSelect;
            }
            //验证和同步账户状态
            if (!string.IsNullOrEmpty(CheckStatusSelect))
            {
                condition += " and CheckStatus=" + CheckStatusSelect;
            }
            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                var start = Convert.ToDateTime(Convert.ToDateTime(datelist[0]).ToString("yyyy-MM-dd"));
                var end = Convert.ToDateTime(Convert.ToDateTime(datelist[1]).ToString("yyyy-MM-dd") + " 23:59:59");
                var check = db.ProfitRewardRecord.Any(m => m.CreateDate >= start && m.BrandId == Convert.ToInt32(BrandId));
                var checks = db.ProfitRewardRecord.Any(m => m.CreateDate <= end && m.BrandId == Convert.ToInt32(BrandId));
                if (check)
                {
                    var sId = db.ProfitRewardRecord.Where(m => m.CreateDate >= start  && m.BrandId == Convert.ToInt32(BrandId)).Min(m => m.Id);
                    condition += "  and Id >=" + sId;
                }
                if (checks)
                {
                    var eId = db.ProfitRewardRecord.Where(m => m.CreateDate <= end && m.BrandId == Convert.ToInt32(BrandId)).Max(m => m.Id);
                    condition += " and Id <=" + eId;
                }
            }
            else
            {
                var start = Convert.ToDateTime(DateTime.Now.AddMonths(-1).ToString("yyyy-MM") + "-01");
                var check = db.ProfitRewardRecord.Any(m => m.CreateDate >= start && m.BrandId == Convert.ToInt32(BrandId));
                if (check)
                {
                    var minId = db.ProfitRewardRecord.Where(m => m.CreateDate >= start && m.BrandId == Convert.ToInt32(BrandId)).Min(m => m.Id);
                    var Info = function.ReadInstance("/WritePage/ProfitRewardRecord/ProfitRewardRecord" + BrandId + ".txt");
                    if (string.IsNullOrEmpty(Info.ToString()))
                    {
                        function.WritePage("/WritePage/ProfitRewardRecord/", "ProfitRewardRecord" + BrandId + ".txt", minId.ToString());
                        condition += " and Id >=" + minId;
                    }
                    else if (minId != int.Parse(Info))
                    {
                        function.WritePage("/WritePage/ProfitRewardRecord/", "ProfitRewardRecord" + BrandId + ".txt", minId.ToString());
                        condition += " and Id >=" + minId;
                    }
                    else
                    {
                        condition += " and Id >=" + Convert.ToInt32(Info);
                    }
                }
                else
                {
                    condition += " and Id =0";
                }
            }

            // TODO: 读取太慢，要优化
            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("ProfitRewardRecord", 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)
            {
                //创客
                int UserId = int.Parse(dic["UserId"].ToString());
                Users puser = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["MakerCode"] = puser.MakerCode;
                dic["RealName"] = puser.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 ProfitType = int.Parse(dic["ProfitType"].ToString());
                if (ProfitType == 0) dic["ProfitType"] = "直营商户交易分润";
                if (ProfitType == 1) dic["ProfitType"] = "团队交易分润";
                if (ProfitType == 2) dic["ProfitType"] = "其他";
                //创客分润类型
                int CheckStatus = int.Parse(dic["CheckStatus"].ToString());
                if (CheckStatus == 0) dic["CheckStatus"] = "初始";
                if (CheckStatus == 1) dic["CheckStatus"] = "已验证和同步";

                //其他产品交易额(元)
                string OtherTradeAmt = "";
                OtherTradeAmt += "其他产品交易总金额:" + dic["OtherTradeAmt"].ToString() + "<br />";
                OtherTradeAmt += "其他产品贷记卡交易总金额:" + dic["OtherCreditTradeAmt"].ToString() + "<br />";
                OtherTradeAmt += "其他产品借记卡非封顶交易总金额:" + dic["OtherDebitNotCapTradeAmt"].ToString() + "<br />";
                dic["OtherTradeAmt"] = OtherTradeAmt;
                //贷记卡交易金额(元)
                string CreditTradeAmt = "";
                CreditTradeAmt += "贷记卡交易总金额:" + dic["CreditTradeAmt"].ToString() + "<br />";
                CreditTradeAmt += "(云闪付)贷记卡交易总金额:" + dic["QrCreditTradeAmt"].ToString() + "<br />";
                CreditTradeAmt += "(非云闪付)贷记卡交易总金额:" + dic["NonQrCreditTradeAmt"].ToString() + "<br />";
                CreditTradeAmt += "(非扶持期)(非云闪付)贷记卡交易总金额:" + dic["NotHelpCreditTradeAmt"].ToString() + "<br />";
                CreditTradeAmt += "(扶持期)(非云闪付)贷记卡交易总金额:" + dic["HelpCreditTradeAmt"].ToString() + "<br />";
                dic["CreditTradeAmt"] = CreditTradeAmt;
                //商户借记卡交易金额(元)
                string MerDebitTradeAmt = "";
                MerDebitTradeAmt += "商户非封顶借记卡交易总额:" + dic["DebitNonCapTradeAmt"].ToString() + "<br />";
                MerDebitTradeAmt += "(云闪付)商户非封顶借记卡交易总额:" + dic["QrDebitNotCapTradeAmt"].ToString() + "<br />";
                MerDebitTradeAmt += "(非云闪付)商户非封顶借记卡交易总额:" + dic["NonQrDebitNotCapTradeAmt"].ToString() + "<br />";
                MerDebitTradeAmt += "(非扶持期)(非云闪付)借记卡非封顶交易总金额:" + dic["NotHelpDebitNonCapTradeAmt"].ToString() + "<br />";
                MerDebitTradeAmt += "(扶持期)(非云闪付)借记卡非封顶交易总金额:" + dic["HelpDebitNonCapTradeAmt"].ToString() + "<br />";
                MerDebitTradeAmt += "商户借记卡封顶交易总额:" + dic["DebitCapTradeAmt"].ToString() + "<br />";
                MerDebitTradeAmt += "商户借记卡封顶交易总笔数:" + dic["DebitCapTradeNum"].ToString() + "<br />";
                dic["MerDebitTradeAmt"] = MerDebitTradeAmt;
                //贷记卡分润金额
                string CreditProfitAmt = "";
                CreditProfitAmt += "贷记卡分润总金额:" + dic["CreditTradeProfit"].ToString() + "<br />";
                CreditProfitAmt += "(云闪付)贷记卡交易分润:" + dic["QrCreditTradeProfit"].ToString() + "<br />";
                CreditProfitAmt += "(非云闪付)贷记卡交易分润:" + dic["NonQrCreditTradeProfit"].ToString() + "<br />";
                CreditProfitAmt += "(非扶持期)(非云闪付)贷记卡分润总金额:" + dic["NotHelpCreditTradeProfit"].ToString() + "<br />";
                CreditProfitAmt += "(扶持期)(非云闪付)贷记卡分润总金额:" + dic["HelpCreditTradeProfit"].ToString() + "<br />";
                dic["CreditProfitAmt"] = CreditProfitAmt;
                //借记卡交易分润金额
                string DebitProfitAmt = "";
                DebitProfitAmt += "借记卡非封顶交易分润总金额:" + dic["DebitNonTradeCapProfit"].ToString() + "<br />";
                DebitProfitAmt += "(云闪付)借记卡非封顶交易分润总金额:" + dic["QrDebitNonTradeCapProfit"].ToString() + "<br />";
                DebitProfitAmt += "(非云闪付)借记卡非封顶交易分润总金额:" + dic["NonQrDebitNonTradeCapProfit"].ToString() + "<br />";
                DebitProfitAmt += "(非扶持期)(非云闪付)借记卡非封顶交易分润总金额:" + dic["NotHelpDebitNonTradeCapProfit"].ToString() + "<br />";
                DebitProfitAmt += "(扶持期)(非云闪付)借记卡非封顶交易分润总金额:" + dic["HelpDebitNonTradeCapProfit"].ToString() + "<br />";
                DebitProfitAmt += "借记卡封顶交易分润总金额:" + dic["DebitTradeCapProfit"].ToString() + "<br />";
                dic["DebitProfitAmt"] = DebitProfitAmt;
            }
            Dictionary<string, object> other = new Dictionary<string, object>();
            string MerchantTradeAmount = "0.00";//商户交易总额
            string CreditTradeAmount = "0.00";//贷记卡交易总金额
            string MerchantProfitAmount = "0.00";//商户交易分润总金额
            string CreditProfitAmount = "0.00";//贷记卡分润总金额
            // TODO: 读取太慢，要优化
            DataTable dt = OtherMySqlConn.dtable("SELECT SUM(if(BrandId=" + BrandId + ",TradeAmt,0)),SUM(if(BrandId=" + BrandId + ",CreditTradeAmt,0)),SUM(if(BrandId=" + BrandId + ",TradeProfit,0)),SUM(if(BrandId=" + BrandId + ",CreditTradeProfit,0)) FROM ProfitRewardRecord where 1=1 " + condition);
            if (dt.Rows.Count > 0)
            {
                MerchantTradeAmount = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString())).ToString();
                CreditTradeAmount = decimal.Parse(function.CheckNum(dt.Rows[0][1].ToString())).ToString();
                MerchantProfitAmount = decimal.Parse(function.CheckNum(dt.Rows[0][2].ToString())).ToString();
                CreditProfitAmount = decimal.Parse(function.CheckNum(dt.Rows[0][3].ToString())).ToString();
            }
            other.Add("MerchantTradeAmount", MerchantTradeAmount);
            other.Add("CreditTradeAmount", CreditTradeAmount);
            other.Add("MerchantProfitAmount", MerchantProfitAmount);
            other.Add("CreditProfitAmount", CreditProfitAmount);
            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(ProfitRewardRecord 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("ProfitRewardRecord", Fields, 0);
            AddSysLog(data.Id.ToString(), "ProfitRewardRecord", "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;


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

        #endregion

        #region 修改分润奖励记录

        /// <summary>
        /// 增加或修改分润奖励记录信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(ProfitRewardRecord 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("ProfitRewardRecord", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "ProfitRewardRecord", "update");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 删除分润奖励记录信息

        /// <summary>
        /// 删除分润奖励记录信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "ProfitRewardRecord", "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("ProfitRewardRecord", 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, "ProfitRewardRecord", "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("ProfitRewardRecord", 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, "ProfitRewardRecord", "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("ProfitRewardRecord", 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("ProfitRewardRecord", Sort, Id);

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

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

        #region 导出Excel

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

            Fields.Add("BrandId", "1");
            Fields.Add("CreateDate", "3"); //交易时间
            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(ProfitTypeSelect))
            {
                condition += " and ProfitType=" + ProfitTypeSelect;
            }
            //验证和同步账户状态
            if (!string.IsNullOrEmpty(CheckStatusSelect))
            {
                condition += " and CheckStatus=" + CheckStatusSelect;
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("ProfitRewardRecord", Fields, "Id desc", "0", 1, 20000, condition, "UserId,TopUserId,ProfitType,OtherTradeAmt,OtherCreditTradeAmt,OtherDebitNotCapTradeAmt,TradeAmt,CreditTradeAmt,QrCreditTradeAmt,NonQrCreditTradeAmt,DebitNonCapTradeAmt,QrDebitNotCapTradeAmt,NonQrDebitNotCapTradeAmt,DebitCapTradeAmt,DebitCapTradeNum,TradeProfit,CreditTradeProfit,QrCreditTradeProfit,NonQrCreditTradeProfit,DebitNonTradeCapProfit,QrDebitNonTradeCapProfit,NonQrDebitNonTradeCapProfit,DebitTradeCapProfit,CheckStatus,TradeMonth,RecordNo", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                //创客
                int UserId = int.Parse(dic["UserId"].ToString());
                Users puser = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["MakerCode"] = puser.MakerCode;
                dic["RealName"] = puser.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 ProfitType = int.Parse(dic["ProfitType"].ToString());
                if (ProfitType == 0) dic["ProfitType"] = "直营商户交易分润";
                if (ProfitType == 1) dic["ProfitType"] = "团队交易分润";
                if (ProfitType == 2) dic["ProfitType"] = "其他";
                //创客分润类型
                int CheckStatus = int.Parse(dic["CheckStatus"].ToString());
                if (CheckStatus == 0) dic["CheckStatus"] = "初始";
                if (CheckStatus == 1) dic["CheckStatus"] = "已验证和同步";
                dic.Remove("UserId");
                dic.Remove("TopUserId");
            }

            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("RecordNo", "记录单号");
            ReturnFields.Add("MakerCode", "创客编号");
            ReturnFields.Add("RealName", "创客姓名");
            ReturnFields.Add("TopMakerCode", "顶级创客编号");
            ReturnFields.Add("TopRealName", "顶级创客名称");
            ReturnFields.Add("TradeMonth", "交易月");
            ReturnFields.Add("ProfitType", "创客分润类型");
            ReturnFields.Add("OtherTradeAmt", "其他产品交易总金额");
            ReturnFields.Add("OtherCreditTradeAmt", "其他产品贷记卡交易总金额");
            ReturnFields.Add("OtherDebitNotCapTradeAmt", "其他产品借记卡非封顶交易总金额");
            ReturnFields.Add("TradeAmt", "商户交易总额");
            ReturnFields.Add("CreditTradeAmt", "贷记卡交易总金额");
            ReturnFields.Add("QrCreditTradeAmt", "(云闪付)贷记卡交易总金额");
            ReturnFields.Add("NonQrCreditTradeAmt", "(非云闪付)贷记卡交易总金额");
            ReturnFields.Add("DebitNonCapTradeAmt", "商户非封顶借记卡交易总额");
            ReturnFields.Add("QrDebitNotCapTradeAmt", "(云闪付)商户非封顶借记卡交易总额");
            ReturnFields.Add("NonQrDebitNotCapTradeAmt", "(非云闪付)商户非封顶借记卡交易总额");
            ReturnFields.Add("DebitCapTradeAmt", "商户借记卡封顶交易总额");
            ReturnFields.Add("DebitCapTradeNum", "商户借记卡封顶交易总笔数");
            ReturnFields.Add("TradeProfit", "交易分润");
            ReturnFields.Add("CreditTradeProfit", "贷记卡分润总金额");
            ReturnFields.Add("QrCreditTradeProfit", "(云闪付)贷记卡交易分润");
            ReturnFields.Add("NonQrCreditTradeProfit", "(非云闪付)贷记卡交易分润");
            ReturnFields.Add("DebitNonTradeCapProfit", "借记卡非封顶交易分润总金额");
            ReturnFields.Add("QrDebitNonTradeCapProfit", "(云闪付)借记卡非封顶交易分润总金额");
            ReturnFields.Add("NonQrDebitNonTradeCapProfit", "(非云闪付)借记卡非封顶交易分润总金额");
            ReturnFields.Add("DebitTradeCapProfit", "借记卡封顶交易分润总金额");
            ReturnFields.Add("CheckStatus", "验证和同步账户状态");

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

        #endregion






        #region 同步到余额

        public string SycnData(int BrandId, int OpType = 0)
        {
            string date = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            string OpTypeString = "";
            if (OpType > 0)
            {
                OpTypeString += "-" + OpType;
            }
            string check = function.ReadInstance("/Balance/" + BrandId + "/" + date + OpTypeString + ".txt");
            if (string.IsNullOrEmpty(check))
            {
                function.WritePage("/Balance/" + BrandId + "/", date + OpTypeString + ".txt", DateTime.Now.ToString());
                RedisDbconn.Instance.AddList("SycnProfitQueue2", BrandId + "#cut#" + date + "#cut#" + OpType + "#cut#" + SysUserName);
                return "success";
            }
            return date + "分润已同步，请勿重复操作";
        }

        public string SycnDataByCondi(int BrandId, string MakerCode, int OpType = 0)
        {
            string date = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            string OpTypeString = "";
            if (OpType > 0)
            {
                OpTypeString += "-" + OpType;
            }
            string check = function.ReadInstance("/Balance/" + BrandId + "/" + MakerCode + "/" + date + OpTypeString + ".txt");
            if (string.IsNullOrEmpty(check))
            {
                function.WritePage("/Balance/" + BrandId + "/" + MakerCode + "/", date + OpTypeString + ".txt", DateTime.Now.ToString());
                UserForMakerCode forMakerCode = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode) ?? new UserForMakerCode();
                DoTradeProfitByCondi(forMakerCode.UserId, BrandId, date, OpType);
                DoSubsidyProfitByCondi(forMakerCode.UserId, BrandId, date, OpType);
                return "success";
            }
            return date + "分润已同步，请勿重复操作";
        }

        //交易分润
        private void DoTradeProfitByCondi(int Id, int BrandId, string date, int OpType = 0)
        {
            int OpTypeDo = OpType + 1;
            WebCMSEntities db = new WebCMSEntities();
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            DataTable dt = OtherMySqlConn.dtable("select UserId,ProfitType,sum(CreditTradeProfit+DebitNonTradeCapProfit+DebitTradeCapProfit+QrCreditTradeProfit) from ProfitRewardRecord where CheckStatus=" + OpType + " and BrandId=" + BrandId + " and TradeMonth='" + date + "' and UserId=" + Id + " group by UserId,ProfitType");
            foreach (DataRow dr in dt.Rows)
            {
                int UserId = int.Parse(dr["UserId"].ToString());
                ulong ProfitType = ulong.Parse(dr["ProfitType"].ToString());
                OtherMySqlConn.op("update ProfitRewardRecord set CheckStatus=" + OpTypeDo + " where BrandId=" + BrandId + " and TradeMonth='" + date + "' and UserId=" + UserId + " and ProfitType=" + ProfitType);
                decimal ProfitMoney = decimal.Parse(dr[2].ToString());
                var tran = db.Database.BeginTransaction();
                try
                {
                    Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                    if (OpType == 0)
                    {
                        ProfitRecord profit = db.ProfitRecord.FirstOrDefault(m => m.UserId == UserId && m.BrandId == BrandId && m.SeoTitle == date);
                        if (profit == null)
                        {
                            profit = db.ProfitRecord.Add(new ProfitRecord()
                            {
                                CreateDate = DateTime.Now,
                                CreateMan = SysUserName,
                                SeoTitle = date,
                                ParentNav = user.ParentNav,
                                BrandId = BrandId,
                                UserId = UserId,
                            }).Entity;
                            db.SaveChanges();
                        }
                        profit.ProfitAmount += ProfitMoney;
                        string IdBrand = UserId + "_" + BrandId;
                        UserMachineData MachineData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
                        if (MachineData != null)
                        {
                            MachineData.TradeProfit += ProfitMoney;
                        }
                        db.SaveChanges();
                    }
                    else if (OpType == 1)
                    {
                        UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == UserId);
                        if (account == null)
                        {
                            account = db.UserAccount.Add(new UserAccount()
                            {
                                Id = UserId,
                                UserId = UserId,
                            }).Entity;
                            db.SaveChanges();
                        }
                        decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                        decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                        decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                        account.BalanceAmount += ProfitMoney;
                        account.TotalAmount += ProfitMoney;
                        decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                        decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                        decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
                        UserAccountRecord add = db.UserAccountRecord.Add(new UserAccountRecord()
                        {
                            CreateDate = DateTime.Now,
                            UpdateDate = DateTime.Now,
                            UserId = UserId, //创客
                            ProductType = BrandId,
                            ChangeType = 1, //变动类型
                            ChangeAmount = ProfitMoney, //变更金额
                            BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                            AfterTotalAmount = AfterTotalAmount, //变更后总金额
                            BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                            AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                            BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                            AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                            Remark = ProfitType == 1 ? "直拓商户分润" : "品牌推广服务费",
                        }).Entity;
                        db.SaveChanges();
                        PublicFunction.SplitUserAccountRecord(add);
                        RedisDbconn.Instance.Clear("UserAccount:" + UserId);
                        RedisDbconn.Instance.Clear("UserAccount:Income:" + UserId + ":" + DateTime.Now.ToString("yyyyMM"));
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + UserId + "," + ProfitType + "," + ProfitMoney + "\n" + ex.ToString(), "同步到余额异常");
                    tran.Rollback();
                }
            }
            db.Dispose();
        }
        //分润补贴
        private void DoSubsidyProfitByCondi(int Id, int BrandId, string date, int OpType = 0)
        {
            int OpTypeDo = OpType + 1;
            WebCMSEntities db = new WebCMSEntities();
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            DataTable dt = OtherMySqlConn.dtable("select SubsidyUserId,sum(SubsidyProfitRate) from ProfitSubsidyDetail where Status=" + OpType + " and BrandId=" + BrandId + " and TradeMonth='" + date + "' and SubsidyUserId=" + Id + " GROUP BY SubsidyUserId");
            foreach (DataRow dr in dt.Rows)
            {
                int UserId = int.Parse(dr["SubsidyUserId"].ToString());
                decimal ProfitMoney = decimal.Parse(dr[1].ToString());
                OtherMySqlConn.op("update ProfitSubsidyDetail set Status=" + OpTypeDo + " where BrandId=" + BrandId + " and TradeMonth='" + date + "' and SubsidyUserId=" + Id + "");
                var tran = db.Database.BeginTransaction();
                try
                {
                    Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                    if (OpType == 0)
                    {
                        string IdBrand = UserId + "_" + BrandId;
                        UserMachineData MachineData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
                        if (MachineData != null)
                        {
                            MachineData.OtherProfit += ProfitMoney;
                        }
                        db.SaveChanges();
                    }
                    else if (OpType == 1)
                    {
                        UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == UserId);
                        if (account == null)
                        {
                            account = db.UserAccount.Add(new UserAccount()
                            {
                                Id = UserId,
                                UserId = UserId,
                            }).Entity;
                            db.SaveChanges();
                        }
                        decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                        decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                        decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                        account.BalanceAmount += ProfitMoney;
                        account.TotalAmount += ProfitMoney;
                        decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                        decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                        decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
                        UserAccountRecord add = db.UserAccountRecord.Add(new UserAccountRecord()
                        {
                            CreateDate = DateTime.Now,
                            UpdateDate = DateTime.Now,
                            UserId = UserId, //创客
                            ProductType = BrandId,
                            ChangeType = 111, //变动类型
                            ChangeAmount = ProfitMoney, //变更金额
                            BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                            AfterTotalAmount = AfterTotalAmount, //变更后总金额
                            BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                            AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                            BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                            AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                            Remark = "直拓商户补贴",
                        }).Entity;
                        db.SaveChanges();
                        PublicFunction.SplitUserAccountRecord(add);
                        RedisDbconn.Instance.Clear("UserAccount:" + UserId);
                        RedisDbconn.Instance.Clear("UserAccount:Income:" + UserId + ":" + DateTime.Now.ToString("yyyyMM"));
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + UserId + "," + ProfitMoney + "\n" + ex.ToString(), "同步到补贴异常");
                    tran.Rollback();
                }
            }
            db.Dispose();
        }

        //直拓商户分润
        //品牌推广服务费
        //品牌名称(交易分润)  备注：***

        #endregion


    }
}
