using System;
using System.Threading;
using System.Linq;
using System.Data;
using Library;
using MySystem.Models;
using System.Collections.Generic;

/// <summary>
/// 创客信息相关数据导入
/// </summary>
namespace MySystem
{
    public class BatchEditUserAmountService
    {
        public readonly static BatchEditUserAmountService Instance = new BatchEditUserAmountService();
        private BatchEditUserAmountService()
        {
        }

        public void Start()//启动
        {
            Thread thread = new Thread(ImportPostDo);
            thread.IsBackground = true;
            thread.Start();
        }

        public void ImportPostDo()
        {
            while (true)
            {
                try
                {
                    string data = RedisDbconn.Instance.RPop<string>("BatchEditUserAmountQueue");
                    if (!string.IsNullOrEmpty(data))
                    {
                        string[] dataList = data.Split("#cut#");
                        string _ExcelPath = dataList[0];
                        string _Kind = dataList[1];
                        string checkKey = dataList[2];
                        string Operator = dataList[3]; // 操作人
                        int SuccessCount = 0;
                        int DoCount = 0;
                        string FullExcelPath = function.getPath(_ExcelPath);
                        FullExcelPath = FullExcelPath.Replace("//", "/");
                        DataTable list = new PublicFunction().ExcelToDataTable(FullExcelPath);
                        int TotalCount = list.Rows.Count;
                        while (DoCount < list.Rows.Count)
                        {
                            WebCMSEntities db = new WebCMSEntities();
                            //导入结算金额
                            if (_Kind == "1")
                            {
                                var tran = db.Database.BeginTransaction();
                                try
                                {
                                    int Size = 100;
                                    if (list.Rows.Count - DoCount < 100)
                                    {
                                        Size = list.Rows.Count - DoCount;
                                    }
                                    Dictionary<string, int> storeData = new Dictionary<string, int>();
                                    for (int i = DoCount; i < DoCount + Size; i++)
                                    {
                                        DataRow dr = list.Rows[i];
                                        string MakerCode = dr[0].ToString(); //创客编号
                                        string RealName = dr[1].ToString(); //创客姓名
                                        string SettleAmount = dr[2].ToString(); //提现结算金额(元)
                                        UserForMakerCode UserCode = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode);
                                        if (UserCode.UserId > 0)
                                        {
                                            var user = db.Users.FirstOrDefault(m => m.Id == UserCode.UserId) ?? new Users();
                                            if (user.Id > 0)
                                            {
                                                SuccessCount += 1;
                                                user.SettleAmount = decimal.Parse(function.CheckInt(SettleAmount));
                                            }
                                            else
                                            {
                                                RedisDbconn.Instance.AddList("ErrList" + checkKey, "未找到" + MakerCode + " " + RealName + "创客信息");
                                            }
                                        }
                                        else
                                        {
                                            RedisDbconn.Instance.AddList("ErrList" + checkKey, "未找到" + MakerCode + "编号关联信息");
                                        }
                                    }
                                    DoCount += Size;
                                    db.SaveChanges();
                                    tran.Commit();
                                    if (DoCount >= list.Rows.Count)
                                    {
                                        RedisDbconn.Instance.Set("BatchEditUserAmountCheckImport:" + checkKey, "success|" + SuccessCount);
                                        RedisDbconn.Instance.SetExpire("BatchEditUserAmountCheckImport:" + checkKey, 60000);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    DoCount = list.Rows.Count;
                                    function.WriteLog(ex.ToString(), "导入结算金额");
                                    tran.Rollback();
                                    ErrorMsg msg = new ErrorMsg()
                                    {
                                        Time = DateTime.Now,
                                        ErrorContent = ex.ToString(),
                                    };
                                    function.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(msg), "导入结算金额Excel文件异常");
                                }
                                tran.Dispose();
                            }
                            //导入冻结金额
                            if (_Kind == "2")
                            {
                                var tran = db.Database.BeginTransaction();
                                try
                                {
                                    int Size = 100;
                                    if (list.Rows.Count - DoCount < 100)
                                    {
                                        Size = list.Rows.Count - DoCount;
                                    }
                                    Dictionary<string, int> storeData = new Dictionary<string, int>();
                                    for (int i = DoCount; i < DoCount + Size; i++)
                                    {
                                        DataRow dr = list.Rows[i];
                                        string MakerCode = dr[0].ToString(); //创客编号
                                        string RealName = dr[1].ToString(); //创客姓名
                                        string CashFreezeAmt = dr[2].ToString(); //提现结算金额(元)
                                        UserForMakerCode UserCode = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode);
                                        if (UserCode.UserId > 0)
                                        {
                                            var user = db.Users.FirstOrDefault(m => m.Id == UserCode.UserId) ?? new Users();
                                            if (user.Id > 0)
                                            {
                                                SuccessCount += 1;
                                                user.CashFreezeAmt = decimal.Parse(function.CheckInt(CashFreezeAmt));
                                            }
                                            else
                                            {
                                                RedisDbconn.Instance.AddList("ErrList" + checkKey, "未找到" + MakerCode + " " + RealName + "创客信息");
                                            }
                                        }
                                        else
                                        {
                                            RedisDbconn.Instance.AddList("ErrList" + checkKey, "未找到" + MakerCode + "编号关联信息");
                                        }
                                    }
                                    DoCount += Size;
                                    db.SaveChanges();
                                    tran.Commit();
                                    if (DoCount >= list.Rows.Count)
                                    {
                                        RedisDbconn.Instance.Set("BatchEditUserAmountCheckImport:" + checkKey, "success|" + SuccessCount);
                                        RedisDbconn.Instance.SetExpire("BatchEditUserAmountCheckImport:" + checkKey, 60000);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    DoCount = list.Rows.Count;
                                    function.WriteLog(ex.ToString(), "导入冻结金额");
                                    tran.Rollback();
                                    ErrorMsg msg = new ErrorMsg()
                                    {
                                        Time = DateTime.Now,
                                        ErrorContent = ex.ToString(),
                                    };
                                    function.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(msg), "导入冻结金额Excel文件异常");
                                }
                                tran.Dispose();
                            }
                            //导入风控数据
                            if (_Kind == "3")
                            {
                                var tran = db.Database.BeginTransaction();
                                try
                                {
                                    int Size = 100;
                                    if (list.Rows.Count - DoCount < 100)
                                    {
                                        Size = list.Rows.Count - DoCount;
                                    }
                                    Dictionary<string, int> storeData = new Dictionary<string, int>();
                                    for (int i = DoCount; i < DoCount + Size; i++)
                                    {
                                        DataRow dr = list.Rows[i];
                                        string MakerCode = dr[0].ToString(); //创客编号
                                        string RealName = dr[1].ToString(); //创客姓名
                                        string RiskFlag = dr[2].ToString(); //风控标记(0 否 1 是)
                                        string RiskNote = dr[3].ToString(); //风控备注
                                        UserForMakerCode UserCode = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode);
                                        if (UserCode.UserId > 0)
                                        {
                                            var user = db.Users.FirstOrDefault(m => m.Id == UserCode.UserId && m.RealName == RealName) ?? new Users();
                                            if (user.Id > 0)
                                            {
                                                SuccessCount += 1;
                                                user.RiskFlag = ulong.Parse(function.CheckInt(RiskFlag));
                                                user.RiskRemark = RiskNote;
                                            }
                                            else
                                            {
                                                RedisDbconn.Instance.AddList("ErrList" + checkKey, "未找到" + MakerCode + " " + RealName + "创客信息");
                                            }
                                        }
                                        else
                                        {
                                            RedisDbconn.Instance.AddList("ErrList" + checkKey, "未找到" + MakerCode + "编号关联信息");
                                        }
                                    }
                                    DoCount += Size;
                                    db.SaveChanges();
                                    tran.Commit();
                                    if (DoCount >= list.Rows.Count)
                                    {
                                        RedisDbconn.Instance.Set("BatchEditUserAmountCheckImport:" + checkKey, "success|" + SuccessCount);
                                        RedisDbconn.Instance.SetExpire("BatchEditUserAmountCheckImport:" + checkKey, 60000);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    DoCount = list.Rows.Count;
                                    function.WriteLog(ex.ToString(), "导入风控数据");
                                    tran.Rollback();
                                    ErrorMsg msg = new ErrorMsg()
                                    {
                                        Time = DateTime.Now,
                                        ErrorContent = ex.ToString(),
                                    };
                                    function.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(msg), "导入风控数据Excel文件异常");
                                }
                                tran.Dispose();
                            }
                            //批量修改账户金额
                            if (_Kind == "4")
                            {
                                var tran = db.Database.BeginTransaction();
                                try
                                {
                                    int Size = 100;
                                    if (list.Rows.Count - DoCount < 100)
                                    {
                                        Size = list.Rows.Count - DoCount;
                                    }
                                    Dictionary<string, int> storeData = new Dictionary<string, int>();
                                    for (int i = DoCount; i < DoCount + Size; i++)
                                    {
                                        DataRow dr = list.Rows[i];
                                        string MakerCode = dr[0].ToString(); //创客编号
                                        string RealName = dr[1].ToString(); //创客姓名
                                        string OperationAmt = dr[2].ToString();//操作金额
                                        string OperationType = dr[3].ToString();//操作类型(1-冻结 2-解冻 3-扣减 4-增加)
                                        UserForMakerCode UserCode = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode);
                                        if (UserCode.UserId > 0)
                                        {
                                            var user = db.Users.FirstOrDefault(m => m.Id == UserCode.UserId && m.RealName == RealName) ?? new Users();
                                            if (user.Id > 0)
                                            {
                                                UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == user.Id) ?? new UserAccount();
                                                if (account.Id == 0)
                                                {
                                                    account = db.UserAccount.Add(new UserAccount()
                                                    {
                                                        Id = user.Id,
                                                        UserId = user.Id,
                                                    }).Entity;
                                                    db.SaveChanges();
                                                }
                                                if (account.Id > 0)
                                                {
                                                    decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                                                    decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                                                    decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                                                    int ChangeType = 0;
                                                    if (OperationType == "1" && Convert.ToDecimal(OperationAmt) > account.BalanceAmount)
                                                    {
                                                        RedisDbconn.Instance.AddList("ErrList" + checkKey, "以下操作失败" + user.MakerCode + ',' + user.RealName + "冻结金额大于余额");
                                                    }
                                                    if (OperationType == "2" && Convert.ToDecimal(OperationAmt) > account.FreezeAmount)
                                                    {
                                                        RedisDbconn.Instance.AddList("ErrList" + checkKey, "以下操作失败" + user.MakerCode + ',' + user.RealName + "解冻金额大于冻结金额");
                                                    }
                                                    if (OperationType == "3" && Convert.ToDecimal(OperationAmt) > account.BalanceAmount)
                                                    {
                                                        RedisDbconn.Instance.AddList("ErrList" + checkKey, "以下操作失败" + user.MakerCode + ',' + user.RealName + "扣减金额大于余额");
                                                    }
                                                    if ((OperationType == "1" && Convert.ToDecimal(OperationAmt) <= account.BalanceAmount) || (OperationType == "2" && Convert.ToDecimal(OperationAmt) <= account.FreezeAmount) || (OperationType == "3" && Convert.ToDecimal(OperationAmt) <= account.BalanceAmount) || (OperationType == "4"))
                                                    {
                                                        if (OperationType == "1" && Convert.ToDecimal(OperationAmt) <= account.BalanceAmount)
                                                        {
                                                            account.BalanceAmount -= Convert.ToDecimal(OperationAmt);
                                                            account.FreezeAmount += Convert.ToDecimal(OperationAmt);
                                                            ChangeType = 61;
                                                        }
                                                        if (OperationType == "2" && Convert.ToDecimal(OperationAmt) <= account.FreezeAmount)
                                                        {
                                                            account.BalanceAmount += Convert.ToDecimal(OperationAmt);
                                                            account.FreezeAmount -= Convert.ToDecimal(OperationAmt);
                                                            ChangeType = 62;
                                                        }
                                                        if (OperationType == "3" && Convert.ToDecimal(OperationAmt) <= account.BalanceAmount)
                                                        {
                                                            account.TotalAmount -= Convert.ToDecimal(OperationAmt);
                                                            account.BalanceAmount -= Convert.ToDecimal(OperationAmt);
                                                            ChangeType = 63;
                                                        }
                                                        if (OperationType == "4")
                                                        {
                                                            account.TotalAmount += Convert.ToDecimal(OperationAmt);
                                                            account.BalanceAmount += Convert.ToDecimal(OperationAmt);
                                                            ChangeType = 64;
                                                        }
                                                        decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                                                        decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                                                        decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
                                                        UserAccountRecord userAccountRecord = db.UserAccountRecord.Add(new UserAccountRecord()
                                                        {
                                                            CreateDate = DateTime.Now,
                                                            UpdateDate = DateTime.Now,
                                                            UserId = user.Id, //创客
                                                            ChangeType = ChangeType, //变动类型
                                                            ChangeAmount = Convert.ToDecimal(OperationAmt), //变更金额
                                                            BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                                                            AfterTotalAmount = AfterTotalAmount, //变更后总金额
                                                            BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                                                            AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                                                            BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                                                            AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                                                            Remark = dr[4].ToString(),
                                                        }).Entity;
                                                        db.SaveChanges();
                                                        SuccessCount += 1;
                                                        function.WriteLog(DateTime.Now.ToString() + "\n" + user.Id.ToString(), "批量修改账户金额");
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                RedisDbconn.Instance.AddList("ErrList" + checkKey, "未找到" + MakerCode + " " + RealName + "创客信息");
                                            }
                                        }
                                        else
                                        {
                                            RedisDbconn.Instance.AddList("ErrList" + checkKey, "未找到" + MakerCode + "编号关联信息");
                                        }
                                    }
                                    DoCount += Size;
                                    db.SaveChanges();
                                    tran.Commit();
                                    if (DoCount >= list.Rows.Count)
                                    {
                                        RedisDbconn.Instance.Set("BatchEditUserAmountCheckImport:" + checkKey, "success|" + SuccessCount);
                                        RedisDbconn.Instance.SetExpire("BatchEditUserAmountCheckImport:" + checkKey, 60000);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    DoCount = list.Rows.Count;
                                    function.WriteLog(ex.ToString(), "批量修改账户金额");
                                    tran.Rollback();
                                    ErrorMsg msg = new ErrorMsg()
                                    {
                                        Time = DateTime.Now,
                                        ErrorContent = ex.ToString(),
                                    };
                                    function.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(msg), "批量修改账户金额Excel文件异常");
                                }
                                tran.Dispose();
                            }
                        }
                    }
                    else
                    {
                        Thread.Sleep(5000);
                    }
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "后台导入Excel文件队列异常");
                }
            }
        }
    }
}