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

public class PreStoreApplyHelper
{
    public readonly static PreStoreApplyHelper Instance = new PreStoreApplyHelper();
    private PreStoreApplyHelper()
    {
    }

    public void StartEverTime()
    {
        Thread th = new Thread(StartEverTimeDo);
        th.IsBackground = true;
        th.Start();
    }

    private void StartEverTimeDo()
    {
        while (true)
        {
            WebCMSEntities db = new WebCMSEntities();
            try
            {
                string data = RedisDbconn.Instance.RPop<string>("PreStoreApplyQueue");
                if (!string.IsNullOrEmpty(data))
                {
                    function.WriteLog("data:" + data, "创客预发额度变动日志");
                    JsonData jsonObj = JsonMapper.ToObject(data);
                    if (jsonObj["Kind"].ToString() == "1") // 购买创客预发临时额度
                    {
                        int OrderId = int.Parse(jsonObj["Data"]["OrderId"].ToString());
                        Orders order = db.Orders.FirstOrDefault(m => m.Id == OrderId);
                        if (order != null)
                        {
                            decimal TotalPrice = order.TotalPrice;
                            AddAmount2(db, 1, order.UserId, TotalPrice, order.PayMode, 1, order.Id);
                        }
                    }
                    else if (jsonObj["Kind"].ToString() == "2") // 增减创客预发临时额度
                    {
                        int UserId = int.Parse(jsonObj["Data"]["UserId"].ToString());
                        decimal Amount = decimal.Parse(jsonObj["Data"]["Amount"].ToString());
                        int OperateType = int.Parse(jsonObj["Data"]["OperateType"].ToString());
                        AddAmount(db, 2, UserId, Amount, OperateType);
                    }
                    else if (jsonObj["Kind"].ToString() == "3") // 调低创客预发额度返回余额
                    {
                        int UserId = int.Parse(jsonObj["Data"]["UserId"].ToString());
                        decimal Amount = decimal.Parse(jsonObj["Data"]["Amount"].ToString());
                        int PayMode = int.Parse(jsonObj["Data"]["PayMode"].ToString());
                        AddAmount2(db, 3, UserId, Amount, PayMode, 0);
                        if (PayMode != 1)
                        {
                            decimal BalanceAmount = Amount;
                            UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == UserId);
                            if (account == null)
                            {
                                account = db.UserAccount.Add(new UserAccount()
                                {
                                    Id = UserId,
                                    UserId = UserId,
                                }).Entity;
                                db.SaveChanges();
                            }
                            decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                            decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                            decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                            account.BalanceAmount += BalanceAmount;
                            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 = UserId, //创客
                                ChangeType = 130, //变动类型
                                ChangeAmount = BalanceAmount, //变更金额
                                BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                                AfterTotalAmount = AfterTotalAmount, //变更后总金额
                                BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                                AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                                BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                                AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                            }).Entity;
                        }
                    }
                    db.SaveChanges();
                }
                else
                {
                    Thread.Sleep(5000);
                }
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "创客预发临时额度变动线程异常");
            }
            db.Dispose();
        }
    }

    public void AddAmount(WebCMSEntities db, int Kind, int UserId, decimal Amount, int OperateType = 1, int OrderId = 0)
    {
        UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == UserId);
        if (account == null)
        {
            account = db.UserAccount.Add(new UserAccount()
            {
                Id = UserId,
                UserId = UserId,
            }).Entity;
            db.SaveChanges();
        }
        decimal BeforeTotalAmount = account.ValidPreAmount; //变更前总金额
        if (OperateType == 1)
        {
            account.ValidPreAmount += Amount;
        }
        else
        {
            account.ValidPreAmount -= Amount;
        }
        decimal AfterTotalAmount = account.ValidPreAmount; //变更后总金额
        PreAmountRecord preAmountRecord = db.PreAmountRecord.Add(new PreAmountRecord()
        {
            CreateDate = DateTime.Now,
            UpdateDate = DateTime.Now,
            OperateType = OperateType,
            AfterAmount = AfterTotalAmount,
            BeforeAmount = BeforeTotalAmount,
            UseAmount = Amount,
            UserId = UserId,
            QueryCount = OrderId,
            Sort = Kind,
        }).Entity;
        db.SaveChanges();
    }

    public void AddAmount2(WebCMSEntities db, int Kind, int UserId, decimal Amount, int PayMode, int OperateType = 1, int OrderId = 0)
    {
        UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == UserId);
        if (account == null)
        {
            account = db.UserAccount.Add(new UserAccount()
            {
                Id = UserId,
                UserId = UserId,
            }).Entity;
            db.SaveChanges();
        }
        decimal BeforeTotalAmount = account.ValidPreAmount; //变更前总金额

        if (OperateType == 1)
        {
            if (PayMode == 3)//余额
            {
                account.PreTempAmountForBalance += Amount;
            }
            else
            {
                account.PreTempAmount += Amount;
            }
            account.ValidPreAmount += Amount;
        }
        else
        {
            if (PayMode == 3)
            {
                account.PreTempAmountForBalance -= Amount;
            }
            else
            {
                account.PreTempAmount -= Amount;
            }
            account.ValidPreAmount -= Amount;
        }
        decimal AfterTotalAmount = account.ValidPreAmount; //变更后总金额
        PreAmountRecord preAmountRecord = db.PreAmountRecord.Add(new PreAmountRecord()
        {
            CreateDate = DateTime.Now,
            UpdateDate = DateTime.Now,
            OperateType = OperateType,
            AmountType = PayMode,
            AfterAmount = AfterTotalAmount,
            BeforeAmount = BeforeTotalAmount,
            UseAmount = Amount,
            UserId = UserId,
            QueryCount = OrderId,
            Sort = Kind,
            PayMode = PayMode,
        }).Entity;
        db.SaveChanges();
    }
}