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();
            }

        }

        /// <summary>
        /// 长度10 任务编号 PLC限制
        /// </summary>
        /// <param name="trigerType"></param>
        /// <returns></returns>
        public string CrateTaskNumber(TaskTrigerType trigerType)
        {
            var date = DateTime.Now;
            var serinum = date.DayOfYear+date.Month +date.Day+ date.Hour + date.Minute + date.Second + date.Millisecond;
            var dayofyear = GetDayOfYear(date);
            if (trigerType== TaskTrigerType.Auto)
            {
                return $"A{date.Year}{dayofyear}{serinum}";
            }
            else
            {
                return $"M{date.Year}{dayofyear}{serinum}";
            }
        }
        /// <summary>
        /// 工件长度10 PLC 限制
        /// </summary>
        /// <param name="productCode"></param>
        /// <returns></returns>
        public string CreateRandonSn(string productCode)
        {
            var date = DateTime.Now;
            var serinum = date.DayOfYear + date.Month + date.Day + date.Hour + date.Minute + date.Second + date.Millisecond;
            var dayofyear = GetDayOfYear(date);
            var lable = $"{date.Year}{dayofyear}{serinum}";
            return lable;
        }
        private string GetDayOfYear(DateTime dt)
        {
            var lable = dt.DayOfYear.ToString();
            var result = string.Empty;
            for (int i = 0;i< 3- lable.Length;i++)
            {
                 result +="0";
            }
            return $"{result}{lable}";


        }

        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 (!string.IsNullOrEmpty(comptime))
            {
                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);
        }
    }
}
