using DbCommon.BusinessCore.DbCore;
using DbCommon.Enties.DbModels;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DbCommon.BusinessCore.BaseCore
{
    public class CallTaskManager : DbContext<CallTask>
    {

        public void Init()
        {
            //If no exist create datebase 
            //Db.DbMaintenance.CreateDatabase();

            //var dt = Db.Ado.GetDataTable("SELECT * FROM sysobjects WHERE NAME = 'CallTask'");
            if (!Db.DbMaintenance.IsAnyTable("CallTask", false))
            {
                //Create tables
                Db.CodeFirst.InitTables(typeof(CallTask));
            }
        }

        public bool DeleteOldData(int day = 1)
        {
            return CurrentDb.Delete(d => d.CallTime < DateTime.Now.AddDays(day * -1));
        }

        public List<CallTask> Query()
        {
            return Db.Queryable<CallTask>()
                .Where(d => (d.TaskStatus == EnumTaskStatus.叫料 || d.TaskStatus == EnumTaskStatus.任务创建 || d.TaskStatus == EnumTaskStatus.任务手动删除))
                .OrderBy(d => d.Priority, SqlSugar.OrderByType.Desc)
                .OrderBy(d => d.CallTime, SqlSugar.OrderByType.Asc)
                .Take(100)
                .ToList();
        }

        public List<CallTask> Query(System.Linq.Expressions.Expression<Func<CallTask, bool>> expression)
        {
            return Db.Queryable<CallTask>()
                .Where(expression)
                .OrderBy(d => d.CallTime, SqlSugar.OrderByType.Asc)
                .ToList();
        }

        public DataTable QueryDataTable()
        {
            return Db.Queryable<CallTask>()
                .Where(d => d.TaskStatus < EnumTaskStatus.叫料)
                .OrderBy(d => d.CallTime, SqlSugar.OrderByType.Desc)
                .ToDataTable();
        }
    }
}
