/*
 * 小分仓额度记录
 */

using System;
using System.Web;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
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 PreAmountRecordController : BaseController
    {
        public PreAmountRecordController(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(PreAmountRecord data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;


            return View();
        }

        #endregion

        #region 根据条件查询小分仓临时额度记录列表

        /// <summary>
        /// 根据条件查询小分仓临时额度记录列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(PreAmountRecord data, string UserIdRealName, string UserIdMakerCode, string CreateDateData, string OperateTypeSelect, string PayModeSelect, int page = 1, int limit = 30)
        {

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

            string condition = " and Status>=-1";
            //创客真实姓名
            if (!string.IsNullOrEmpty(UserIdRealName))
            {
                condition += " and UserId in (select UserId from UserForRealName where RealName='" + UserIdRealName + "')";
            }
            //创客编号
            if (!string.IsNullOrEmpty(UserIdMakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + UserIdMakerCode + "')";
            }
            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(OperateTypeSelect))
            {
                condition += " and OperateType=" + OperateTypeSelect;
            }
            //额度类别
            if (!string.IsNullOrEmpty(PayModeSelect))
            {
                condition += " and PayMode=" + PayModeSelect;
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("PreAmountRecord", 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(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 ChangeType = int.Parse(dic["Sort"].ToString());
                if (ChangeType == 1) dic["ChangeType"] = "购买临额";
                if (ChangeType == 3) dic["ChangeType"] = "调低临额";

                //操作类别
                int OperateType = int.Parse(dic["OperateType"].ToString());
                if (OperateType == 0) dic["OperateType"] = "减少";
                if (OperateType == 1) dic["OperateType"] = "增加";

                //额度类别
                int PayMode = int.Parse(dic["PayMode"].ToString());
                if (PayMode == 1) dic["PayMode"] = "支付宝";
                if (PayMode == 3) dic["PayMode"] = "余额";
                if (PayMode == 0) dic["PayMode"] = "";

            }
            return Json(obj);
        }

        #endregion



        #region 小分仓银行卡临额提现记录列表

        /// <summary>
        /// 根据条件查询小分仓银行卡临额提现记录列表
        /// </summary>
        /// <returns></returns>
        public IActionResult Indexs(PreAmountRecord data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;


            return View();
        }

        #endregion

        #region 小分仓银行卡临额提现记录列表

        /// <summary>
        /// 根据条件查询小分仓银行卡临额提现记录列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexsData(PreAmountRecord data, string UserIdRealName, string UserIdMakerCode, string CreateDateData, string OperateTypeSelect, string PayModeSelect, string StatusSelect = "0", int page = 1, int limit = 30)
        {

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

            string condition = " and Status>=-1 and PayMode=1 and Sort=3";
            //创客真实姓名
            if (!string.IsNullOrEmpty(UserIdRealName))
            {
                condition += " and UserId in (select UserId from Users where RealName='" + UserIdRealName + "')";
            }
            //创客编号
            if (!string.IsNullOrEmpty(UserIdMakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + UserIdMakerCode + "')";
            }
            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(OperateTypeSelect))
            {
                condition += " and OperateType=" + OperateTypeSelect;
            }
            //额度类别
            if (!string.IsNullOrEmpty(PayModeSelect))
            {
                condition += " and PayMode=" + PayModeSelect;
            }
            //状态
            if (!string.IsNullOrEmpty(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("PreAmountRecord", 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(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["CertId"] = userid_Users.CertId;
                dic["SettleBankCardNo"] = userid_Users.SettleBankCardNo;
                dic["SettleBankName"] = userid_Users.SettleBankName;
                dic["Mobile"] = userid_Users.Mobile;
                dic["Type"] = "临额提现";
                dic.Remove("UserId");

                //操作类别
                int OperateType = int.Parse(dic["OperateType"].ToString());
                if (OperateType == 0) dic["OperateType"] = "减少";
                if (OperateType == 1) dic["OperateType"] = "增加";

                //额度类别
                int PayMode = int.Parse(dic["PayMode"].ToString());
                if (PayMode == 1) dic["PayMode"] = "支付宝";
                if (PayMode == 3) dic["PayMode"] = "余额";
                if (PayMode == 0) dic["PayMode"] = "";

                //状态
                int Status = int.Parse(dic["Status"].ToString());
                if (Status == 0) dic["Status"] = "待处理";
                if (Status == 2) dic["Status"] = "处理中";
                if (Status == 1) dic["Status"] = "成功";
                if (Status == -1) dic["Status"] = "失败";
            }
            return Json(obj);
        }

        #endregion



        #region 小分仓银行卡临额提现记录导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportsExcel(PreAmountRecord data, string UserIdRealName, string UserIdMakerCode, string CreateDateData, string StatusSelect)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();


            string condition = " and PayMode=1 and Sort=3";
            //创客真实姓名
            if (!string.IsNullOrEmpty(UserIdRealName))
            {
                condition += " and UserId in (select UserId from Users where RealName='" + UserIdRealName + "')";
            }
            //创客编号
            if (!string.IsNullOrEmpty(UserIdMakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + UserIdMakerCode + "')";
            }
            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(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }

            var Ids = "";
            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("PreAmountRecord", Fields, "Id desc", "0", 1, 20000, condition, "Id,CreateDate,UserId,UseAmount", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                //创客
                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["CertId"] = userid_Users.CertId;
                dic["SettleBankCardNo"] = userid_Users.SettleBankCardNo;
                dic["SettleBankName"] = userid_Users.SettleBankName;
                dic["Mobile"] = userid_Users.Mobile;
                dic["Type"] = "临额提现";
                dic["IsOk"] = "";
                dic.Remove("UserId");

                //记录Id
                int Id = int.Parse(function.CheckInt(dic["Id"].ToString()));
                var preAmountRecord = db.PreAmountRecord.FirstOrDefault(m => m.Id == Id) ?? new PreAmountRecord();
                if (preAmountRecord.Status == 0) dic["Status"] = "待处理";
                if (preAmountRecord.Status == 2) dic["Status"] = "处理中";
                if (preAmountRecord.Status == 1) dic["Status"] = "成功";
                if (preAmountRecord.Status == -1) dic["Status"] = "失败";
                dic["Id"] = Id;
                Ids += Id + ",";
            }
            Ids = Ids.TrimEnd(',');

            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("Id", "记录ID");
            ReturnFields.Add("CreateDate", "提现申请时间");
            ReturnFields.Add("Status", "提现结果");
            ReturnFields.Add("UserIdRealName", "创客真实姓名");
            ReturnFields.Add("UserIdMakerCode", "创客编号");
            ReturnFields.Add("UseAmount", "申请提现临额");
            ReturnFields.Add("CertId", "身份证号");
            ReturnFields.Add("SettleBankCardNo", "银行卡号");
            ReturnFields.Add("SettleBankName", "银行名称");
            ReturnFields.Add("Mobile", "手机号");
            ReturnFields.Add("Type", "交易类型");
            ReturnFields.Add("IsOk", "是否成功(是、否)");

            result.Add("Fields", ReturnFields);
            OtherMySqlConn.op("UPDATE PreAmountRecord SET `Status`=2 WHERE Id IN(" + Ids + ") AND `Status`=0");
            AddSysLog("0", "PreAmountRecord", "ExportExcel");
            return Json(result);
        }

        #endregion


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

            return View();
        }

        [HttpPost]
        public string QuickExportExcelDo(string UserIdRealName, string UserIdMakerCode, string CreateDateData, string StatusSelect)
        {

            Dictionary<string, string> Fields = new Dictionary<string, string>();
            string condition = " where 1=1 and a.PayMode=1 and a.Sort=3";
            string conditions = " and PayMode=1 and Sort=3";
            //创客真实姓名
            if (!string.IsNullOrEmpty(UserIdRealName))
            {
                condition += " and a.UserId in (select UserId from Users where RealName='" + UserIdRealName + "')";
                conditions += " and UserId in (select UserId from Users where RealName='" + UserIdRealName + "')";
            }
            //创客编号
            if (!string.IsNullOrEmpty(UserIdMakerCode))
            {
                condition += " and a.UserId in (select UserId from UserForMakerCode where MakerCode='" + UserIdMakerCode + "')";
                conditions += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + UserIdMakerCode + "')";
            }
            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and a.CreateDate>='" + start + " 00:00:00' and a.CreateDate<='" + end + " 23:59:59'";
                conditions += " and CreateDate>='" + start + " 00:00:00' and CreateDate<='" + end + " 23:59:59'";
            }
            //状态
            if (!string.IsNullOrEmpty(StatusSelect))
            {
                if (StatusSelect == "0")
                {
                    condition += " and a.Status=2";
                }
                else
                {
                    condition += " and a.Status=" + StatusSelect;
                }
                conditions += " and Status=" + StatusSelect;
            }

            var Ids = "";
            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("PreAmountRecord", Fields, "Id desc", "0", 1, 20000000, conditions, "Id", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                //记录Id
                int Id = int.Parse(function.CheckInt(dic["Id"].ToString()));
                Ids += Id + ",";
            }
            Ids = Ids.TrimEnd(',');

            OtherMySqlConn.op("UPDATE PreAmountRecord SET `Status`=2 WHERE Id IN(" + Ids + ") AND `Status`=0");
            
            var Sql = "SELECT a.Id '记录ID',DATE_FORMAT(a.CreateDate,'%Y-%m-%d %H:%i:%s') '提现申请时间',(CASE WHEN a.Status=0 THEN '待处理' WHEN a.Status=2 THEN '处理中' WHEN a.Status=1 THEN '成功' WHEN a.Status=-1 THEN '失败' ELSE '' end) '提现结果',b.RealName '创客真实姓名',b.MakerCode '创客编号',a.UseAmount '申请提现临额',b.CertId '身份证号',b.SettleBankCardNo '银行卡号',b.SettleBankName '银行名称',b.Mobile '手机号',(CASE WHEN a.AmountType=1 THEN '临额提现' ELSE '' end) '交易类型',null '是否成功(是、否)' FROM PreAmountRecord 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);
            AddSysLog(Ids, "PreAmountRecord", "ExportExcel");
            return "success";
        }
        #endregion



        #region 小分仓银行卡临额提现记录结果导入Excel
        /// <summary>
        /// 小分仓银行卡临额提现记录结果导入Excel
        /// </summary>
        /// <param name="ExcelData"></param>
        public string Imports(string ExcelData)
        {
            ExcelData = HttpUtility.UrlDecode(ExcelData);
            JsonData list = JsonMapper.ToObject(ExcelData);
            string error = "";
            List<int> IdList = new List<int>();
            List<int> IdLists = new List<int>();
            for (int i = 1; i < list.Count; i++)
            {
                JsonData dr = list[i];
                string itemJson = dr.ToJson();
                string Id = itemJson.Contains("\"A\"") ? dr["A"].ToString() : "";
                string IsOk = itemJson.Contains("\"L\"") ? dr["L"].ToString() : "";
                if (IdList.Contains(Convert.ToInt32(Id)))
                {
                    error += "以下操作失败" + Id + ',' + "该记录重复" + '\n';
                }
                else if (IsOk == "否")
                {
                    IdLists.Add(Convert.ToInt32(Id));
                }
                else
                {
                    IdList.Add(Convert.ToInt32(Id));
                }
            }
            if (!string.IsNullOrEmpty(error))
            {
                return "Warning|" + error;
            }
            else
            {
                var Info = db.PreAmountRecord.Where(m => IdList.Contains(m.Id) && m.Status == 2).ToList();//成功
                var Infos = db.PreAmountRecord.Where(m => IdLists.Contains(m.Id) && m.Status == 2).ToList();//失败
                foreach (var item in Info)
                {
                    item.Status = 1;//设置为成功
                    db.SaveChanges();
                }
                foreach (var items in Infos)
                {
                    items.Status = -1;//设置为失败
                    var userAccount = db.UserAccount.FirstOrDefault(m => m.Id == items.UserId) ?? new UserAccount();
                    if (userAccount.Id > 0)
                    {
                        userAccount.PreTempAmount += items.UseAmount;//退还卡充值临额
                        userAccount.ValidPreAmount += items.UseAmount;//退还可用额度
                    }
                    db.SaveChanges();
                }
            }
            AddSysLog("0", "PreCardAmountRecord", "Import");
            return "success";
        }
        #endregion

    }
}
