using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authorization;

using System.Web;
using MySystem.MainModels;
using LitJson;
using Library;

namespace MySystem.Areas.Api.Controllers.v1
{
    [Area("Api")]
    [Route("Api/v1/[controller]/[action]")]
    public class UserCashRecordController : BaseController
    {
        public UserCashRecordController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
        }




        #region 创客-我的-提现-提交提现申请
        [Authorize]
        public JsonResult PostWithdraw(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = PostWithdrawDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson PostWithdrawDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客
            decimal TradeAmount = decimal.Parse(function.CheckNum(data["TradeAmount"].ToString())); //交易金额
            var amount = 0;//手续费
            if (TradeAmount < 100)
            { 
                return new AppResultJson() { Status = "-1", Info = "100元起提" };
            }
            if (TradeAmount < 500)
            { 
                amount = 3;
            }
            UserAccount account = maindb.UserAccount.FirstOrDefault(m => m.Id == UserId) ?? new UserAccount();
            if (account.AccountStatus == 1)
            { 
                return new AppResultJson() { Status = "-1", Info = "参数错误，请联系客服" };
            }
            if (account.BalanceAmount <= 0 || account.BalanceAmount - account.ToChargeAmount <= 0)
            { 
                return new AppResultJson() { Status = "-1", Info = "余额不足" };
            }
            if (account.BalanceAmount - account.ToChargeAmount < TradeAmount)
            {
                TradeAmount = account.BalanceAmount - account.ToChargeAmount;
            }
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            string CashOrderNo = "BC" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
            Users user = UsersDbconn.Instance.Get(UserId) ?? new Users();
            decimal ManageFee = TradeAmount * 0.08M;
            decimal ActualTradeAmount = TradeAmount - ManageFee;
            decimal TradeFee = 0; // 服务费
            if(TradeAmount < 500) //单次提现500元以下的订单收取3元提现服务费/笔
            {
                TradeFee = 3;
                ActualTradeAmount -= TradeFee;
            }
            UserCashRecord cash = maindb.UserCashRecord.Add(new UserCashRecord()
            {
                CreateDate = DateTime.Now,
                CashOrderNo = CashOrderNo, //申请提现单号
                UserId = UserId, //创客
                IdCardNo = user.CertId, //身份证号
                SettleBankCardNo = user.SettleBankCardNo, //提现卡号
                SettleBankName = user.SettleBankName, //银行名称
                TradeType = 2, //交易类型
                TradeAmount = TradeAmount, //交易金额
                ActualTradeAmount = ActualTradeAmount,
                ManageFee = ManageFee,
                TradeFee = TradeFee,
            }).Entity;
            maindb.SaveChanges();
            decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
            decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
            decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
            account.BalanceAmount -= TradeAmount;
            account.FreezeAmount += TradeAmount;
            decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
            decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
            decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
            maindb.UserAccountRecord.Add(new UserAccountRecord()
            {
                CreateDate = DateTime.Now,
                UpdateDate = DateTime.Now,
                UserId = user.Id, //创客
                ChangeType = 2, //变动类型
                ProductType = 99, //产品类型
                ChangeAmount = TradeAmount, //变更金额
                BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                AfterTotalAmount = AfterTotalAmount, //变更后总金额
                BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                AfterBalanceAmount = AfterBalanceAmount, //变更后余额
            });
            maindb.SaveChanges();
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 创客-我的-提现-提现记录
        [Authorize]
        public JsonResult List(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            List<Dictionary<string, object>> dataList = ListDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList });
        }
        public List<Dictionary<string, object>> ListDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客
            int PageSize = int.Parse(function.CheckInt(data["PageSize"].ToString()));
            int PageNum = int.Parse(function.CheckInt(data["PageNum"].ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            // List<int> query = UserCashRecordDbconn.Instance.GetList(UserId, PageNum, PageSize);
            IQueryable<UserCashRecord> query = maindb.UserCashRecord.Where(m => m.UserId == UserId && m.TradeType < 3).OrderByDescending(m => m.Id);
            if (PageNum == 1)
            {
                query = query.Take(PageSize);
            }
            else
            {
                int skipNum = PageSize * (PageNum - 1);
                query = query.Skip(skipNum).Take(PageSize);
            }
            foreach (UserCashRecord subdata in query.ToList())
            {
                // UserCashRecord subdata = UserCashRecordDbconn.Instance.Get(CashRecordId) ?? new UserCashRecord();
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("TradeAmount", subdata.TradeAmount); //交易金额
                curData.Add("Remark", "提现到" + subdata.SettleBankName + "(" + subdata.SettleBankCardNo.Substring(subdata.SettleBankCardNo.Length - 4) + ")"); //备注
                curData.Add("Status", subdata.Status); //状态，0-处理中，1-交易成功，2-提现失败，3-挂账，-1-状态异常
                curData.Add("CreateDate", subdata.CreateDate == null ? "" : subdata.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //CreateDate
                curData.Add("Id", subdata.Id); //Id
                dataList.Add(curData);
            }
            return dataList;
        }
        #endregion


        #region 创客-盟主可提现金额提现-提交提现申请
        [Authorize]
        public JsonResult LeaderPostWithdraw(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = LeaderPostWithdrawDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson LeaderPostWithdrawDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客
            decimal TradeAmount = decimal.Parse(function.CheckNum(data["TradeAmount"].ToString())); //交易金额
            if (TradeAmount < 100)
            { 
                return new AppResultJson() { Status = "-1", Info = "100元起提" };
            }
            UserAccount account = maindb.UserAccount.FirstOrDefault(m => m.Id == UserId) ?? new UserAccount();
            if (account.AccountStatus == 1)
            { 
                return new AppResultJson() { Status = "-1", Info = "参数错误，请联系客服" };
            }
            if (account.LeaderBalanceAmount <= 0)
            { 
                return new AppResultJson() { Status = "-1", Info = "余额不足" };
            }
            if (account.LeaderBalanceAmount < TradeAmount)
            {
                TradeAmount = account.LeaderBalanceAmount;
            }
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            string CashOrderNo = "MZTX" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
            Users user = UsersDbconn.Instance.Get(UserId) ?? new Users();
            decimal ActualTradeAmount = TradeAmount;
            decimal ManageFee = TradeAmount - ActualTradeAmount;
            UserCashRecord cash = maindb.UserCashRecord.Add(new UserCashRecord()
            {
                CreateDate = DateTime.Now,
                CashOrderNo = CashOrderNo, //申请提现单号
                UserId = UserId, //创客
                IdCardNo = user.CertId, //身份证号
                SettleBankCardNo = user.SettleBankCardNo, //提现卡号
                SettleBankName = user.SettleBankName, //银行名称
                TradeType = 3, //交易类型(3 盟主可提现金额提现)
                TradeAmount = TradeAmount, //交易金额
                ActualTradeAmount = TradeAmount,
                ManageFee = ManageFee,
            }).Entity;
            maindb.SaveChanges();
            decimal BeforeBalanceAmount = account.LeaderBalanceAmount; //变更前余额
            account.LeaderBalanceAmount -= TradeAmount;
            decimal AfterBalanceAmount = account.LeaderBalanceAmount; //变更后余额
            maindb.LeaderAccountRecord.Add(new LeaderAccountRecord()
            {
                CreateDate = DateTime.Now,
                Sort = cash.Id,//提现详情Id
                TransRecordNo = CashOrderNo,//提现单号
                SeoDescription = "提现到" + user.SettleBankName + "(" + user.SettleBankCardNo.Substring(user.SettleBankCardNo.Length - 4) + ")",//详情
                UserId = user.Id, //创客
                ChangeType = 2, //变动类型
                ProductType = 99, //产品类型
                ChangeAmount = TradeAmount, //变更金额
                BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                AfterBalanceAmount = AfterBalanceAmount, //变更后余额
            });
            maindb.SaveChanges();
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 创客-盟主可提现金额提现-提现记录
        [Authorize]
        public JsonResult LeaderList(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            List<Dictionary<string, object>> dataList = LeaderListDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList });
        }
        public List<Dictionary<string, object>> LeaderListDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客
            int PageSize = int.Parse(function.CheckInt(data["PageSize"].ToString()));
            int PageNum = int.Parse(function.CheckInt(data["PageNum"].ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            IQueryable<UserCashRecord> query = maindb.UserCashRecord.Where(m => m.UserId == UserId && m.TradeType == 3).OrderByDescending(m => m.Id);
            if (PageNum == 1)
            {
                query = query.Take(PageSize);
            }
            else
            {
                int skipNum = PageSize * (PageNum - 1);
                query = query.Skip(skipNum).Take(PageSize);
            }
            foreach (UserCashRecord subdata in query.ToList())
            {
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("TradeAmount", subdata.ActualTradeAmount); //交易金额
                curData.Add("Remark", "提现到" + subdata.SettleBankName + "(" + subdata.SettleBankCardNo.Substring(subdata.SettleBankCardNo.Length - 4) + ")"); //备注
                curData.Add("Status", subdata.Status); //状态，0-处理中，1-交易成功，2-提现失败，3-挂账，-1-状态异常
                curData.Add("CreateDate", subdata.CreateDate == null ? "" : subdata.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //CreateDate
                curData.Add("Id", subdata.Id); //Id
                curData.Add("DetailId", subdata.Id); //详情Id
                dataList.Add(curData);
            }
            return dataList;
        }
        #endregion



        #region 创客-我的-提现-提现记录详情
        [Authorize]
        public JsonResult Detail(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = DetailDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> DetailDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            UserCashRecord query = UserCashRecordDbconn.Instance.Get(Id) ?? new UserCashRecord();
            Obj.Add("CashOrderNo", query.CashOrderNo); //申请提现单号
            Obj.Add("TradeAmount", query.TradeAmount); //交易金额
            Obj.Add("ActualTradeAmount", query.ActualTradeAmount); //实际交易金额
            Obj.Add("TradeFee", query.TradeFee); //交易手续费
            Obj.Add("ManageFee", query.ManageFee); //扣税金额
            Obj.Add("PaymentDate", query.PaymentDate == null ? "" : query.PaymentDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //支付时间
            Obj.Add("Remark", query.Remark); //备注
            Obj.Add("Id", query.Id); //Id
            Obj.Add("CreateDate", query.CreateDate); //创建时间
            Obj.Add("Status", query.Status); //状态，0-处理中，1-交易成功，2-提现失败，3-挂账，-1-状态异常
            return Obj;
        }
        #endregion


        #region 创客-我的-盟主可提现金额提现-提现记录详情
        [Authorize]
        public JsonResult LeaderDetail(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = LeaderDetailDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> LeaderDetailDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            UserCashRecord query = maindb.UserCashRecord.FirstOrDefault(m => m.Id == Id) ?? new UserCashRecord();
            Obj.Add("CashOrderNo", query.CashOrderNo); //申请提现单号
            Obj.Add("TradeAmount", query.TradeAmount); //交易金额
            Obj.Add("ActualTradeAmount", query.ActualTradeAmount); //实际交易金额
            Obj.Add("TradeFee", query.TradeFee); //交易手续费
            Obj.Add("ManageFee", query.ManageFee); //扣税金额
            Obj.Add("PaymentDate", query.PaymentDate == null ? "" : query.PaymentDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //支付时间
            Obj.Add("Remark", query.Remark); //备注
            Obj.Add("Id", query.Id); //Id
            Obj.Add("CreateDate", query.CreateDate); //创建时间
            Obj.Add("Status", query.Status); //状态，0-处理中，1-交易成功，2-提现失败，3-挂账，-1-状态异常
            return Obj;
        }
        #endregion



        #region 检查签名是否合法，合法返回1，不合法返回提示信息

        /// <summary>
        /// 检查签名是否合法，合法返回1，不合法返回提示信息
        /// </summary>
        /// <param name="value">请求的参数(json字符串)</param>
        /// <param name="signField">要签名的字段</param>
        /// <returns></returns>
        private string CheckSign(string value, string[] signField)
        {
            JsonData json = JsonMapper.ToObject(value);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            for (int i = 0; i < signField.Length; i++)
            {
                dic.Add(signField[i], json[signField[i]].ToString());
            }
            string sign = json["sign"].ToString(); //客户端签名字符串
            return new Sign().sign(dic, sign);
        }

        #endregion

    }
}
