/*
 * 提现记录
 */

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 UserCashRecordController : BaseController
    {
        public UserCashRecordController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
            OtherMySqlConn.connstr = ConfigurationManager.AppSettings["SqlConnStr"].ToString();//111
        }

        #region 提现记录列表

        /// <summary>
        /// 根据条件查询提现记录列表
        /// </summary>
        /// <returns></returns>
        public IActionResult Index(UserCashRecord data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;


            string Condition = "";
            Condition += "CashOrderNo:\"" + data.CashOrderNo + "\",";
            Condition += "TradeType:\"" + data.TradeType + "\",";

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

        #endregion

        #region 根据条件查询提现记录列表

        /// <summary>
        /// 提现记录列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(UserCashRecord data, string MakerCode, string RealName, string StatusSelect, string QueryCountSelect, string CreateDateData, int page = 1, int limit = 30)
        {

            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("CashOrderNo", "1"); //提现单号
            Fields.Add("TradeType", "0"); //交易类型

            string condition = " and Status>-1 and TradeType<3";
            //创客编号
            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(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }
            if (!string.IsNullOrEmpty(data.CashOrderNo))
            {
                condition += " and CashOrderNo='" + data.CashOrderNo + "'";
            }
            if (data.TradeType > 0)
            {
                condition += " and TradeType=" + data.TradeType;
            }
            //提交到代付状态
            if (!string.IsNullOrEmpty(QueryCountSelect))
            {
                if(QueryCountSelect == "0")
                {
                    condition += " and QueryCount=" + QueryCountSelect;
                }
                else
                {
                    condition += " and QueryCount>0";
                }
            }

            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.UserCashRecord.Any(m => m.CreateDate >= start && m.TradeType < 3);
                var checks = db.UserCashRecord.Any(m => m.CreateDate <= end && m.TradeType < 3);
                if (check)
                {
                    var sId = db.UserCashRecord.Where(m => m.CreateDate >= start && m.TradeType < 3).Min(m => m.Id);
                    condition += "  and Id >=" + sId;
                }
                if (checks)
                {
                    var eId = db.UserCashRecord.Where(m => m.CreateDate <= end && m.TradeType < 3).Max(m => m.Id);
                    condition += " and Id <=" + eId;
                }
            }
            else
            {
                var start = Convert.ToDateTime(DateTime.Now.AddMonths(-1).ToString("yyyy-MM") + "-01");
                var check = db.UserCashRecord.Any(m => m.CreateDate >= start && m.TradeType < 3);
                if (check)
                {
                    var minId = db.UserCashRecord.Where(m => m.CreateDate >= start && m.TradeType < 3).Min(m => m.Id);
                    var Info = function.ReadInstance("/WritePage/UserCashRecord/UserCashRecord.txt");
                    if (string.IsNullOrEmpty(Info.ToString()))
                    {
                        function.WritePage("/WritePage/UserCashRecord/", "UserCashRecord.txt", minId.ToString());
                        condition += " and Id >=" + minId;
                    }
                    else if (minId != int.Parse(Info))
                    {
                        function.WritePage("/WritePage/UserCashRecord/", "UserCashRecord.txt", minId.ToString());
                        condition += " and Id >=" + minId;
                    }
                    else
                    {
                        condition += " and Id >=" + Convert.ToInt32(Info);
                    }
                }
                else
                {
                    condition += " and Id =0";
                }
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("UserCashRecord", 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 user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["MakerCode"] = user.MakerCode;
                dic["RealName"] = user.RealName;
                dic["TradeType"] = RelationClassForConst.GetTradeTypeInfo(int.Parse(dic["TradeType"].ToString()));
                int Status = int.Parse(dic["Status"].ToString());
                if (Status == 0) dic["StatusName"] = "处理中";
                if (Status == 1) dic["StatusName"] = "成功";
                if (Status == 2) dic["StatusName"] = "失败";

                int QueryCount = int.Parse(dic["QueryCount"].ToString());
                if (QueryCount == 0) dic["LockName"] = "待提交";
                if (QueryCount > 0) dic["LockName"] = "已提交";
            }
            Dictionary<string, object> other = new Dictionary<string, object>();

            string WaitAmount = "0.00";//待处理总金额
            string SuccessAmount = "0.00";//提现成功总金额
            string FailAmount = "0.00";//提现失败总金额
            string WaitTaxAmount = "0.00";//待处理总金额(税后)
            string SuccessTaxAmount = "0.00";//提现成功总金额(税后)
            string FailTaxAmount = "0.00";//提现失败总金额(税后)
            DataTable dt = OtherMySqlConn.dtable("SELECT SUM(if(Status=0,TradeAmount,0)),SUM(if(Status=1,TradeAmount,0)),SUM(if(Status=2,TradeAmount,0)),SUM(if(Status=0,ActualTradeAmount,0)),SUM(if(Status=1,ActualTradeAmount,0)),SUM(if(Status=2,ActualTradeAmount,0)) FROM UserCashRecord where 1=1 " + condition);
            if (dt.Rows.Count > 0)
            {
                WaitAmount = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString())).ToString("f2");
                SuccessAmount = decimal.Parse(function.CheckNum(dt.Rows[0][1].ToString())).ToString("f2");
                FailAmount = decimal.Parse(function.CheckNum(dt.Rows[0][2].ToString())).ToString("f2");
                WaitTaxAmount = decimal.Parse(function.CheckNum(dt.Rows[0][3].ToString())).ToString("f2");
                SuccessTaxAmount = decimal.Parse(function.CheckNum(dt.Rows[0][4].ToString())).ToString("f2");
                FailTaxAmount = decimal.Parse(function.CheckNum(dt.Rows[0][5].ToString())).ToString("f2");
            }
            other.Add("WaitAmount", WaitAmount);
            other.Add("SuccessAmount", SuccessAmount);
            other.Add("FailAmount", FailAmount);
            other.Add("WaitTaxAmount", WaitTaxAmount);
            other.Add("SuccessTaxAmount", SuccessTaxAmount);
            other.Add("FailTaxAmount", FailTaxAmount);
            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(UserCashRecord data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();

            Fields.Add("Remark", data.Remark); //备注

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

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

        #endregion

        #region 修改提现记录

        /// <summary>
        /// 增加或修改提现记录信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(UserCashRecord data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();

            Fields.Add("Remark", data.Remark); //备注

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

            return "success";
        }

        #endregion

        #region 删除提现记录信息

        /// <summary>
        /// 删除提现记录信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "UserCashRecord", "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("UserCashRecord", 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, "UserCashRecord", "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("UserCashRecord", 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, "UserCashRecord", "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("UserCashRecord", Fields, id);
            }
            db.SaveChanges();
            return "success";
        }

        #endregion


        #region 批量设置成功

        /// <summary>
        /// 批量设置成功
        /// </summary>
        /// <returns></returns>
        public string BatchSetting(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "UserCashRecord", "BatchSetting");
            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("UserCashRecord", Fields, id);
                var userCashRecord = db.UserCashRecord.FirstOrDefault(m => m.Id == id) ?? new UserCashRecord();
                if (userCashRecord.Id > 0)
                {
                    UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == Convert.ToInt32(userCashRecord.UserId));
                    if (account != null)
                    {
                        account.QueryCount = 1;
                        decimal TradeAmount = userCashRecord.TradeAmount;
                        decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                        decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                        decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                        account.WithdrawAmount += userCashRecord.TradeAmount;
                        account.FreezeAmount -= userCashRecord.TradeAmount;
                        decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                        decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                        decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
                        db.UserAccountRecord.Add(new UserAccountRecord()
                        {
                            CreateDate = DateTime.Now,
                            UpdateDate = DateTime.Now,
                            UserId = userCashRecord.UserId, //创客
                            ChangeType = 3, //变动类型
                            ProductType = 99, //产品类型
                            ChangeAmount = userCashRecord.ActualTradeAmount, //变更金额
                            BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                            AfterTotalAmount = AfterTotalAmount, //变更后总金额
                            BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                            AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                            BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                            AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                        });
                        db.UserAccountRecord.Add(new UserAccountRecord()
                        {
                            CreateDate = DateTime.Now,
                            UpdateDate = DateTime.Now,
                            UserId = userCashRecord.UserId, //创客
                            ChangeType = 4, //变动类型
                            ProductType = 99, //产品类型
                            ChangeAmount = userCashRecord.TradeFee, //变更金额
                            BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                            AfterTotalAmount = AfterTotalAmount, //变更后总金额
                            BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                            AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                            BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                            AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                        });
                        db.UserAccountRecord.Add(new UserAccountRecord()
                        {
                            CreateDate = DateTime.Now,
                            UpdateDate = DateTime.Now,
                            UserId = userCashRecord.UserId, //创客
                            ChangeType = 5, //变动类型
                            ProductType = 99, //产品类型
                            ChangeAmount = userCashRecord.ManageFee, //变更金额
                            BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                            AfterTotalAmount = AfterTotalAmount, //变更后总金额
                            BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                            AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                            BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                            AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                        });
                        db.SaveChanges();
                        RedisDbconn.Instance.Set("UserAccount:" + userCashRecord.UserId, account);
                    }
                }
            }
            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("UserCashRecord", Sort, Id);

            AddSysLog(Id.ToString(), "UserCashRecord", "sort");
            return "success";
        }
        #endregion

        #region 导入数据

        public IActionResult Import(string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;
            return View();
        }
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="ExcelData"></param>
        [HttpPost]
        public string ImportPost(string ExcelPath)
        {
            string key = function.MD5_16(Guid.NewGuid().ToString());
            RedisDbconn.Instance.AddList("ExcelImport10", ExcelPath + "#cut#UserCashRecord#cut#" + key + "#cut#" + SysUserName);
            return "success|" + key;
        }
        public string CheckImport(string key)
        {
            string result = RedisDbconn.Instance.Get<string>("CheckImport:" + key);
            if (!string.IsNullOrEmpty(result))
            {
                string[] datalist = result.Split('|');
                if (datalist[0] == "success")
                {
                    return result;
                }
                return datalist[0];
            }
            return "0";
        }
        #endregion

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(UserCashRecord data, string MakerCode, string RealName, string StatusSelect, string QueryCountSelect, string CreateDateData)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("CashOrderNo", "1"); //提现单号
            Fields.Add("TradeType", "0"); //交易类型

            string condition = " and Status>-1 and TradeType<3";
            //创客编号
            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(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }
            if (!string.IsNullOrEmpty(data.CashOrderNo))
            {
                condition += " and CashOrderNo='" + data.CashOrderNo + "'";
            }
            if (data.TradeType > 0)
            {
                condition += " and TradeType=" + data.TradeType;
            }
            //提交到代付状态
            if (!string.IsNullOrEmpty(QueryCountSelect))
            {
                if(QueryCountSelect == "0")
                {
                    condition += " and QueryCount=" + QueryCountSelect;
                }
                else
                {
                    condition += " and QueryCount>0";
                }
            }

            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.UserCashRecord.Any(m => m.CreateDate >= start && m.TradeType < 3);
                var checks = db.UserCashRecord.Any(m => m.CreateDate <= end && m.TradeType < 3);
                if (check)
                {
                    var sId = db.UserCashRecord.Where(m => m.CreateDate >= start && m.TradeType < 3).Min(m => m.Id);
                    condition += "  and Id >=" + sId;
                }
                if (checks)
                {
                    var eId = db.UserCashRecord.Where(m => m.CreateDate <= end && m.TradeType < 3).Max(m => m.Id);
                    condition += " and Id <=" + eId;
                }
            }
            else
            {
                var start = Convert.ToDateTime(DateTime.Now.AddMonths(-1).ToString("yyyy-MM") + "-01");
                var check = db.UserCashRecord.Any(m => m.CreateDate >= start && m.TradeType < 3);
                if (check)
                {
                    var minId = db.UserCashRecord.Where(m => m.CreateDate >= start && m.TradeType < 3).Min(m => m.Id);
                    var Info = function.ReadInstance("/WritePage/UserCashRecord/UserCashRecord.txt");
                    if (string.IsNullOrEmpty(Info.ToString()))
                    {
                        function.WritePage("/WritePage/UserCashRecord/", "UserCashRecord.txt", minId.ToString());
                        condition += " and Id >=" + minId;
                    }
                    else if (minId != int.Parse(Info))
                    {
                        function.WritePage("/WritePage/UserCashRecord/", "UserCashRecord.txt", minId.ToString());
                        condition += " and Id >=" + minId;
                    }
                    else
                    {
                        condition += " and Id >=" + Convert.ToInt32(Info);
                    }
                }
                else
                {
                    condition += " and Id =0";
                }
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("UserCashRecord", Fields, "Id desc", "0", 1, 20000, condition, "CashOrderNo,UserId,IdCardNo,ActualTradeAmount,Remark,Status,QueryCount,CreateDate,TradeType,SettleBankName,SettleBankCardNo", 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 user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["MakerCode"] = user.MakerCode;
                dic["RealName"] = user.RealName;
                dic["Mobile"] = user.Mobile;
                dic["TradeType"] = RelationClassForConst.GetTradeTypeInfo(int.Parse(dic["TradeType"].ToString()));
                dic.Remove("UserId");
                int Status = int.Parse(dic["Status"].ToString());
                if (Status == 0) dic["StatusName"] = "处理中";
                if (Status == 1) dic["StatusName"] = "成功";
                if (Status == 2) dic["StatusName"] = "失败";
                dic.Remove("Status");

                int QueryCount = int.Parse(dic["QueryCount"].ToString());
                if (QueryCount == 0) dic["LockName"] = "待提交";
                if (QueryCount > 0) dic["LockName"] = "已提交";
                dic.Remove("QueryCount");
            }

            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("CashOrderNo", "提现单号");
            ReturnFields.Add("MakerCode", "创客编号");
            ReturnFields.Add("RealName", "灵工姓名");
            ReturnFields.Add("Mobile", "手机号");
            ReturnFields.Add("IdCardNo", "身份证号");
            ReturnFields.Add("SettleBankName", "开户行名称");
            ReturnFields.Add("SettleBankCardNo", "开户行卡号");
            ReturnFields.Add("ActualTradeAmount", "发佣金额(单位：元）");
            ReturnFields.Add("LockName", "代付标记");
            ReturnFields.Add("StatusName", "状态");
            ReturnFields.Add("Remark", "备注");
            ReturnFields.Add("CreateDate", "创建时间");
            result.Add("Fields", ReturnFields);
            AddSysLog("0", "UserCashRecord", "ExportExcel");
            return Json(result);
        }

        #endregion



        #region 快捷导出Excel
        public IActionResult UserQuickExportExcel(string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            return View();
        }

        [HttpPost]
        public string UserQuickExportExcelDo(string TradeType, string CashOrderNo, string MakerCode, string RealName, string StatusSelect, string QueryCountSelect, string CreateDateData)
        {

            string condition = " where 1=1 and a.Status>-1 and a.TradeType<3";
            //创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                condition += " and a.UserId in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            //创客名称
            if (!string.IsNullOrEmpty(RealName))
            {
                condition += " and a.UserId in (select UserId from UserForRealName where RealName='" + RealName + "')";
            }
            //提现状态
            if (!string.IsNullOrEmpty(StatusSelect))
            {
                condition += " and a.Status=" + StatusSelect;
            }
            if (!string.IsNullOrEmpty(CashOrderNo))
            {
                condition += " and a.CashOrderNo='" + CashOrderNo + "'";
            }
            if (!string.IsNullOrEmpty(TradeType))
            {
                condition += " and a.TradeType=" + TradeType;
            }
            //提交到代付状态
            if (!string.IsNullOrEmpty(QueryCountSelect))
            {
                if (QueryCountSelect == "0")
                {
                    condition += " and a.QueryCount=" + QueryCountSelect;
                }
                else
                {
                    condition += " and a.QueryCount>0";
                }
            }

            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.UserCashRecord.Any(m => m.CreateDate >= start && m.TradeType < 3);
                var checks = db.UserCashRecord.Any(m => m.CreateDate <= end && m.TradeType < 3);
                if (check)
                {
                    var sId = db.UserCashRecord.Where(m => m.CreateDate >= start && m.TradeType < 3).Min(m => m.Id);
                    condition += "  and a.Id >=" + sId;
                }
                if (checks)
                {
                    var eId = db.UserCashRecord.Where(m => m.CreateDate <= end && m.TradeType < 3).Max(m => m.Id);
                    condition += " and a.Id <=" + eId;
                }
            }
            else
            {
                var start = Convert.ToDateTime(DateTime.Now.AddMonths(-1).ToString("yyyy-MM") + "-01");
                var check = db.UserCashRecord.Any(m => m.CreateDate >= start && m.TradeType < 3);
                if (check)
                {
                    var minId = db.UserCashRecord.Where(m => m.CreateDate >= start && m.TradeType < 3).Min(m => m.Id);
                    var Info = function.ReadInstance("/WritePage/UserCashRecord/UserCashRecord.txt");
                    if (string.IsNullOrEmpty(Info.ToString()))
                    {
                        function.WritePage("/WritePage/UserCashRecord/", "UserCashRecord.txt", minId.ToString());
                        condition += " and a.Id >=" + minId;
                    }
                    else if (minId != int.Parse(Info))
                    {
                        function.WritePage("/WritePage/UserCashRecord/", "UserCashRecord.txt", minId.ToString());
                        condition += " and a.Id >=" + minId;
                    }
                    else
                    {
                        condition += " and a.Id >=" + Convert.ToInt32(Info);
                    }
                }
                else
                {
                    condition += " and a.Id =0";
                }
            }
            var Sql = "SELECT a.CashOrderNo '提现单号',b.MakerCode '创客编号',b.RealName '创客姓名',b.Mobile '手机号',a.IdCardNo '身份证号',a.SettleBankName '开户行名称',a.SettleBankCardNo '开户行卡号',a.ActualTradeAmount '发佣金额(单位：元)',(CASE WHEN a.QueryCount=0 THEN '待提交' WHEN a.QueryCount>0 THEN '已提交' ELSE '' end) '代付标记',(CASE WHEN a.Status=0 THEN '处理中' WHEN a.Status=1 THEN '成功' WHEN a.Status=2 THEN '失败' ELSE '' end) '状态',a.Remark '备注',DATE_FORMAT(a.CreateDate,'%Y-%m-%d %H:%i:%s') '创建时间' FROM UserCashRecord a LEFT JOIN Users b ON a.UserId=b.Id" + condition + "";
            var sysAdmin = bsdb.SysAdmin.FirstOrDefault(m => m.AdminName == SysUserName && m.Status > -1);
            var FileName = "创客提现记录" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string SendData = "{\"Operater\":\"" + sysAdmin.Id + "\",\"SqlString\":\"" + Sql + "\",\"FileName\":\"" + FileName + "\",\"MaxCount\":\"0\"}";
            RedisDbconn.Instance.AddList("ExportQueue", SendData);
            return "success";
        }
        #endregion



        #region 盟主提现记录列表

        /// <summary>
        /// 根据条件查询盟主提现记录列表
        /// </summary>
        /// <returns></returns>
        public IActionResult LeaderIndex(UserCashRecord data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;


            string Condition = "";
            Condition += "CashOrderNo:\"" + data.CashOrderNo + "\",";
            Condition += "TradeType:\"" + data.TradeType + "\",";

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

        #endregion

        #region 根据条件查询盟主提现记录列表

        /// <summary>
        /// 盟主提现记录列表
        /// </summary>
        /// <returns></returns>
        public JsonResult LeaderIndexData(UserCashRecord data, string MakerCode, string RealName, string StatusSelect, string CreateDateData, int page = 1, int limit = 30)
        {

            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("CashOrderNo", "1"); //提现单号

            string condition = " and Status>-1 and TradeType=3";
            //创客编号
            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(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }
            if (!string.IsNullOrEmpty(data.CashOrderNo))
            {
                condition += " and CashOrderNo='" + data.CashOrderNo + "'";
            }
            if (data.TradeType > 0)
            {
                condition += " and TradeType=" + data.TradeType;
            }
            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                var start = datelist[0];
                var end = datelist[1];
                condition += " and CreateDate>='" + start + " 00:00:00' and CreateDate<='" + end + " 23:59:59'";
            }
            // 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.UserCashRecord.Any(m => m.CreateDate >= start && m.TradeType == 3);
            //     var checks = db.UserCashRecord.Any(m => m.CreateDate <= end && m.TradeType == 3);
            //     if (check)
            //     {
            //         var sId = db.UserCashRecord.Where(m => m.CreateDate >= start && m.TradeType == 3).Min(m => m.Id);
            //         condition += "  and Id >=" + sId;
            //     }
            //     if (checks)
            //     {
            //         var eId = db.UserCashRecord.Where(m => m.CreateDate <= end && m.TradeType == 3).Max(m => m.Id);
            //         condition += " and Id <=" + eId;
            //     }
            // }
            // else
            // {
            //     var start = Convert.ToDateTime(DateTime.Now.AddMonths(-1).ToString("yyyy-MM") + "-01");
            //     var check = db.UserCashRecord.Any(m => m.CreateDate >= start && m.TradeType == 3);
            //     if (check)
            //     {
            //         var minId = db.UserCashRecord.Where(m => m.CreateDate >= start && m.TradeType == 3).Min(m => m.Id);
            //         var Info = function.ReadInstance("/WritePage/UserCashRecord/LeaderUserCashRecord.txt");
            //         if (string.IsNullOrEmpty(Info.ToString()))
            //         {
            //             function.WritePage("/WritePage/UserCashRecord/", "LeaderUserCashRecord.txt", minId.ToString());
            //             condition += " and Id >=" + minId;
            //         }
            //         else if (minId != int.Parse(Info))
            //         {
            //             function.WritePage("/WritePage/UserCashRecord/", "LeaderUserCashRecord.txt", minId.ToString());
            //             condition += " and Id >=" + minId;
            //         }
            //         else
            //         {
            //             condition += " and Id >=" + Convert.ToInt32(Info);
            //         }
            //     }
            //     else
            //     {
            //         condition += " and Id =0";
            //     }
            // }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("UserCashRecord", 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 user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["MakerCode"] = user.MakerCode;
                dic["RealName"] = user.RealName;
                dic["TradeType"] = RelationClassForConst.GetTradeTypeInfo(int.Parse(dic["TradeType"].ToString()));
                int Status = int.Parse(dic["Status"].ToString());
                if (Status == 0) dic["StatusName"] = "处理中";
                if (Status == 1) dic["StatusName"] = "成功";
                if (Status == 2) dic["StatusName"] = "失败";

                int QueryCount = int.Parse(dic["QueryCount"].ToString());
                if (QueryCount == 0) dic["LockName"] = "待提交";
                if (QueryCount == 1) dic["LockName"] = "已提交";
            }
            Dictionary<string, object> other = new Dictionary<string, object>();

            string WaitAmount = "0.00";//待处理总金额
            string SuccessAmount = "0.00";//提现成功总金额
            string FailAmount = "0.00";//提现失败总金额
            DataTable dt = OtherMySqlConn.dtable("SELECT SUM(if(Status=0,TradeAmount,0)),SUM(if(Status=1,TradeAmount,0)),SUM(if(Status=2,TradeAmount,0)) FROM UserCashRecord where 1=1 " + condition);
            if (dt.Rows.Count > 0)
            {
                WaitAmount = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString())).ToString("f2");
                SuccessAmount = decimal.Parse(function.CheckNum(dt.Rows[0][1].ToString())).ToString("f2");
                FailAmount = decimal.Parse(function.CheckNum(dt.Rows[0][2].ToString())).ToString("f2");
            }
            other.Add("WaitAmount", WaitAmount);
            other.Add("SuccessAmount", SuccessAmount);
            other.Add("FailAmount", FailAmount);
            obj.Add("other", other);
            return Json(obj);
        }

        #endregion

        #region 导出盟主Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult LeaderExportExcel(UserCashRecord data, string MakerCode, string RealName, string StatusSelect, string CreateDateData)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("CashOrderNo", "1"); //提现单号

            string condition = " and Status>-1 and TradeType=3";
            //创客编号
            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(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }
            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                var start = datelist[0];
                var end = datelist[1];
                condition += " and CreateDate>='" + start + " 00:00:00' and CreateDate<='" + end + " 23:59:59'";
            }
            // 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.UserCashRecord.Any(m => m.CreateDate >= start && m.TradeType == 3);
            //     var checks = db.UserCashRecord.Any(m => m.CreateDate <= end && m.TradeType == 3);
            //     if (check)
            //     {
            //         var sId = db.UserCashRecord.Where(m => m.CreateDate >= start && m.TradeType == 3).Min(m => m.Id);
            //         condition += "  and Id >=" + sId;
            //     }
            //     if (checks)
            //     {
            //         var eId = db.UserCashRecord.Where(m => m.CreateDate <= end && m.TradeType == 3).Max(m => m.Id);
            //         condition += " and Id <=" + eId;
            //     }
            // }
            // else
            // {
            //     var start = Convert.ToDateTime(DateTime.Now.AddMonths(-1).ToString("yyyy-MM") + "-01");
            //     var check = db.UserCashRecord.Any(m => m.CreateDate >= start && m.TradeType == 3);
            //     if (check)
            //     {
            //         var minId = db.UserCashRecord.Where(m => m.CreateDate >= start && m.TradeType == 3).Min(m => m.Id);
            //         var Info = function.ReadInstance("/WritePage/UserCashRecord/LeaderUserCashRecord.txt");
            //         if (string.IsNullOrEmpty(Info.ToString()))
            //         {
            //             function.WritePage("/WritePage/UserCashRecord/", "LeaderUserCashRecord.txt", minId.ToString());
            //             condition += " and Id >=" + minId;
            //         }
            //         else if (minId != int.Parse(Info))
            //         {
            //             function.WritePage("/WritePage/UserCashRecord/", "LeaderUserCashRecord.txt", minId.ToString());
            //             condition += " and Id >=" + minId;
            //         }
            //         else
            //         {
            //             condition += " and Id >=" + Convert.ToInt32(Info);
            //         }
            //     }
            //     else
            //     {
            //         condition += " and Id =0";
            //     }
            // }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("UserCashRecord", Fields, "Id desc", "0", 1, 20000, condition, "CashOrderNo,UserId,IdCardNo,ActualTradeAmount,Remark,Status,QueryCount,CreateDate", 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 user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["MakerCode"] = user.MakerCode;
                dic["RealName"] = user.RealName;
                dic["Mobile"] = user.Mobile;
                dic["SettleBankName"] = user.SettleBankName;
                dic["SettleBankCardNo"] = user.SettleBankCardNo;
                dic.Remove("UserId");
                int Status = int.Parse(dic["Status"].ToString());
                if (Status == 0) dic["StatusName"] = "处理中";
                if (Status == 1) dic["StatusName"] = "成功";
                if (Status == 2) dic["StatusName"] = "失败";
                dic.Remove("Status");

                int QueryCount = int.Parse(dic["QueryCount"].ToString());
                if (QueryCount == 0) dic["LockName"] = "待提交";
                if (QueryCount == 1) dic["LockName"] = "已提交";
                dic.Remove("QueryCount");
            }

            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("CashOrderNo", "提现单号");
            ReturnFields.Add("MakerCode", "创客编号");
            ReturnFields.Add("RealName", "灵工姓名");
            ReturnFields.Add("Mobile", "手机号");
            ReturnFields.Add("IdCardNo", "身份证号");
            ReturnFields.Add("SettleBankName", "开户行名称");
            ReturnFields.Add("SettleBankCardNo", "开户行卡号");
            ReturnFields.Add("ActualTradeAmount", "发佣金额(单位：元）");
            ReturnFields.Add("LockName", "代付标记");
            ReturnFields.Add("StatusName", "状态");
            ReturnFields.Add("Remark", "备注");
            ReturnFields.Add("CreateDate", "创建时间");

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

        #endregion



        #region 快捷导出Excel
        public IActionResult LeaderQuickExportExcel(string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            return View();
        }

        [HttpPost]
        public string LeaderQuickExportExcelDo(string CashOrderNo, string MakerCode, string RealName, string StatusSelect, string CreateDateData)
        {

            string condition = " where 1=1 and a.Status>-1 and a.TradeType=3";
            //创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                condition += " and a.UserId in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            //创客名称
            if (!string.IsNullOrEmpty(RealName))
            {
                condition += " and a.UserId in (select UserId from UserForRealName where RealName='" + RealName + "')";
            }
            //提现状态
            if (!string.IsNullOrEmpty(StatusSelect))
            {
                condition += " and a.Status=" + StatusSelect;
            }
            if (!string.IsNullOrEmpty(CashOrderNo))
            {
                condition += " and a.CashOrderNo='" + CashOrderNo + "'";
            }
            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                var start = datelist[0];
                var end = datelist[1];
                condition += " and a.CreateDate>='" + start + " 00:00:00' and a.CreateDate<='" + end + " 23:59:59'";
            }
            // 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.UserCashRecord.Any(m => m.CreateDate >= start && m.TradeType < 3);
            //     var checks = db.UserCashRecord.Any(m => m.CreateDate <= end && m.TradeType < 3);
            //     if (check)
            //     {
            //         var sId = db.UserCashRecord.Where(m => m.CreateDate >= start && m.TradeType < 3).Min(m => m.Id);
            //         condition += "  and a.Id >=" + sId;
            //     }
            //     if (checks)
            //     {
            //         var eId = db.UserCashRecord.Where(m => m.CreateDate <= end && m.TradeType < 3).Max(m => m.Id);
            //         condition += " and a.Id <=" + eId;
            //     }
            // }
            // else
            // {
            //     var start = Convert.ToDateTime(DateTime.Now.AddMonths(-1).ToString("yyyy-MM") + "-01");
            //     var check = db.UserCashRecord.Any(m => m.CreateDate >= start && m.TradeType < 3);
            //     if (check)
            //     {
            //         var minId = db.UserCashRecord.Where(m => m.CreateDate >= start && m.TradeType < 3).Min(m => m.Id);
            //         var Info = function.ReadInstance("/WritePage/UserCashRecord/LeaderUserCashRecord.txt");
            //         if (string.IsNullOrEmpty(Info.ToString()))
            //         {
            //             function.WritePage("/WritePage/UserCashRecord/", "LeaderUserCashRecord.txt", minId.ToString());
            //             condition += " and Id >=" + minId;
            //         }
            //         else if (minId != int.Parse(Info))
            //         {
            //             function.WritePage("/WritePage/UserCashRecord/", "LeaderUserCashRecord.txt", minId.ToString());
            //             condition += " and Id >=" + minId;
            //         }
            //         else
            //         {
            //             condition += " and Id >=" + Convert.ToInt32(Info);
            //         }
            //     }
            //     else
            //     {
            //         condition += " and a.Id =0";
            //     }
            // }
            var Sql = "SELECT a.CashOrderNo '提现单号',b.MakerCode '创客编号',b.RealName '创客姓名',b.Mobile '手机号',a.IdCardNo '身份证号',a.SettleBankName '开户行名称',a.SettleBankCardNo '开户行卡号',a.ActualTradeAmount '发佣金额(单位：元)',(CASE WHEN a.QueryCount=0 THEN '待提交' WHEN a.QueryCount>0 THEN '已提交' ELSE '' end) '代付标记',(CASE WHEN a.Status=0 THEN '处理中' WHEN a.Status=1 THEN '成功' WHEN a.Status=2 THEN '失败' ELSE '' end) '状态',a.Remark '备注',DATE_FORMAT(a.CreateDate,'%Y-%m-%d %H:%i:%s') '创建时间' FROM UserCashRecord a LEFT JOIN Users b ON a.UserId=b.Id" + condition + "";
            var sysAdmin = bsdb.SysAdmin.FirstOrDefault(m => m.AdminName == SysUserName && m.Status > -1);
            var FileName = "盟主提现记录" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string SendData = "{\"Operater\":\"" + sysAdmin.Id + "\",\"SqlString\":\"" + Sql + "\",\"FileName\":\"" + FileName + "\",\"MaxCount\":\"0\"}";
            RedisDbconn.Instance.AddList("ExportQueue", SendData);
            return "success";
        }
        #endregion


        #region 助利宝提现记录列表

        /// <summary>
        /// 根据条件查询助利宝提现记录列表
        /// </summary>
        /// <returns></returns>
        public IActionResult HelpProfitIndex(UserCashRecord data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;


            string Condition = "";
            Condition += "CashOrderNo:\"" + data.CashOrderNo + "\",";
            Condition += "TradeType:\"" + data.TradeType + "\",";

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

        #endregion


        #region

        /// <summary>
        /// 助利宝提现记录列表
        /// </summary>
        /// <returns></returns>
        public JsonResult HelpProfitIndexData(UserCashRecord data, string MakerCode, string RealName, string StatusSelect, string QueryCountSelect, string CreateDateData, int page = 1, int limit = 30)
        {

            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("CashOrderNo", "1"); //提现单号

            string condition = " and Status>-1 and TradeType=4";
            //创客编号
            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(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }
            if (!string.IsNullOrEmpty(data.CashOrderNo))
            {
                condition += " and CashOrderNo='" + data.CashOrderNo + "'";
            }
            if (data.TradeType > 0)
            {
                condition += " and TradeType=" + data.TradeType;
            }
            //提交到代付状态
            if (!string.IsNullOrEmpty(QueryCountSelect))
            {
                condition += " and QueryCount=" + QueryCountSelect;
            }
            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and CreateDate>='" + start + " 00:00:00' and CreateDate<='" + end + " 23:59:59'";
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("UserCashRecord", 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 user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["MakerCode"] = user.MakerCode;
                dic["RealName"] = user.RealName;
                dic["TradeType"] = RelationClassForConst.GetTradeTypeInfo(int.Parse(dic["TradeType"].ToString()));
                int Status = int.Parse(dic["Status"].ToString());
                if (Status == 0) dic["StatusName"] = "处理中";
                if (Status == 1) dic["StatusName"] = "成功";
                if (Status == 2) dic["StatusName"] = "失败";

                int QueryCount = int.Parse(dic["QueryCount"].ToString());
                if (QueryCount == 0) dic["LockName"] = "待提交";
                if (QueryCount == 1) dic["LockName"] = "已提交";
            }
            Dictionary<string, object> other = new Dictionary<string, object>();

            string WaitAmount = "0.00";//待处理总金额
            string SuccessAmount = "0.00";//提现成功总金额
            string FailAmount = "0.00";//提现失败总金额
            DataTable dt = OtherMySqlConn.dtable("SELECT SUM(if(Status=0,TradeAmount,0)),SUM(if(Status=1,TradeAmount,0)),SUM(if(Status=2,TradeAmount,0)) FROM UserCashRecord where 1=1 " + condition);
            if (dt.Rows.Count > 0)
            {
                WaitAmount = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString())).ToString("f2");
                SuccessAmount = decimal.Parse(function.CheckNum(dt.Rows[0][1].ToString())).ToString("f2");
                FailAmount = decimal.Parse(function.CheckNum(dt.Rows[0][2].ToString())).ToString("f2");
            }
            other.Add("WaitAmount", WaitAmount);
            other.Add("SuccessAmount", SuccessAmount);
            other.Add("FailAmount", FailAmount);
            obj.Add("other", other);
            return Json(obj);
        }

        #endregion

        #region 导出助利宝Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult HelpProfitExportExcel(UserCashRecord data, string MakerCode, string RealName, string StatusSelect, string PayStatus)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("CashOrderNo", "1"); //提现单号
            Fields.Add("CreateDate", "3"); //创建时间

            string condition = " and Status>-1 and TradeType=4";
            //创客编号
            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(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }
            //提交到代付状态
            if (!string.IsNullOrEmpty(PayStatus))
            {
                int QueryCount = int.Parse(function.CheckInt(PayStatus));
                if (QueryCount == 2)
                {
                    QueryCount = 0;
                }
                condition += " and QueryCount=" + QueryCount;
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("UserCashRecord", Fields, "Id desc", "0", 1, 20000, condition, "CashOrderNo,UserId,IdCardNo,ActualTradeAmount,Remark,Status,QueryCount,CreateDate", 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 user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["MakerCode"] = user.MakerCode;
                dic["RealName"] = user.RealName;
                dic["Mobile"] = user.Mobile;
                dic["SettleBankName"] = user.SettleBankName;
                dic["SettleBankCardNo"] = user.SettleBankCardNo;
                dic.Remove("UserId");
                int Status = int.Parse(dic["Status"].ToString());
                if (Status == 0) dic["StatusName"] = "处理中";
                if (Status == 1) dic["StatusName"] = "成功";
                if (Status == 2) dic["StatusName"] = "失败";
                dic.Remove("Status");

                int QueryCount = int.Parse(dic["QueryCount"].ToString());
                if (QueryCount == 0) dic["LockName"] = "待提交";
                if (QueryCount == 1) dic["LockName"] = "已提交";
                dic.Remove("QueryCount");
            }

            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("CashOrderNo", "提现单号");
            ReturnFields.Add("MakerCode", "创客编号");
            ReturnFields.Add("RealName", "灵工姓名");
            ReturnFields.Add("Mobile", "手机号");
            ReturnFields.Add("IdCardNo", "身份证号");
            ReturnFields.Add("SettleBankName", "开户行名称");
            ReturnFields.Add("SettleBankCardNo", "开户行卡号");
            ReturnFields.Add("ActualTradeAmount", "发佣金额(单位：元）");
            ReturnFields.Add("LockName", "代付标记");
            ReturnFields.Add("StatusName", "状态");
            ReturnFields.Add("Remark", "备注");
            ReturnFields.Add("CreateDate", "创建时间");

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

        #endregion



        #region 提交代付平台

        public IActionResult Cash(string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;
            return View();
        }

        /// <summary>
        /// 提交代付平台
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Cash(string Id, int Channel = 1)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "UserCashRecord", "cash");
            db.SaveChanges();
            CustomTagSet set = db.CustomTagSet.FirstOrDefault(m => m.Tags == "CashWithoutUser") ?? new CustomTagSet();
            string IdString = "," + set.Contents + ",";
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                UserCashRecord edit = db.UserCashRecord.FirstOrDefault(m => m.Id == id && m.QueryCount == 0);
                if (edit != null)
                {
                    Users user = db.Users.FirstOrDefault(m => m.Id == edit.UserId) ?? new Users();
                    if (!IdString.Contains("," + user.Id + ","))
                    {
                        edit.QueryCount = Channel;
                        edit.UpdateDate = DateTime.Now;
                        db.SaveChanges();
                        if(Channel == 1)
                        {
                            RedisDbconn.Instance.AddList("CashPayApplyQueue", Newtonsoft.Json.JsonConvert.SerializeObject(edit));
                        }
                        else if(Channel == 2)
                        {
                            RedisDbconn.Instance.AddList("JkCashPayApplyQueue", Newtonsoft.Json.JsonConvert.SerializeObject(edit));
                        }
                        else if(Channel == 3 || Channel == 4)
                        {
                            RedisDbconn.Instance.AddList("HyfCashPayApplyQueue", Newtonsoft.Json.JsonConvert.SerializeObject(edit) + "#cut#" + Channel);
                        }
                    }
                }
            }
            return "success";
        }

        #endregion

        #region 拒绝

        /// <summary>
        /// 拒绝
        /// </summary>
        /// <returns></returns>
        public IActionResult Reduce(string right, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            UserCashRecord editData = db.UserCashRecord.FirstOrDefault(m => m.Id == Id) ?? new UserCashRecord();
            ViewBag.data = editData;

            return View();
        }

        #endregion

        #region 拒绝

        /// <summary>
        /// 拒绝
        /// </summary>
        /// <returns></returns>
        public string ReduceDo(int Id, string Remark)
        {
            AddSysLog(Id, "UserCashRecord", "Reduce");
            UserCashRecord edit = db.UserCashRecord.FirstOrDefault(m => m.Id == Id);
            if (edit != null)
            {
                if (edit.TradeType == 3)
                {
                    edit.Status = 2;
                    edit.Remark = Remark;
                    edit.UpdateMan = SysUserName;
                    UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == edit.UserId);
                    if (account != null)
                    {
                        decimal TradeAmount = edit.TradeAmount;
                        account.LeaderBalanceAmount += TradeAmount;
                        db.LeaderAccountRecord.Add(new LeaderAccountRecord()
                        {
                            CreateDate = DateTime.Now,
                            UserId = edit.UserId, //创客
                            ChangeType = 6, //变动类型
                            ProductType = 99, //产品类型
                            ChangeAmount = TradeAmount, //变更金额
                            BeforeBalanceAmount = account.LeaderBalanceAmount - TradeAmount, //变更前余额
                            AfterBalanceAmount = account.LeaderBalanceAmount, //变更后余额
                        });
                        db.SaveChanges();
                        RedisDbconn.Instance.Set("UserAccount:" + edit.UserId, account);
                    }
                }
                else if (edit.TradeType == 4)
                {
                    edit.Status = 2;
                    edit.Remark = Remark;
                    edit.UpdateMan = SysUserName;
                    UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == edit.UserId);
                    if (account != null)
                    {
                        decimal TradeAmount = edit.TradeAmount;
                        account.HelpProfitBalanceAmount += TradeAmount;
                        db.HelpProfitAccountRecord.Add(new HelpProfitAccountRecord()
                        {
                            CreateDate = DateTime.Now,
                            UserId = edit.UserId, //创客
                            ChangeType = 6, //变动类型
                            ProductType = 99, //产品类型
                            ChangeAmount = TradeAmount, //变更金额
                            BeforeBalanceAmount = account.HelpProfitBalanceAmount - TradeAmount, //变更前余额
                            AfterBalanceAmount = account.HelpProfitBalanceAmount, //变更后余额
                        });
                        db.SaveChanges();
                        RedisDbconn.Instance.Set("UserAccount:" + edit.UserId, account);
                    }
                }
                else
                {
                    edit.Status = 2;
                    edit.Remark = Remark;
                    edit.UpdateMan = SysUserName;
                    UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == edit.UserId);
                    if (account != null)
                    {
                        decimal TradeAmount = edit.TradeAmount;
                        decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                        decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                        decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                        account.BalanceAmount += TradeAmount;
                        if (account.FreezeAmount >= TradeAmount)
                        {
                            account.FreezeAmount -= TradeAmount;
                        }
                        else
                        {
                            return "冻结金额不足";
                        }
                        decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                        decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                        decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
                        db.UserAccountRecord.Add(new UserAccountRecord()
                        {
                            CreateDate = DateTime.Now,
                            UpdateDate = DateTime.Now,
                            UserId = edit.UserId, //创客
                            ChangeType = 6, //变动类型
                            ProductType = 99, //产品类型
                            ChangeAmount = TradeAmount, //变更金额
                            BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                            AfterTotalAmount = AfterTotalAmount, //变更后总金额
                            BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                            AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                            BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                            AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                        });
                        db.SaveChanges();
                        RedisDbconn.Instance.Set("UserAccount:" + edit.UserId, account);
                    }
                }

                db.SaveChanges();
            }
            return "success";
        }

        #endregion

        #region 解除

        /// <summary>
        /// 解除
        /// </summary>
        /// <returns></returns>
        public string Cancel(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "WithdrawRecord", "Cancel");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                UserCashRecord edit = db.UserCashRecord.FirstOrDefault(m => m.Id == id);
                if (edit != null)
                {
                    edit.QueryCount = 0;
                    db.SaveChanges();
                }
            }

            return "success";
        }

        #endregion



        #region 退汇

        /// <summary>
        /// 退汇
        /// </summary>
        /// <returns></returns>
        public string Refund(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "退汇", "Refund");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                var userCashRecord = db.UserCashRecord.FirstOrDefault(m => m.Id == id) ?? new UserCashRecord();
                DataTable dt = OtherMySqlConn.dtable("DELETE FROM UserAccountRecord WHERE Version=" + userCashRecord.Id + "");
                userCashRecord.Status = 0;
                userCashRecord.QueryCount = 0;
                var userAccount = db.UserAccount.FirstOrDefault(m => m.Id == userCashRecord.UserId) ?? new UserAccount();
                userAccount.WithdrawAmount -= userCashRecord.TradeAmount;
                userAccount.FreezeAmount += userCashRecord.TradeAmount;
                db.SaveChanges();
            }

            return "success";
        }

        #endregion

    }
}