using System;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.AccRepository.Entities;
using Siger.Middlelayer.AccRepository.Repositories.Interface;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Repository.Data;
using Siger.Middlelayer.Repository.Paged;

namespace Siger.Middlelayer.AccRepository.Repositories
{
    internal class SigerTrReworkWoSettingRepository : AccRepositoryBase<SigerTrReworkWoSetting>, ISigerTrReworkWoSettingRepository
    {
        private readonly ApiAccDbContext accDbContext;
        public SigerTrReworkWoSettingRepository(ApiAccDbContext context) : base(context)
        {
            accDbContext = context;
        }

        public IPagedCollectionResult<ReworkWoSetting> GetPagedList(string wo, int projectid, int page = 1, int pagesize = 10)
        {
            var reworkWoSettings =
                accDbContext.siger_tr_rework_wo_setting.Where(q => q.status == (int)RowState.Valid && q.projectId == projectid);
            var query = from p in reworkWoSettings
                        join m in accDbContext.siger_project_level_section
                        on new { stationid = p.start_station, projectids = projectid, rowstatus = (int)RowState.Valid }
                        equals new { stationid = m.id, projectids = m.projectid, rowstatus = m.status }
                        into stationtemp
                        from m in stationtemp.DefaultIfEmpty()
                        select new ReworkWoSetting
                        {
                            id = p.id,
                            wo = p.wo,
                            reason = p.reason,
                            start_station = p.start_station,
                            start_station_value = m.title,
                            functions = p.functions,
                            functions_value = "",
                            transdatetime = p.TransDateTime.ToString(ParameterConstant.DateTimeFormat)
                        };
            Expression<Func<ReworkWoSetting, bool>> predicate = q => true;
            if (!string.IsNullOrEmpty(wo))
            {
                predicate = q => q.wo==wo;
            }

            var totalCount = query.Count(predicate);
            var entities = query.Where(predicate).OrderByDescending(q => q.id).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();
            return new PagedCollectionResult<ReworkWoSetting>(entities, totalCount);
        }
    }
}
