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

namespace MySystem
{
    /// <summary>
    /// 分期扣款(每月20号执行)
    /// </summary>
    public class InstallmentDeductionService
    {
        public readonly static InstallmentDeductionService Instance = new InstallmentDeductionService();
        private InstallmentDeductionService()
        { }

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

        public void doSomething()
        {
            while (true)
            {
                if (DateTime.Now.Day <= 10 && DateTime.Now.Hour > 2 && DateTime.Now.Hour < 19)
                {
                    try
                    {
                        string check = function.ReadInstance("/InstallmentDeduction/check" + DateTime.Now.ToString("yyyy-MM-20") + ".txt");
                        if (string.IsNullOrEmpty(check))
                        {
                            function.WritePage("/InstallmentDeduction/", "check" + DateTime.Now.ToString("yyyy-MM-20") + ".txt", DateTime.Now.ToString("HH:mm:ss"));
                            WebCMSEntities db = new WebCMSEntities();
                            var startdate = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-20 00:00:00"));
                            var enddate = startdate.AddDays(1);
                            // var info = db.ToChargeBackRecordSub.Where(m => m.Status == 0 && m.StartDate >= startdate && m.StartDate < enddate).ToList();//分期扣款记录明细
                            var info = db.ToChargeByStage.Where(m => m.Status == 0).ToList();//分期扣款记录
                            foreach (var item in info)
                            {
                                var toChargeBackRecordSub = db.ToChargeBackRecordSub.FirstOrDefault(m => m.Status == 0 && m.ParentId == item.Id && m.StartDate >= startdate && m.StartDate < enddate) ?? new ToChargeBackRecordSub();
                                if (toChargeBackRecordSub.Id > 0)
                                {
                                    var userAccount = db.UserAccount.FirstOrDefault(m => m.Id == item.UserId);
                                    if (userAccount == null)
                                    {
                                        userAccount = db.UserAccount.Add(new UserAccount()
                                        {
                                            Id = item.UserId,
                                            UserId = item.UserId,
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    toChargeBackRecordSub.Status = 2;
                                    if (toChargeBackRecordSub.Kind == 0) userAccount.ToChargeAmount += toChargeBackRecordSub.ChargeAmount;//增加创客预扣款
                                    if (toChargeBackRecordSub.Kind == 1) userAccount.LeaderToChargeAmount += toChargeBackRecordSub.ChargeAmount;//增加盟主预扣款
                                    if (toChargeBackRecordSub.Kind == 2) userAccount.OperateToChargeAmount += toChargeBackRecordSub.ChargeAmount;//增加运营中心预扣款
                                    var toChargeBackRecord = db.ToChargeBackRecord.Add(new ToChargeBackRecord
                                    {
                                        CreateDate = DateTime.Now,
                                        Sort = toChargeBackRecordSub.Id,
                                        UserId = item.UserId,
                                        ChargeAmount = toChargeBackRecordSub.ChargeAmount,
                                        ChargeType = 2,//分期预扣款
                                        Remark = toChargeBackRecordSub.Remark,
                                        Kind = toChargeBackRecordSub.Kind,

                                    }).Entity;
                                }

                                // //只能存在一笔分期扣款记录(先前有的但是余额不够未扣除的则不添加新的)
                                // var checks = db.ToChargeBackRecord.Any(m => m.Sort > 0 && (m.Status == 0 || m.Status == 3) && m.ChargeType == 2 && m.UserId == item.UserId);
                                // if (!checks)
                                // {
                                //     string checkAdd = RedisDbconn.Instance.Get<string>("InstallmentDeductionAddRecord:" + item.UserId);
                                //     if (string.IsNullOrEmpty(check))
                                //     {
                                //         var toChargeBackRecordSub = db.ToChargeBackRecordSub.FirstOrDefault(m => m.Status == 0 && m.ParentId == item.Id && m.StartDate >= startdate && m.StartDate < enddate) ?? new ToChargeBackRecordSub();
                                //         if (toChargeBackRecordSub.Id > 0)
                                //         {
                                //             var userAccount = db.UserAccount.FirstOrDefault(m => m.Id == item.UserId);
                                //             if (userAccount == null)
                                //             {
                                //                 userAccount = db.UserAccount.Add(new UserAccount()
                                //                 {
                                //                     Id = item.UserId,
                                //                     UserId = item.UserId,
                                //                 }).Entity;
                                //                 db.SaveChanges();
                                //             }
                                //             userAccount.ToChargeAmount += toChargeBackRecordSub.ChargeAmount;//增加预扣款
                                //             var toChargeBackRecord = db.ToChargeBackRecord.Add(new ToChargeBackRecord
                                //             {
                                //                 CreateDate = DateTime.Now,
                                //                 Sort = toChargeBackRecordSub.Id,
                                //                 UserId = item.UserId,
                                //                 ChargeAmount = toChargeBackRecordSub.ChargeAmount,
                                //                 ChargeType = 2,//分期预扣款
                                //                 Remark = "分期预扣款",

                                //             }).Entity;
                                //         }
                                //     }
                                //     RedisDbconn.Instance.Set("InstallmentDeductionAddRecord:" + item.UserId, "wait");
                                //     RedisDbconn.Instance.SetExpire("InstallmentDeductionAddRecord:" + item.UserId, 300);
                                // }
                            }
                            db.SaveChanges();

                        }
                    }
                    catch (Exception ex)
                    {
                        function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "执行分期扣费异常");
                    }
                }
                Thread.Sleep(10000);
            }
        }
    }
}