using HandyControl.Controls;
using HKCardOUT.Logic.Model;
using HKControl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XExten.Advance.LinqFramework;

namespace HKCardOUT.Logic.Service
{
    public class HKCore
    {
        /// <summary>
        /// 刷卡消费
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public bool DeviceSale(SaleLog input)
        {
            if (RemoteService.CheckCardStuatas(input.CardNo) != 1) return false;
            if (!Main.GetInstance.GetIsSwipe(input.Location.AsInt())) return false;
            var Old = DbContext.Context.Queryable<SaleLog>()
                  .Where(t => t.CardNo == input.CardNo).OrderByDescending(t => t.CreateTime).First();
            if (Old != null)
            {
                //10秒防止重复刷卡
                if (Old.CreateTime.Subtract(DateTime.Now).TotalSeconds > 10d)
                {
                    var entity = DbContext.Context.Insertable(input).CallEntityMethod(t => t.Create()).ExecuteReturnEntity();
                    if (entity.Id!=Guid.Empty)
                    {
                        var res = RemoteService.SyncSaleLog(input.CardNo, input.Location);
                        Main.GetInstance.Start(input.Location.AsInt());
                        DbContext.Context.Updateable<SaleLog>().SetColumns(t => t.IsSync == true).Where(t => t.Id == entity.Id).ExecuteCommand();
                        return res;
                    }
                }
                return false;
            }
            else
            {
                var entity = DbContext.Context.Insertable(input).CallEntityMethod(t => t.Create()).ExecuteReturnEntity();
                if (entity.Id!=Guid.Empty)
                {
                    var res = RemoteService.SyncSaleLog(input.CardNo, input.Location);
                    Main.GetInstance.Start(input.Location.AsInt());
                    DbContext.Context.Updateable<SaleLog>().SetColumns(t => t.IsSync == true).Where(t => t.Id == entity.Id).ExecuteCommand();
                    return res;
                }
                return false;
            }
        }
        /// <summary>
        /// 获取当天消费前100条展示
        /// </summary>
        /// <returns></returns>
        public List<SaleLog> PullDaySaleLog()
        {
            var Begin = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
            var End = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 23:59:59"));
            return DbContext.Context.Queryable<SaleLog>()
                   .Where(t => t.CreateTime >= Begin)
                   .Where(t => t.CreateTime < End)
                   .OrderByDescending(t => t.CreateTime).ToPageList(0, 100);
        }
    }
}
