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

namespace MySystem
{
    public class OrderRefundService
    {
        public readonly static OrderRefundService Instance = new OrderRefundService();
        private OrderRefundService()
        { }

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

        public void dosomething()
        {
            while (true)
            {
                string data = RedisDbconn.Instance.RPop<string>("RefundQueue");
                if (!string.IsNullOrEmpty(data))
                {
                    try
                    {
                        JsonData jsonOj = JsonMapper.ToObject(data);
                        int OrderId = int.Parse(function.CheckInt(jsonOj["OrderId"].ToString()));
                        string Operator = jsonOj["Operator"].ToString();
                        decimal Amount = decimal.Parse(function.CheckNum(jsonOj["Amount"].ToString()));
                        string Remark = jsonOj["Remark"].ToString();
                        WebCMSEntities db = new WebCMSEntities();
                        Orders order = db.Orders.FirstOrDefault(m => m.Id == OrderId);
                        if(order != null)
                        {
                            bool op = true;
                            decimal TotalPrice = order.TotalPrice;
                            if(order.PayMode == 1)
                            {
                                PublicAccountSet set = db.PublicAccountSet.FirstOrDefault() ?? new PublicAccountSet();
                                string result = new Alipay.AlipayPublicMethod().Refund(set.AlipayAppId, set.AlipayPrivateKey, set.AlipayPublicKey, order.OrderNo, Amount);
                            }
                            else if(order.PayMode == 3)
                            {
                                UserAccount user = db.UserAccount.FirstOrDefault(m => m.Id == order.UserId);
                                if (user == null)
                                {
                                    user = db.UserAccount.Add(new UserAccount()
                                    {
                                        Id = order.UserId,
                                        UserId = order.UserId,
                                    }).Entity;
                                    db.SaveChanges();
                                }
                                decimal BeforeTotalAmount = user.TotalAmount; //变更前总金额
                                decimal BeforeFreezeAmount = user.FreezeAmount; //变更前冻结金额
                                decimal BeforeBalanceAmount = user.BalanceAmount; //变更前余额
                                user.BalanceAmount += Amount;
                                decimal AfterTotalAmount = user.TotalAmount; //变更后总金额
                                decimal AfterFreezeAmount = user.FreezeAmount; //变更后冻结金额
                                decimal AfterBalanceAmount = user.BalanceAmount; //变更后余额
                                db.UserAccountRecord.Add(new UserAccountRecord()
                                {
                                    CreateDate = DateTime.Now,
                                    UpdateDate = DateTime.Now,
                                    UserId = order.UserId, //创客
                                    ChangeType = 21, //变动类型
                                    ChangeAmount = Amount, //变更金额
                                    BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                                    AfterTotalAmount = AfterTotalAmount, //变更后总金额
                                    BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                                    AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                                    BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                                    AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                                    QueryCount = order.Id,
                                    Remark = Remark,
                                });
                            }
                            if(op)
                            {
                                order.RefundStatus = 1;
                                order.RefundActAmount = Amount;
                                db.OrderRefund.Add(new OrderRefund()
                                {
                                    CreateDate = DateTime.Now,
                                    Mobile = order.Mobile,
                                    Amount = Amount,
                                    SeoDescription = Remark,
                                    ProductId = order.ProductId.ToString(),
                                    OrderId = order.Id,
                                    UserId = order.UserId,
                                });
                            }
                            else
                            {
                                order.RefundStatus = 0;
                                order.RefundReason = null;
                                order.RefundActAmount = 0;
                            }
                            db.SaveChanges();
                        }
                        db.Dispose();
                    }
                    catch (Exception ex)
                    {                        
                        function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "订单退款异常");
                    }
                }
                else
                {
                    Thread.Sleep(60000);
                }
            }
        }
    }
}