/*
 * 商户退押金申请记录
 */

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


            return View();
        }

        #endregion

        #region 根据条件查询首台商户退押金申请记录列表

        /// <summary>
        /// 首台商户退押金申请记录列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(MerchantDepositReturns data, string CreateDateData, string UpdateDateData, string MerchantName, string PosSn, string PayKindSelect, string BankNameSelect, string BrandId, string StatusSelect = "0", int page = 1, int limit = 30)
        {

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

            Fields.Add("AlipayAccountNo", "1"); //支付宝账号
            Fields.Add("BankCardNo", "1"); //银行卡号
            Fields.Add("SeoKeyword", "1"); //退押订单号

            string condition = " and Status>-1 and QueryCount=1";

            //提现状态
            if (!string.IsNullOrEmpty(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }
            //退款类型
            if (!string.IsNullOrEmpty(PayKindSelect))
            {
                condition += " and PayKind=" + PayKindSelect;
            }
            //开户行
            if (!string.IsNullOrEmpty(BankNameSelect))
            {
                condition += " and BankName='" + BankNameSelect + "'";
            }
            //品牌
            if (!string.IsNullOrEmpty(BrandId))
            {
                int brandId = int.Parse(BrandId);
                var merchantIds = "";
                var posMerchantInfo = db.PosMerchantInfo.Where(m => m.Status > -1 && m.BrandId == brandId && m.StandardMonths == 10).ToList();
                foreach (var item in posMerchantInfo)
                {
                    merchantIds += item.Id + ",";
                }
                merchantIds = merchantIds.TrimEnd(',');
                condition += " and MerchantId In(" + merchantIds + ")";
            }
            //创建时间
            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'";
            }
            //发放时间
            if (!string.IsNullOrEmpty(UpdateDateData))
            {
                string[] datelist = UpdateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and UpdateDate>='" + start + " 00:00:00' and UpdateDate<='" + end + " 23:59:59'";
            }
            if (!string.IsNullOrEmpty(MerchantName))
            {
                var Ids = "";
                var posMerchantInfo = db.PosMerchantInfo.Where(m => m.MerRealName == MerchantName).ToList();
                foreach (var item in posMerchantInfo)
                {
                    Ids += item.Id + ",";
                }
                Ids = Ids.TrimEnd(',');
                condition += " and MerchantId in(" + Ids + ")";
            }
            if (!string.IsNullOrEmpty(PosSn))
            {
                var Ids = "";
                var posMerchantInfo = db.PosMerchantInfo.Where(m => m.KqSnNo == PosSn).ToList();
                foreach (var item in posMerchantInfo)
                {
                    Ids += item.Id + ",";
                }
                Ids = Ids.TrimEnd(',');
                condition += " and MerchantId in(" + Ids + ")";
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("MerchantDepositReturns", 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 MerchantId = int.Parse(function.CheckInt(dic["MerchantId"].ToString()));
                PosMerchantInfo merchantid_PosMerchantInfo = db.PosMerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new PosMerchantInfo();
                dic["MerchantIdMerRealName"] = merchantid_PosMerchantInfo.MerRealName;
                dic["MerchantIdMerchantMobile"] = merchantid_PosMerchantInfo.MerchantMobile;
                dic["MerchantIdMerIdcardNo"] = merchantid_PosMerchantInfo.MerIdcardNo;
                dic["MerchantIdKqSnNo"] = merchantid_PosMerchantInfo.KqSnNo;
                dic.Remove("MerchantId");
                int Status = int.Parse(dic["Status"].ToString());
                if (Status == 0) dic["StatusName"] = "待处理";
                if (Status == 1) dic["StatusName"] = "成功";
                if (Status == 2) dic["StatusName"] = "失败";
                // if (Status == 4) dic["StatusName"] = "通过";
                // if (Status == 5) dic["StatusName"] = "未通过";
                dic["BrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(merchantid_PosMerchantInfo.BrandId.ToString()));
                //创客
                int UserId = int.Parse(function.CheckInt(dic["UserId"].ToString()));
                Users userid_Users = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["UserIdRealName"] = userid_Users.RealName;
                dic["UserIdMakerCode"] = userid_Users.MakerCode;
                dic.Remove("UserId");

                int PayKind = int.Parse(dic["PayKind"].ToString());
                if (PayKind == 0) dic["PayKindName"] = "支付宝";
                if (PayKind == 1) dic["PayKindName"] = "银行卡";

                //实际返还金额
                decimal amt = decimal.Parse(dic["ReturnAmount"].ToString());
                dic["ReturnAmounts"] = (amt * 0.92M).ToString("f2");
            }
            Dictionary<string, object> other = new Dictionary<string, object>();
            decimal ReturnAmount = 0.00M;
            decimal fReturnAmount = 0.00M;
            DataTable dt = OtherMySqlConn.dtable("SELECT SUM(ReturnAmount),SUM(ReturnAmount*0.92) FROM MerchantDepositReturns WHERE 1=1" + condition);
            if (dt.Rows.Count > 0)
            {
                ReturnAmount = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString()));
                fReturnAmount = decimal.Parse(function.CheckNum(dt.Rows[0][1].ToString()));
            }
            other.Add("ReturnAmount", ReturnAmount.ToString("f2"));
            other.Add("fReturnAmount", fReturnAmount.ToString("f2"));
            obj.Add("other", other);
            return Json(obj);
        }

        #endregion


        #region 非首台商户退押金申请记录列表

        /// <summary>
        /// 根据条件查询非首台商户退押金申请记录列表
        /// </summary>
        /// <returns></returns>
        public IActionResult Indexs(MerchantDepositReturns data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;


            return View();
        }

        #endregion

        #region 根据条件查询非首台商户退押金申请记录列表

        /// <summary>
        /// 非首台商户退押金申请记录列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexsData(MerchantDepositReturns data, string CreateDateData, string UpdateDateData, string MerchantName, string PosSn, string PayKindSelect, string BankNameSelect, string BrandId, string StatusSelect = "0", int page = 1, int limit = 30)
        {

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

            Fields.Add("AlipayAccountNo", "1"); //支付宝账号
            Fields.Add("BankCardNo", "1"); //银行卡号
            Fields.Add("SeoKeyword", "1"); //退押订单号

            string condition = " and Status>-1 and QueryCount=0";

            //提现状态
            if (!string.IsNullOrEmpty(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }
            //退款类型
            if (!string.IsNullOrEmpty(PayKindSelect))
            {
                condition += " and PayKind=" + PayKindSelect;
            }
            //开户行
            if (!string.IsNullOrEmpty(BankNameSelect))
            {
                condition += " and BankName='" + BankNameSelect + "'";
            }
            //品牌
            if (!string.IsNullOrEmpty(BrandId))
            {
                int brandId = int.Parse(BrandId);
                var merchantIds = "";
                var posMerchantInfo = db.PosMerchantInfo.Where(m => m.Status > -1 && m.BrandId == brandId && m.StandardMonths == 10).ToList();
                foreach (var item in posMerchantInfo)
                {
                    merchantIds += item.Id + ",";
                }
                merchantIds = merchantIds.TrimEnd(',');
                condition += " and MerchantId In(" + merchantIds + ")";
            }
            //创建时间
            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'";
            }
            //发放时间
            if (!string.IsNullOrEmpty(UpdateDateData))
            {
                string[] datelist = UpdateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and UpdateDate>='" + start + " 00:00:00' and UpdateDate<='" + end + " 23:59:59'";
            }
            if (!string.IsNullOrEmpty(MerchantName))
            {
                var Ids = "";
                var posMerchantInfo = db.PosMerchantInfo.Where(m => m.MerRealName == MerchantName).ToList();
                foreach (var item in posMerchantInfo)
                {
                    Ids += item.Id + ",";
                }
                Ids = Ids.TrimEnd(',');
                condition += " and MerchantId in(" + Ids + ")";
            }
            if (!string.IsNullOrEmpty(PosSn))
            {
                var Ids = "";
                var posMerchantInfo = db.PosMerchantInfo.Where(m => m.KqSnNo == PosSn).ToList();
                foreach (var item in posMerchantInfo)
                {
                    Ids += item.Id + ",";
                }
                Ids = Ids.TrimEnd(',');
                condition += " and MerchantId in(" + Ids + ")";
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("MerchantDepositReturns", 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 MerchantId = int.Parse(function.CheckInt(dic["MerchantId"].ToString()));
                PosMerchantInfo merchantid_PosMerchantInfo = db.PosMerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new PosMerchantInfo();
                dic["MerchantIdMerRealName"] = merchantid_PosMerchantInfo.MerRealName;
                dic["MerchantIdMerchantMobile"] = merchantid_PosMerchantInfo.MerchantMobile;
                dic["MerchantIdMerIdcardNo"] = merchantid_PosMerchantInfo.MerIdcardNo;
                dic["MerchantIdKqSnNo"] = merchantid_PosMerchantInfo.KqSnNo;
                dic.Remove("MerchantId");
                int Status = int.Parse(dic["Status"].ToString());
                if (Status == 0) dic["StatusName"] = "待处理";
                if (Status == 1) dic["StatusName"] = "成功";
                if (Status == 2) dic["StatusName"] = "失败";
                if (Status == 4) dic["StatusName"] = "通过";
                if (Status == 5) dic["StatusName"] = "未通过";
                dic["BrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(merchantid_PosMerchantInfo.BrandId.ToString()));
                //创客
                int UserId = int.Parse(function.CheckInt(dic["UserId"].ToString()));
                Users userid_Users = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["UserIdRealName"] = userid_Users.RealName;
                dic["UserIdMakerCode"] = userid_Users.MakerCode;
                dic.Remove("UserId");

                int PayKind = int.Parse(dic["PayKind"].ToString());
                if (PayKind == 0) dic["PayKindName"] = "支付宝";
                if (PayKind == 1) dic["PayKindName"] = "银行卡";

                //实际返还金额
                decimal amt = decimal.Parse(dic["ReturnAmount"].ToString());
                dic["ReturnAmounts"] = (amt * 0.92M).ToString("f2");
            }
            Dictionary<string, object> other = new Dictionary<string, object>();
            decimal ReturnAmount = 0.00M;
            decimal fReturnAmount = 0.00M;
            DataTable dt = OtherMySqlConn.dtable("SELECT SUM(ReturnAmount),SUM(ReturnAmount*0.92) FROM MerchantDepositReturns WHERE 1=1" + condition);
            if (dt.Rows.Count > 0)
            {
                ReturnAmount = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString()));
                fReturnAmount = decimal.Parse(function.CheckNum(dt.Rows[0][1].ToString()));
            }
            other.Add("ReturnAmount", ReturnAmount.ToString("f2"));
            other.Add("fReturnAmount", fReturnAmount.ToString("f2"));
            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(MerchantDepositReturns 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("MerchantDepositReturns", Fields, 0);
            AddSysLog(data.Id.ToString(), "MerchantDepositReturns", "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;


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

        #endregion

        #region 修改商户退押金申请记录

        /// <summary>
        /// 增加或修改商户退押金申请记录信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(MerchantDepositReturns 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("MerchantDepositReturns", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "MerchantDepositReturns", "update");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 删除商户退押金申请记录信息

        /// <summary>
        /// 删除商户退押金申请记录信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "MerchantDepositReturns", "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("MerchantDepositReturns", 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, "MerchantDepositReturns", "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("MerchantDepositReturns", 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, "MerchantDepositReturns", "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("MerchantDepositReturns", 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("MerchantDepositReturns", Sort, Id);

            AddSysLog(Id.ToString(), "MerchantDepositReturns", "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);
            string error = "";
            for (int i = 1; i < list.Count; i++)
            {
                JsonData dr = list[i];
                string itemJson = dr.ToJson();
                string PosSn = itemJson.Contains("\"A\"") ? dr["A"].ToString().Replace("机具SN：","") : "";// 退押机具Sn
                string Statuss = itemJson.Contains("\"B\"") ? dr["B"].ToString() : ""; // 结果
                string SeoDescription = itemJson.Contains("\"C\"") ? dr["C"].ToString() : "";// 备注
                // int Status = int.Parse(Statuss);
                int Status = 0;
                if (Statuss == "SUCCESS")//成功
                {
                    Status = 1;
                }
                if (Statuss == "FAIL")//失败
                {
                    Status = 2;
                }
                var pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == PosSn) ?? new PosMachinesTwo();
                var merchantDepositReturns = db.MerchantDepositReturns.FirstOrDefault(m => m.MerchantId == pos.BindMerchantId && m.Status == 0) ?? new MerchantDepositReturns();
                if (merchantDepositReturns.Id == 0)
                {
                    error += "以下操作失败,机具" + PosSn + ',' + "对应的退押订单" + merchantDepositReturns.SeoKeyword + "该订单未找到或不符合规则" + '\n';
                }
                //失败
                if (Status == 2)
                {
                    var posm = db.PosMerchantInfo.FirstOrDefault(m => m.Id == merchantDepositReturns.MerchantId) ?? new PosMerchantInfo();
                    posm.StandardStatus = 101;
                }
                merchantDepositReturns.Status = Status;
                merchantDepositReturns.UpdateDate = DateTime.Now;
                merchantDepositReturns.SeoDescription = SeoDescription;
                merchantDepositReturns.SeoTitle = SysUserName + "-" + SysRealName;
            }
            if (!string.IsNullOrEmpty(error))
            {
                return "Warning|" + error;
            }
            db.SaveChanges();
            return "success";
        }
        #endregion

        #region 非首台导入数据
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="ExcelData"></param>
        public string Imports(string ExcelData)
        {
            ExcelData = HttpUtility.UrlDecode(ExcelData);
            JsonData list = JsonMapper.ToObject(ExcelData);
            string error = "";
            for (int i = 1; i < list.Count; i++)
            {
                JsonData dr = list[i];
                string itemJson = dr.ToJson();
                string PosSn = itemJson.Contains("\"A\"") ? dr["A"].ToString().Replace("机具SN：","") : "";// 退押机具Sn
                string Statuss = itemJson.Contains("\"B\"") ? dr["B"].ToString() : ""; // 结果
                string SeoDescription = itemJson.Contains("\"C\"") ? dr["C"].ToString() : "";// 备注
                // int Status = int.Parse(Statuss);
                int Status = 0;
                if (Statuss == "SUCCESS")//成功
                {
                    Status = 1;
                }
                if (Statuss == "FAIL")//失败
                {
                    Status = 2;
                }
                var pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == PosSn) ?? new PosMachinesTwo();
                var merchantDepositReturns = db.MerchantDepositReturns.FirstOrDefault(m => m.MerchantId == pos.BindMerchantId && m.Status == 0) ?? new MerchantDepositReturns();
                if (merchantDepositReturns.Id == 0)
                {
                    error += "以下操作失败,机具" + PosSn + ',' + "对应的退押订单" + merchantDepositReturns.SeoKeyword + "该订单未找到或不符合规则" + '\n';
                }
                //失败
                if (Status == 2)
                {
                    var posm = db.PosMerchantInfo.FirstOrDefault(m => m.Id == merchantDepositReturns.MerchantId) ?? new PosMerchantInfo();
                    posm.StandardStatus = 101;
                }
                merchantDepositReturns.Status = Status;
                merchantDepositReturns.UpdateDate = DateTime.Now;
                merchantDepositReturns.SeoDescription = SeoDescription;
                merchantDepositReturns.SeoTitle = SysUserName + "-" + SysRealName;
            }
            if (!string.IsNullOrEmpty(error))
            {
                return "Warning|" + error;
            }
            db.SaveChanges();
            return "success";
        }
        #endregion


        #region 提交代付平台

        /// <summary>
        /// 提交代付平台
        /// </summary>
        /// <returns></returns>
        public string Cash(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            var Ids = "";
            AddSysLog(Id, "UserCashRecord", "cash");
            db.SaveChanges();
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                var merchantDepositReturns = db.MerchantDepositReturns.FirstOrDefault(m => m.Id == id && m.Status == 4) ?? new MerchantDepositReturns();
                if (merchantDepositReturns.Id > 0)
                {
                    Ids += subid + ",";
                }
            }
            DataTable dt = OtherMySqlConn.dtable("UPDATE MerchantDepositReturns SET `Status`=3  WHERE Id IN(" + Ids.TrimEnd(',') + ")");
            string text = string.Format("商户押金退还，记录Id: '" + Ids.TrimEnd(',') + "'，操作人: '" + SysUserName + "_" + SysRealName + "'，Time'" + DateTime.Now + "'");
            function.WriteLog(text, "商户押金退还");
            RedisDbconn.Instance.AddList("ToAlipayAccountQueue", Ids.TrimEnd(','));
            return "success";
        }

        #endregion

        #region 首台导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(MerchantDepositReturns data, string CreateDateData, string UpdateDateData, string MerchantName, string PosSn, string PayKindSelect, string BankNameSelect, string StatusSelect, string BrandId)
        {

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

            Fields.Add("AlipayAccountNo", "1"); //支付宝账号
            Fields.Add("BankCardNo", "1"); //银行卡号
            Fields.Add("SeoKeyword", "1"); //退押订单号

            string condition = " and Status>-1 and QueryCount=1";

            //提现状态
            if (!string.IsNullOrEmpty(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }
            //退款类型
            if (!string.IsNullOrEmpty(PayKindSelect))
            {
                condition += " and PayKind=" + PayKindSelect;
            }
            //开户行
            if (!string.IsNullOrEmpty(BankNameSelect))
            {
                condition += " and BankName=" + BankNameSelect;
            }
            //品牌
            if (!string.IsNullOrEmpty(BrandId))
            {
                int brandId = int.Parse(BrandId);
                var merchantIds = "";
                var posMerchantInfo = db.PosMerchantInfo.Where(m => m.Status > -1 && m.BrandId == brandId && m.StandardMonths == 10).ToList();
                foreach (var item in posMerchantInfo)
                {
                    merchantIds += item.Id + ",";
                }
                merchantIds = merchantIds.TrimEnd(',');
                condition += " and MerchantId In(" + merchantIds + ")";
            }
            //创建时间
            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'";
            }
            //发放时间
            if (!string.IsNullOrEmpty(UpdateDateData))
            {
                string[] datelist = UpdateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and UpdateDate>='" + start + " 00:00:00' and UpdateDate<='" + end + " 23:59:59'";
            }
            if (!string.IsNullOrEmpty(MerchantName))
            {
                var Ids = "";
                var posMerchantInfo = db.PosMerchantInfo.Where(m => m.MerRealName == MerchantName).ToList();
                foreach (var item in posMerchantInfo)
                {
                    Ids += item.Id + ",";
                }
                Ids = Ids.TrimEnd(',');
                condition += " and MerchantId in(" + Ids + ")";
            }
            if (!string.IsNullOrEmpty(PosSn))
            {
                var Ids = "";
                var posMerchantInfo = db.PosMerchantInfo.Where(m => m.KqSnNo == PosSn).ToList();
                foreach (var item in posMerchantInfo)
                {
                    Ids += item.Id + ",";
                }
                Ids = Ids.TrimEnd(',');
                condition += " and MerchantId in(" + Ids + ")";
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("MerchantDepositReturns", Fields, "Id desc", "0", 1, 20000, condition, "Id,MerchantId,SeoKeyword,CreateDate,SeoDescription,AlipayAccountNo,BankCardNo,BankName", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                int Id = int.Parse(function.CheckInt(dic["Id"].ToString()));
                var merchantDepositReturn = db.MerchantDepositReturns.FirstOrDefault(m => m.Id == Id) ?? new MerchantDepositReturns();
                //商户
                int MerchantId = int.Parse(function.CheckInt(dic["MerchantId"].ToString()));
                // var merchantDepositReturns = db.MerchantDepositReturns.FirstOrDefault(m => m.MerchantId == MerchantId) ?? new MerchantDepositReturns();
                // PosMerchantInfo merchantid_PosMerchantInfo = db.PosMerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new PosMerchantInfo();
                PosMerchantInfo merchantid_PosMerchantInfo = db.PosMerchantInfo.FirstOrDefault(m => m.Id == merchantDepositReturn.MerchantId) ?? new PosMerchantInfo();
                dic["MerchantIdMerRealName"] = merchantid_PosMerchantInfo.MerRealName;
                // dic["MerchantIdMerchantMobile"] = merchantid_PosMerchantInfo.MerchantMobile;
                // dic["MerchantIdMerIdcardNo"] = merchantid_PosMerchantInfo.MerIdcardNo;
                dic.Remove("MerchantId");
                dic["PosSn"] = merchantid_PosMerchantInfo.KqSnNo;
                dic["BrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(merchantid_PosMerchantInfo.BrandId.ToString()));
                // 实际返还金额
                // decimal amt = decimal.Parse(merchantDepositReturns.ReturnAmount.ToString());
                decimal amt = decimal.Parse(merchantDepositReturn.ReturnAmount.ToString());
                dic["Amount"] = amt.ToString("f2");
                dic["ReturnAmount"] = (amt * 0.92M).ToString("f2");

                if (!string.IsNullOrEmpty(merchantDepositReturn.AlipayAccountNo))
                {
                    dic["AccountNo"] = merchantDepositReturn.AlipayAccountNo;
                }
                if (!string.IsNullOrEmpty(merchantDepositReturn.BankCardNo))
                {
                    dic["AccountNo"] = merchantDepositReturn.BankCardNo;
                }


                int PayKind = merchantDepositReturn.PayKind;
                if (PayKind == 0) dic["PayKindName"] = "支付宝";
                if (PayKind == 1) dic["PayKindName"] = "银行卡";
                dic.Remove("Id");
                dic.Remove("AlipayAccountNo");
                dic.Remove("BankCardNo");
            }

            Dictionary<string, object> result = new Dictionary<string, object>();
            // result.Add("Status", "0");
            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("Id", "记录ID");
            ReturnFields.Add("CreateDate", "申请提现时间");
            ReturnFields.Add("MerchantIdMerRealName", "商户真实姓名");
            ReturnFields.Add("BrandId", "机具品牌");
            ReturnFields.Add("PosSn", "机具Sn");
            // ReturnFields.Add("MerchantIdMerchantMobile", "商户手机号");
            // ReturnFields.Add("MerchantIdMerIdcardNo", "商户身份证号");
            ReturnFields.Add("SeoKeyword", "退押订单号");
            ReturnFields.Add("AccountNo", "收款账号");
            // ReturnFields.Add("AlipayAccountNo", "支付宝账号");
            // ReturnFields.Add("BankCardNo", "银行卡号");
            ReturnFields.Add("BankName", "开户行");
            ReturnFields.Add("PayKindName", "退款类型");
            ReturnFields.Add("Amount", "服务费金额");
            ReturnFields.Add("ReturnAmount", "达标奖金额");
            ReturnFields.Add("SeoDescription", "备注");
            // ReturnFields.Add("UserIdRealName", "创客真实姓名");
            // ReturnFields.Add("UserIdMakerCode", "创客编号");

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

        #endregion


        #region 非首台导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportsExcel(MerchantDepositReturns data, string CreateDateData, string UpdateDateData, string MerchantName, string PosSn, string PayKindSelect, string BankNameSelect, string StatusSelect, string BrandId)
        {

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

            Fields.Add("AlipayAccountNo", "1"); //支付宝账号
            Fields.Add("BankCardNo", "1"); //银行卡号
            Fields.Add("SeoKeyword", "1"); //退押订单号

            string condition = " and Status>-1 and QueryCount=0";

            //提现状态
            if (!string.IsNullOrEmpty(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }
            //退款类型
            if (!string.IsNullOrEmpty(PayKindSelect))
            {
                condition += " and PayKind=" + PayKindSelect;
            }
            //开户行
            if (!string.IsNullOrEmpty(BankNameSelect))
            {
                condition += " and BankName=" + BankNameSelect;
            }
            //品牌
            if (!string.IsNullOrEmpty(BrandId))
            {
                int brandId = int.Parse(BrandId);
                var merchantIds = "";
                var posMerchantInfo = db.PosMerchantInfo.Where(m => m.Status > -1 && m.BrandId == brandId && m.StandardMonths == 10).ToList();
                foreach (var item in posMerchantInfo)
                {
                    merchantIds += item.Id + ",";
                }
                merchantIds = merchantIds.TrimEnd(',');
                condition += " and MerchantId In(" + merchantIds + ")";
            }
            //创建时间
            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'";
            }
            //发放时间
            if (!string.IsNullOrEmpty(UpdateDateData))
            {
                string[] datelist = UpdateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and UpdateDate>='" + start + " 00:00:00' and UpdateDate<='" + end + " 23:59:59'";
            }
            if (!string.IsNullOrEmpty(MerchantName))
            {
                var Ids = "";
                var posMerchantInfo = db.PosMerchantInfo.Where(m => m.MerRealName == MerchantName).ToList();
                foreach (var item in posMerchantInfo)
                {
                    Ids += item.Id + ",";
                }
                Ids = Ids.TrimEnd(',');
                condition += " and MerchantId in(" + Ids + ")";
            }
            if (!string.IsNullOrEmpty(PosSn))
            {
                var Ids = "";
                var posMerchantInfo = db.PosMerchantInfo.Where(m => m.KqSnNo == PosSn).ToList();
                foreach (var item in posMerchantInfo)
                {
                    Ids += item.Id + ",";
                }
                Ids = Ids.TrimEnd(',');
                condition += " and MerchantId in(" + Ids + ")";
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("MerchantDepositReturns", Fields, "Id desc", "0", 1, 20000, condition, "Id,MerchantId,SeoKeyword,CreateDate,SeoDescription,AlipayAccountNo,BankCardNo,BankName", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                int Id = int.Parse(function.CheckInt(dic["Id"].ToString()));
                var merchantDepositReturn = db.MerchantDepositReturns.FirstOrDefault(m => m.Id == Id) ?? new MerchantDepositReturns();
                //商户
                int MerchantId = int.Parse(function.CheckInt(dic["MerchantId"].ToString()));
                // var merchantDepositReturns = db.MerchantDepositReturns.FirstOrDefault(m => m.MerchantId == MerchantId) ?? new MerchantDepositReturns();
                // PosMerchantInfo merchantid_PosMerchantInfo = db.PosMerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new PosMerchantInfo();
                PosMerchantInfo merchantid_PosMerchantInfo = db.PosMerchantInfo.FirstOrDefault(m => m.Id == merchantDepositReturn.MerchantId) ?? new PosMerchantInfo();
                dic["MerchantIdMerRealName"] = merchantid_PosMerchantInfo.MerRealName;
                // dic["MerchantIdMerchantMobile"] = merchantid_PosMerchantInfo.MerchantMobile;
                // dic["MerchantIdMerIdcardNo"] = merchantid_PosMerchantInfo.MerIdcardNo;
                dic.Remove("MerchantId");
                dic["PosSn"] = merchantid_PosMerchantInfo.KqSnNo;
                dic["BrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(merchantid_PosMerchantInfo.BrandId.ToString()));
                // 实际返还金额
                // decimal amt = decimal.Parse(merchantDepositReturns.ReturnAmount.ToString());
                decimal amt = decimal.Parse(merchantDepositReturn.ReturnAmount.ToString());
                dic["Amount"] = amt.ToString("f2");
                dic["ReturnAmount"] = (amt * 0.92M).ToString("f2");

                if (!string.IsNullOrEmpty(merchantDepositReturn.AlipayAccountNo))
                {
                    dic["AccountNo"] = merchantDepositReturn.AlipayAccountNo;
                }
                if (!string.IsNullOrEmpty(merchantDepositReturn.BankCardNo))
                {
                    dic["AccountNo"] = merchantDepositReturn.BankCardNo;
                }


                int PayKind = merchantDepositReturn.PayKind;
                if (PayKind == 0) dic["PayKindName"] = "支付宝";
                if (PayKind == 1) dic["PayKindName"] = "银行卡";
                dic.Remove("Id");
                dic.Remove("AlipayAccountNo");
                dic.Remove("BankCardNo");
            }

            Dictionary<string, object> result = new Dictionary<string, object>();
            // result.Add("Status", "0");
            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("Id", "记录ID");
            ReturnFields.Add("CreateDate", "申请提现时间");
            ReturnFields.Add("MerchantIdMerRealName", "商户真实姓名");
            ReturnFields.Add("BrandId", "机具品牌");
            ReturnFields.Add("PosSn", "机具Sn");
            // ReturnFields.Add("MerchantIdMerchantMobile", "商户手机号");
            // ReturnFields.Add("MerchantIdMerIdcardNo", "商户身份证号");
            ReturnFields.Add("SeoKeyword", "退押订单号");
            ReturnFields.Add("AccountNo", "收款账号");
            // ReturnFields.Add("AlipayAccountNo", "支付宝账号");
            // ReturnFields.Add("BankCardNo", "银行卡号");
            ReturnFields.Add("BankName", "开户行");
            ReturnFields.Add("PayKindName", "退款类型");
            ReturnFields.Add("Amount", "服务费金额");
            ReturnFields.Add("ReturnAmount", "达标奖金额");
            ReturnFields.Add("SeoDescription", "备注");
            // ReturnFields.Add("UserIdRealName", "创客真实姓名");
            // ReturnFields.Add("UserIdMakerCode", "创客编号");

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

        #endregion

    }
}
