using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using Siger.Middlelayer.AccRepository.Entities;
using Siger.Middlelayer.AccRepository.Repositories.Interface;
using Siger.Middlelayer.AccRepository.Response;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Repository.Data.Acc;
using Siger.Middlelayer.Repository.Extensions;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.Share.Enum.ModuleEnum;
using static Siger.Middlelayer.Share.Enum.ModuleEnum.Automation;

namespace Siger.Middlelayer.AccRepository.Repositories
{
    internal class AutomationTaskListRepository : AccRepositoryBase<siger_automation_task_list>, IAutomationTaskListRepository
    {
        private ApiAccDbContext _context;
        public AutomationTaskListRepository(ApiAccDbContext context) : base(context)
        {
            _context = context;
        }

        public bool CanTask(int projectId,int section)
        {
            //已经下发，并且任务完成
            var taskObjs = _context.siger_automation_task_list.Where(f => f.projectId == projectId && f.send==0);

            if (taskObjs.Any())
                return false;
            else
            {
                var complatedData = taskObjs.Where(f => f.status < (int)TaskResultStatus.Complated);
               
                return !complatedData.Any();
            }

        }

        public string CrateTaskNumber(TaskTrigerType trigerType)
        {
            var date = DateTime.Now;
            var lable = date.ToString(UnixTimeHelper.DateTimeFormatYmd)+date.Hour + date.Minute + date.Second;
            var lableUnix = UnixTimeHelper.GetNow();
            var radon = new Random().Next(1000, 9999);
            if (trigerType== TaskTrigerType.Auto)
            {
                return $"A{lableUnix}R{radon}T{lable}";
            }else
            {
                return $"M{lableUnix}R{radon}T{lable}";
            }
        }

        public string CreateRandonSn(string productCode)
        {
            var date = DateTime.Now;
            var serinum = date.DayOfYear+date.Hour + date.Minute + date.Second + date.Millisecond;

            var randon = new Random().Next(1000, 9999);
            return $"{productCode}{date.ToString(UnixTimeHelper.DateTimeFormatYmd)}{serinum}{randon}";
        }

        public IPagedCollectionResult<ResponseAutomationTasklist> GetTasklistPagedList(List<int> sections, int taskType, string productCode, string TaskNo, string sn, int status, int actionType, string tiggertime, string comptime, int projectid, int page, int pagesize)
        {
            var query = from q in _context.siger_automation_task_list 
                        join t in _context.siger_automation_fixture_tools on q.fixtureguid equals t.guid
                        join s in _context.siger_project_level_section on q.sectionid equals s.id
                        join lv in _context.siger_project_level_section on s.parentid equals lv.id
                        where q.projectId == projectid
                        select new ResponseAutomationTasklist
                        {
                             id=q.id,
                             taskno=q.no,
                             sectionid= q.sectionid,
                             section=$"{lv.title}-{s.title}",
                             trigger =EnumHelper.GetEnumDesc(q.trigger),
                             triggervalue=q.triggertime,
                             triggerTime=q.triggertime==DateTime.MinValue?"":q.triggertime.ToString(),
                             complatevalue=q.completetime,
                             complatetime=q.completetime==DateTime.MinValue?"":q.completetime.ToString(),
                             action=EnumHelper.GetEnumDesc(q.action),
                             actionType=EnumHelper.GetEnumDesc(q.actiontype),
                             fixtureCode=t.code,
                             fixtureName=t.name,
                             location=q.locationid.ToString(),
                             sn=q.sn,
                             ordernumber=q.ordercode,
                             productCode=q.productcode,
                             program=q.programnumber,
                             route=q.remark,
                             tasktype=EnumHelper.GetEnumDesc(q.tasktype),
                             status=q.status,
                             
                        };
            Expression<Func<ResponseAutomationTasklist, bool>> sectonsExpression = f => true;
            if (sections.Any())
            {
                sectonsExpression = q =>sections.Contains( q.sectionid );
            }
            Expression<Func<ResponseAutomationTasklist, bool>> taskTypeExpression = f => true;
            if (taskType != 0 )
            {
                taskTypeExpression = q => q.tasktypeid == taskType;
            }
            Expression<Func<ResponseAutomationTasklist, bool>> productCodeExpression = f => true;
            if (!string.IsNullOrEmpty(productCode))
            {
                productCodeExpression = q => q.productCode.Contains(productCode);
            }
            Expression<Func<ResponseAutomationTasklist, bool>> tasknoExpression = f => true;
            if (!string.IsNullOrEmpty(TaskNo))
            {
                tasknoExpression = q => q.taskno.Contains(TaskNo);
            }
            Expression<Func<ResponseAutomationTasklist, bool>> snExpression = f => true;
            if (!string.IsNullOrEmpty(sn))
            {
                snExpression = q => q.sn.Contains(sn);
            }
            Expression<Func<ResponseAutomationTasklist, bool>> actionTypeExpression = f => true;
            if (actionType!=0)
            {
                actionTypeExpression = q => q.actionTypeid==actionType;
            }
            Expression<Func<ResponseAutomationTasklist, bool>> triggerTimeTypeExpression = f => true;
            if (string.IsNullOrEmpty(tiggertime))
            {
                
                triggerTimeTypeExpression = q => q.triggervalue == tiggertime.ToDateTime();
            }
            Expression<Func<ResponseAutomationTasklist, bool>> comptimeExpression = f => true;
            if (actionType != 0)
            {
                comptimeExpression = q => q.complatevalue == comptime.ToDateTime();
            }

            var expression = sectonsExpression.And(taskTypeExpression).And(productCodeExpression).And(tasknoExpression).And(snExpression)
                .And(actionTypeExpression).And(triggerTimeTypeExpression).And(comptimeExpression);


            var entities = query.Where(expression).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();
            var totalCount = query.Where(expression).Count();
            return new PagedCollectionResult<ResponseAutomationTasklist>(entities, totalCount);
        }
    }
}
