using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using MySystem.Models.Main;
using Library;
using System.Threading;
using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;
using LitJson;

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

        public void Start()
        {
            Thread th = new Thread(StartDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StartDo()
        {
            while (true)
            {
                DoSomeThing();
                Thread.Sleep(2000);
            }
        }

        public void DoSomeThing()
        { 
            try
            {
                WebCMSEntities db = new WebCMSEntities();
                DateTime starDate = DateTime.Parse("2025-01-01 00:00:00");
                DateTime checkDate = DateTime.Now.AddMinutes(-10);
                var orders = db.ConsumerOrders.Select(m => new { m.Id, m.Status, m.IsAct, m.UpdateDate, m.SettleAmount }).Where(m => m.Status > 0 && m.IsAct == 1 && m.UpdateDate >= starDate && m.UpdateDate < checkDate && m.SettleAmount == 0).ToList();
                foreach(var sub in orders)
                {
                    ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == sub.Id);
                    if (order != null)
                    {
                        MerchantAddInfo add = db.MerchantAddInfo.FirstOrDefault(m => m.Id == order.MerchantId) ?? new MerchantAddInfo();
                        // string text = function.GetWebRequest(Library.ConfigurationManager.AppSettings["SpHost"].ToString() + "/Api/PublicMethod/GetSettleOrderAmount?orderNo=" + order.SeoTitle + "&date=" + order.CreateDate.Value.ToString("yyyy-M-d"));
                        string result = HaoDaHelper.Instance.QueryOrderDivideDetail(add.OutMchtNo, order.SeoTitle, add.BrandId);
                        JsonData jsonObj = JsonMapper.ToObject(result);
                        if(jsonObj["resultCode"].ToString() == "1" && result.Contains("\"settleAmount\""))
                        {
                            order.SettleAmount = int.Parse(function.CheckInt(jsonObj["data"]["settleAmount"].ToString()));
                            db.SaveChanges();
                        }
                    }
                }
                db.Dispose();
            }
            catch(Exception ex)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "检查未结算分账订单异常");
            }
        }
    }
}