using DTO;
using HKCardOUT.Helper;
using HKCardOUT.Logic;
using HKCardOUT.Logic.Model;
using Quartz;
using S7.Net.Types;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using XExten.Advance.LinqFramework;

namespace HKCardOUT.QuartzUtil.Job
{
    public class QuartzJob : IJob
    {
        public async Task Execute(IJobExecutionContext context)
        {
            switch (context.JobDetail.Key.Group)
            {
                default:
                    {
                        var WaitSync = DbContext.Context.Queryable<SaleLog>().Where(t => t.IsSync == false).ToList();
                        List<SaleDto> dto = new List<SaleDto>();
                        if (WaitSync.Count > 0)
                        {
                            HKLog.HKLogImport.WriteInfo($"订单推送执行,推送数量{WaitSync.Count},推送的卡号：【{string.Join(",", WaitSync.Select(t => t.CardNo))}】");

                            foreach (var input in WaitSync)
                            {

                                var GateId = DataBus.StoreInfo.Devices.FirstOrDefault(t => t.Address.AsInt() == input.Location.AsInt())?.GateId;

                                dto.Add(new SaleDto
                                {
                                    CardNum = input.CardNo,
                                    GateId = GateId,
                                    Id= input.Id,
                                    CreateAt=input.CreateTime
                                });
                            }
                            var db = DbContext.Context;
                            try
                            {
                                db.BeginTran();
                                var res = RemoteService.SyncSaleLogList(dto);
                                if (res)
                                {
                                    var ids = WaitSync.Select(t => t.Id).ToList();
                                    await DbContext.Context.Updateable<SaleLog>().SetColumns(t => t.IsSync == true).Where(t => ids.Contains(t.Id)).ExecuteCommandAsync();
                                    db.CommitTran();
                                }
                            }
                            catch (Exception)
                            {
                                db.RollbackTran();
                            }
                          
                        }
                    }
                    break;
            }
        }
    }
}
