using System;
using System.Linq;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.TpmRepository.Entities;
using Siger.Middlelayer.TpmRepository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Response;

namespace Siger.Middlelayer.TpmRepository.Repositories
{
    internal class RepairEditRecordRepository : TpmRepositoryBase<siger_project_repair_edit_record>, IRepairEditRecordRepository
    {
        private readonly ApiTpmDbContext _context;
        public RepairEditRecordRepository(ApiTpmDbContext context) : base(context)
        {
            _context = context;
        }

        public IPagedCollectionResult<RepairEditRecord> GetRepairEditRecords(int page, int pagesize, int projectId)
        {
            var queryList = from q in _context.siger_project_repair_edit_record
                join u in _context.siger_project_user on q.creator_mid equals u.mid into uu
                from us in uu.DefaultIfEmpty()
                where q.project_id == projectId && q.status == (int)RowState.Valid
                select new RepairEditRecord
                {
                    create_time = q.create_time,
                    create_time_str = q.create_time.ToString(ParameterConstant.DateTimeFormat),
                    creator_mid = q.creator_mid,
                    user_name = us != null ? us.name : "",
                    content = q.content,
                    repair_id = q.repair_id,
                    work_order = q.repair_id.ToString()
                };
            var totalCount = queryList.Count();
            var entities = queryList.OrderByDescending(q => q.create_time).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();

            return new PagedCollectionResult<RepairEditRecord>(entities, totalCount);
        }
    }
}
