/*
 * 提现记录
 */

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.OpModels;
using Library;
using LitJson;
using MySystemLib;

namespace MySystem.Areas.Admin.Controllers
{
    [Area("Admin")]
    [Route("Admin/[controller]/[action]")]
    public class UserCashRecordOperateController : BaseController
    {
        public UserCashRecordOperateController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
            OtherMySqlConn.connstr = ConfigurationManager.AppSettings["OpSqlConnStr"].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 OpCode, string StatusSelect, 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(OpCode))
            {
                condition += " and UserId in (select UserId from SysAdmin where OpCode='" + OpCode + "')";
            }
            //提现状态
            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 = 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 = opdb.UserCashRecord.Any(m => m.CreateDate >= start && m.TradeType < 3);
                var checks = opdb.UserCashRecord.Any(m => m.CreateDate <= end && m.TradeType < 3);
                if (check)
                {
                    var sId = opdb.UserCashRecord.Where(m => m.CreateDate >= start && m.TradeType < 3).Min(m => m.Id);
                    condition += "  and Id >=" + sId;
                }
                if (checks)
                {
                    var eId = opdb.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 = opdb.UserCashRecord.Any(m => m.CreateDate >= start && m.TradeType < 3);
                if (check)
                {
                    var minId = opdb.UserCashRecord.Where(m => m.CreateDate >= start && m.TradeType < 3).Min(m => m.Id);
                    var Info = function.ReadInstance("/WritePage/OpUserCashRecord/OpUserCashRecord.txt");
                    if (string.IsNullOrEmpty(Info.ToString()))
                    {
                        function.WritePage("/WritePage/OpUserCashRecord/", "OpUserCashRecord.txt", minId.ToString());
                        condition += " and Id >=" + minId;
                    }
                    else if (minId != int.Parse(Info))
                    {
                        function.WritePage("/WritePage/OpUserCashRecord/", "OpUserCashRecord.txt", minId.ToString());
                        condition += " and Id >=" + minId;
                    }
                    else
                    {
                        condition += " and Id >=" + Convert.ToInt32(Info);
                    }
                }
                else
                {
                    condition += " and Id =0";
                }
            }

            Dictionary<string, object> obj = new AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).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());
                SysAdmin sysAdmin = opdb.SysAdmin.FirstOrDefault(m => m.UserId == UserId) ?? new SysAdmin();
                dic["OpCode"] = sysAdmin.OpCode;
                dic["MakerCode"] = sysAdmin.MakerCode;
                dic["RealName"] = sysAdmin.MakerName;
                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 增加提现记录

        /// <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 AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).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 = opdb.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 AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).Edit("UserCashRecord", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "UserCashRecord", "update");
            opdb.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 AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).Edit("UserCashRecord", Fields, id);
            }
            opdb.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 AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).Edit("UserCashRecord", Fields, id);
            }
            opdb.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 AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).Edit("UserCashRecord", Fields, id);
            }
            opdb.SaveChanges();
            return "success";
        }

        #endregion


        #region 批量设置成功

        /// <summary>
        /// 批量设置成功
        /// </summary>
        /// <returns></returns>
        public string BatchSetting(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "OpUserCashRecord", "BatchSetting");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", 1);//设置提现记录为成功
                Fields.Add("SeoTitle", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                new AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).Edit("UserCashRecord", Fields, id);
            }
            opdb.SaveChanges();
            return "success";
        }

        #endregion

        #region 排序
        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="Id"></param>
        public string Sort(int Id, int Sort)
        {
            new AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).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("ExcelImportOperate", ExcelPath + "#cut#OpUserCashRecord#cut#" + key + "#cut#" + SysUserName);
            return "success|" + key;
        }
        public string CheckImport(string key)
        {
            string result = RedisDbconn.Instance.Get<string>("OpCheckImport:" + 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 OpCode, 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 and TradeType<3";
            //运营中心编号
            if (!string.IsNullOrEmpty(OpCode))
            {
                var sysUser = opdb.SysAdmin.FirstOrDefault(m => m.OpCode == OpCode) ?? new OpModels.SysAdmin();
                if (sysUser.Id > 0)
                {
                    condition += " and OpId=" + sysUser.UserId;
                }
            }
            //提现状态
            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 AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).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());
                SysAdmin sysAdmin = opdb.SysAdmin.FirstOrDefault(m => m.UserId == UserId) ?? new SysAdmin();
                var user = db.Users.FirstOrDefault(m => m.Id == sysAdmin.UserId) ?? new Models.Users();
                dic["OpCode"] = sysAdmin.OpCode;
                dic["MakerCode"] = sysAdmin.MakerCode;
                dic["MakerName"] = sysAdmin.MakerName;
                dic["RealName"] = sysAdmin.RealName;
                dic["Mobile"] = sysAdmin.MakerMobile;
                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("OpCode", "运营中心编号");
            ReturnFields.Add("MakerCode", "创客编号");
            ReturnFields.Add("MakerName", "创客姓名");
            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", "OpUserCashRecord", "ExportExcel");
            return Json(result);
        }

        #endregion


        #region 拒绝

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

            UserCashRecord editData = opdb.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 = opdb.UserCashRecord.FirstOrDefault(m => m.Id == Id);
            if (edit != null)
            {
                edit.Status = 2;
                edit.Remark = Remark;
                edit.UpdateMan = SysUserName;
                UserAccount account = opdb.UserAccount.FirstOrDefault(m => m.Id == edit.UserId);
                if (account != null)
                {
                    decimal TradeAmount = edit.TradeAmount;
                    decimal BeforeAmount = account.TotalAmt + account.ValidAmount + account.ValidForGetAmount; //变更前总金额
                    decimal AfterAmount = account.TotalAmt + account.ValidAmount + account.ValidForGetAmount + TradeAmount; //变更后总金额
                    account.ValidForGetAmount += TradeAmount;//返回可提现余额
                    opdb.AmountRecord.Add(new AmountRecord()
                    {
                        CreateDate = DateTime.Now,
                        UserId = edit.UserId, //创客
                        SeoDescription = "提现驳回",
                        UseAmount = TradeAmount, //变更金额
                        BeforeAmount = BeforeAmount, //变更前总金额
                        AfterAmount = AfterAmount, //变更后总金额
                        AfterTotalAmt = account.TotalAmt,
                        AfterValidForGetAmount = account.ValidForGetAmount,
                        AfterValidAmount = account.ValidAmount,
                        OperateType = 1,
                    });
                    opdb.SaveChanges();
                }

                opdb.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 = opdb.UserCashRecord.FirstOrDefault(m => m.Id == id);
                if (edit != null)
                {
                    edit.QueryCount = 0;
                    opdb.SaveChanges();
                }
            }

            return "success";
        }

        #endregion

    }
}