/*
 * 提现记录
 */

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();
        }

        #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";
            //创客编号
            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 + "')";
                // condition += " and UserId in (select Id from Users 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(TradeAmount) from UserCashRecord where Status=0" + condition);
            if (dt.Rows.Count > 0)
            {
                WaitAmount = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString())).ToString("f2");
            }
            dt = OtherMySqlConn.dtable("select sum(TradeAmount) from UserCashRecord where Status=1" + condition);
            if (dt.Rows.Count > 0)
            {
                SuccessAmount = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString())).ToString("f2");
            }
            dt = OtherMySqlConn.dtable("select sum(TradeAmount) from UserCashRecord where Status=2" + condition);
            if (dt.Rows.Count > 0)
            {
                FailAmount = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString())).ToString("f2");
            }
            other.Add("WaitAmount", WaitAmount);
            other.Add("SuccessAmount", SuccessAmount);
            other.Add("FailAmount", FailAmount);
            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>
        /// <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("ExcelImportV2", 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 PayStatus)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("CashOrderNo", "1"); //提现单号
            Fields.Add("CreateDate", "3"); //创建时间
            Fields.Add("TradeType", "0"); //交易类型

            string condition = " and Status>-1";
            //创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            //创客名称
            if (!string.IsNullOrEmpty(RealName))
            {
                condition += " and UserId in (select UserId from UserForRealName where RealName='" + RealName + "')";
            }
            //提现状态
            if (!string.IsNullOrEmpty(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", 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");
                // 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"] = "失败";
                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("CashOrderNo", "提现单号");
            // ReturnFields.Add("MakerCode", "创客编码");
            // ReturnFields.Add("RealName", "创客名称");
            // ReturnFields.Add("IdCardNo", "身份证号");
            // ReturnFields.Add("SettleBankCardNo", "提现卡号");
            // ReturnFields.Add("SettleBankName", "银行名称");
            // ReturnFields.Add("TradeType", "交易类型");
            // ReturnFields.Add("TradeAmount", "交易金额(元)");
            // ReturnFields.Add("Status", "订单状态");
            // ReturnFields.Add("ReturnCode", "提现服务返回编码");
            // ReturnFields.Add("ReturnMsg", "提现服务返回信息");
            // ReturnFields.Add("CreateDate", "创建时间");
            result.Add("Fields", ReturnFields);
            AddSysLog("0", "UserCashRecord", "ExportExcel");
            return Json(result);
        }

        #endregion






        #region 提交代付平台

        /// <summary>
        /// 提交代付平台
        /// </summary>
        /// <returns></returns>
        public string Cash(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "UserCashRecord", "cash");
            db.SaveChanges();
            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)
                {
                    edit.QueryCount = 1;
                    db.SaveChanges();
                    RedisDbconn.Instance.AddList("CashPayApplyQueue", Newtonsoft.Json.JsonConvert.SerializeObject(edit));
                }
            }
            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)
            {
                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

    }
}