using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.DncRepository.Entities;
using Siger.Middlelayer.DncRepository.Repositories.Interface;
using Siger.Middlelayer.DncRepository.Response;

namespace Siger.Middlelayer.DncRepository.Repositories
{
    internal class SigerDncJobProgramRepository : DncJobRepositoryBase<siger_project_dnc_job_program>, ISigerDncJobProgramRepository
    {
        private readonly ApiDncDbContext _context;
        public SigerDncJobProgramRepository(ApiDncDbContext context) : base(context)
        {
            _context = context;
        }

        public ResponseChangeProgram GetChangeProram(int machineID, string ProgramCode, DateTime startTime,
            DateTime endTime, ChangeProgramType? typeObj, int projectId,int page = 1, int pagesize = 10)
        {
            Expression<Func<siger_project_dnc_job_program, bool>> program = f => true;
            if (!string.IsNullOrEmpty(ProgramCode))
            {
                program = w => w.program_number.Contains(ProgramCode);
            }
            Expression<Func<siger_project_dnc_job_program, bool>> type = f => true;
            if (typeObj != null)
            {
                type = w => w.type == typeObj.ToString().ToLower();
            }

            var lsColl = _context.siger_project_dnc_job_program.Where(w => w.machine_name == machineID.ToString() &&
                                                                           w.time > startTime &&
                                                                           w.time < endTime && w.projectid == projectId).OrderBy(o => o.time).ToList();

            lsColl = lsColl.AsQueryable().Where(program).Where(type).ToList();
            var total = lsColl.Count();
            var data = lsColl.Skip((page - 1) * pagesize).Take(pagesize).ToList();
            if (!data.Any())
            {
                return new ResponseChangeProgram();
            }
            var tempData = new List<ResponseDNCChangeProgram>();
            for (int i = 0; i < data.Count; i++)
            {
                //转换时间
                var newInfo = new ResponseDNCChangeProgram
                {
                    id = data[i].id,
                    id_old = data[i].id_old,
                    time = data[i].time.ToString("yyyy-MM-dd HH:mm:ss")
                };
                
                newInfo.machine_name = data[i].machine_name;
                newInfo.program_number = data[i].program_number;
                newInfo.document = data[i].document == null ? "" :Encoding.ASCII.GetString(data[i].document);
                newInfo.type = data[i].type;
                //update类型,查询其修改之前程序信息
                if (data[i].type.ToUpper() == ChangeProgramType.Update.ToString().ToUpper())
                {
                    var lastData = _context.siger_project_dnc_job_program.FirstOrDefault(f => f.id == data[i].id_old);
                    if (lastData != null)
                    {
                        newInfo.LastContext = lastData.document == null ? "": Encoding.ASCII.GetString(lastData.document);
                        newInfo.LastTime = lastData.time.ToString("yyyy-MM-dd HH:mm:ss");
                    }
                    else
                    {
                        newInfo.LastTime = "NA";
                    }
                }
                tempData.Add(newInfo);
            }

            var echartResult = new List<EchartData>();
            var _echart = data.GroupBy(g => g.time).Select(g => new { date = g.Key, dcount = g.Count() });

            foreach (var echar in _echart)
            {
                echartResult.Add(new EchartData { DateTime = (int)UnixTimeHelper.ConvertDataTimeLong(echar.date), Count = echar.dcount });
            }
            var result = new ResponseChangeProgram
            {
                ListDetails = tempData,
                Echarts = echartResult,
                TotalCount = total
            };
            return result;
        }

        public int GetChangeCount(List<int> machineids, DateTime starttime, DateTime endtime, int projectId)
        {
            var machines = new List<string>();
            machineids.ForEach(f =>
            {
                machines.Add(f.ToString());
            });
            return _context.siger_project_dnc_job_program.Count(f => f.projectid == projectId &&
                machines.Contains(f.machine_name) && f.time >= starttime &&
                f.time <= endtime && f.type == ChangeProgramType.Update.ToString().ToLower());
        }

    }
}
