/*
 * 直营团队提现记录
 */

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 UserCashRecordForBusinessController : BaseController
    {
        public UserCashRecordForBusinessController(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(UserCashRecordForBusiness 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(UserCashRecordForBusiness data, string MakerCode, string RealName, string CreateDateData, int page = 1, int limit = 30)
        {

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

            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 Id from Users where RealName='" + RealName + "')";
            }
            if (!string.IsNullOrEmpty(data.CashOrderNo))
            {
                condition += " and CashOrderNo='" + data.CashOrderNo + "'";
            }

            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                var start = datelist[0];
                var end = datelist[1];
                condition += " and CreateDate>='" + start + " 00:00:00' and CreateDate<='" + end + " 23:59:59'";
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("UserCashRecordForBusiness", 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;
            }
            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(UserCashRecordForBusiness data, string MakerCode, string RealName, string Amount)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            var userInfo = db.Users.FirstOrDefault(m => m.MakerCode == MakerCode && m.RealName == RealName && m.BusinessFlag == 1) ?? new Users();
            if (userInfo.Id > 0 && !string.IsNullOrEmpty(Amount))
            {
                UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == userInfo.Id) ?? new UserAccount();
                // GetReserve(MakerCode, RealName, Amount);
                if (account.BalanceAmount - account.ToChargeAmount - decimal.Parse(Amount) >= 0)
                {
                    string CashOrderNo = "T1" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
                    Fields.Add("UserId", userInfo.Id); //创客Id
                    Fields.Add("CreateMan", SysUserName + "_" + SysRealName); //操作人
                    Fields.Add("TradeAmount", Amount); //提现金额
                    Fields.Add("CashOrderNo", CashOrderNo); //提现单号
                    Fields.Add("SeoKeyword", data.SeoKeyword); //备注
                    int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Add("UserCashRecordForBusiness", Fields, 0);

                    decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                    decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                    decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                    account.BalanceAmount -= decimal.Parse(Amount);
                    // account.FreezeAmount += decimal.Parse(Amount);
                    account.WithdrawAmount += decimal.Parse(Amount);
                    decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                    decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                    decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额

                    db.UserAccountRecord.Add(new UserAccountRecord()
                    {
                        CreateDate = DateTime.Now,
                        UserId = userInfo.Id, //创客
                        ChangeType = 132, //变动类型
                        Kind = 2,
                        Remark = data.SeoKeyword, // 备注
                        ChangeAmount = decimal.Parse(Amount), //变更金额
                        BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                        AfterTotalAmount = AfterTotalAmount, //变更后总金额
                        BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                        AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                        BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                        AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                    });
                    AddSysLog(data.Id.ToString(), "UserCashRecordForBusiness", "add");
                    db.SaveChanges();
                    return "success";
                }
                else
                {
                    return "创客可提现余额不足";
                }
            }
            else
            {
                return "输入的创客信息不存在或者创客编号和姓名不匹配";
            }
        }

        #endregion

        #region 获取创客账户信息
        public string GetReserve(string MakerCode, string RealName, string Amount)
        {
            var userInfo = db.Users.FirstOrDefault(m => m.MakerCode == MakerCode && m.RealName == RealName) ?? new Users();
            UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == userInfo.Id) ?? new UserAccount();
            return "当前余额为：" + account.BalanceAmount + "元 可提现余额为：" + (account.BalanceAmount - account.ToChargeAmount) + "元 提现后余额为：" + (account.BalanceAmount - decimal.Parse(Amount)) + "元";
        }
        #endregion


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

            return View();
        }

        [HttpPost]
        public string QuickExportExcelDo(string CashOrderNo, string MakerCode, string RealName, string CreateDateData)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();

            string condition = " where 1=1 and a.Status>-1";
            //创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                condition += " and a.UserId in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            //创客名称
            if (!string.IsNullOrEmpty(RealName))
            {
                condition += " and a.UserId in (select Id from Users where RealName='" + RealName + "')";
            }
            if (!string.IsNullOrEmpty(CashOrderNo))
            {
                condition += " and a.CashOrderNo='" + CashOrderNo + "'";
            }

            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                var start = datelist[0];
                var end = datelist[1];
                condition += " and a.CreateDate>='" + start + " 00:00:00' and a.CreateDate<='" + end + " 23:59:59'";
            }
            var Sql = "SELECT b.MakerCode '创客编号',b.RealName '创客姓名',a.CashOrderNo '提现单号',a.TradeAmount '提现金额',DATE_FORMAT(a.CreateDate,'%Y-%m-%d %H:%i:%s') '提现时间',a.SeoKeyword '备注',a.CreateMan '操作人' FROM UserCashRecordForBusiness a LEFT JOIN Users b ON a.UserId=b.Id" + condition;
            var sysAdmin = bsdb.SysAdmin.FirstOrDefault(m => m.AdminName == SysUserName && m.Status > -1);
            var FileName = "直营团队提现记录" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string SendData = "{\"Operater\":\"" + sysAdmin.Id + "\",\"SqlString\":\"" + Sql + "\",\"FileName\":\"" + FileName + "\",\"MaxCount\":\"0\"}";
            RedisDbconn.Instance.AddList("ExportQueue", SendData);
            return "success";
        }
        #endregion

    }
}