using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.AccRepository.Entities;
using Siger.Middlelayer.AccRepository.Repositories.Interface;
using Siger.Middlelayer.AccRepository.Response;
using Siger.Middlelayer.Repository.Extensions;
using Siger.Middlelayer.Repository.Paged;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;

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

        public async Task<IPagedCollectionResult<ResponseTrSnTraceDetails>> TrSNTraceDtsRtpPagedList(string sn, DateTime startTime, DateTime endTime, int projectId, string productId, int line, int station, string pn, int page = 1, int pagesize = 10)
        {
            return await Task.Run(() =>
            {
                Expression<Func<SigerTrSnTrace, bool>> FunSn = f => true;
                Expression<Func<SigerTrSnTrace, bool>> FunDate = f => true;
                Expression<Func<SigerTrSnTrace, bool>> FunProduct = f => true;
                Expression<Func<SigerTrSnTrace, bool>> FunLine = f => true;
                Expression<Func<SigerTrSnTrace, bool>> FunStation = f => true;
                if (!string.IsNullOrEmpty(sn))
                    FunSn = f => f.SN.Contains(sn);
                else
                    FunDate = f => f.LastUpdateTime >= startTime && f.LastUpdateTime <= endTime;
                if (line != 0)
                    FunLine = f => f.Line == line;
                if (station != 0)
                    FunStation = f => f.Station == station;
                if (!string.IsNullOrEmpty(productId))
                    FunProduct = f => f.ProductID.Contains(productId);
                var predicate = FunSn.And(FunDate).And(FunProduct).And(FunLine).And(FunStation).And(FunProduct);

                var query = from h in accDbContext.siger_tr_sn_trace.Where(predicate)
                            join d in accDbContext.siger_tr_sn_trace_detail on h.SeqID equals d.SeqID
                            join l in accDbContext.siger_project_level_section on h.Station equals l.id
                            join m in accDbContext.siger_project_level_section on l.parentid equals m.id
                            join s in accDbContext.siger_project_level_section on h.Station equals s.id
                            where h.projectId == projectId
                            select new ResponseTrSnTraceDetails
                            {
                                Id = d.id,
                                SeqID = d.SeqID,
                                SN = d.SN,
                                Item = d.Item,
                                Item2 = d.Item2,
                                Item3 = d.Item3,
                                Value = d.Item != "检测结果"? d.Value : d.Value.Trim() == "1" ? "合格" : d.Value.Trim() == "0" ? "不合格" : "",
                                Result = d.Result,
                                Remarks = d.Remarks,
                                Remarks2 = d.Remarks2,
                                Remarks3 = d.Remarks3,
                                TransDateTime = d.TransDateTime,
                                LastUpdateTime = d.LastUpdateTime,
                                Line = h.Line,
                                LineTitle = m.title,
                                Station = h.Station,
                                StationTitle = s.title,
                                ProductId = h.ProductID,

                            };
                var totalCount = query.Count();
                var entities = query.OrderByDescending(o=>o.Id).Skip((page - 1) * pagesize).Take(pagesize).OrderByDescending(o => o.TransDateTime).AsQueryable();
                return new PagedCollectionResult<ResponseTrSnTraceDetails>(entities, totalCount);
            });
        }
        /// <summary>
        /// 仅供导出数据使用
        /// </summary>
        /// <param name="sns"></param>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public async Task<List<ResponseTrSnTraceDetails>> TrSNTraceDtsRtpPagedList(List<string> sns, int projectId)
        {
            return await Task.Run(() =>
            {
                var ret = new List<ResponseTrSnTraceDetails>();
                if (!sns.Any())
                {
                    return ret;
                }
                var query = from h in accDbContext.siger_tr_sn_trace.Where(f => sns.Contains(f.SN) && f.projectId.Equals(projectId) && f.status == (int)RowState.Valid)
                            join d in accDbContext.siger_tr_sn_trace_detail on h.SeqID equals d.SeqID
                            join l in accDbContext.siger_project_level_section on h.Line equals l.id
                            join s in accDbContext.siger_project_level_section on h.Station equals s.id
                            where d.projectId == projectId && d.status == (int)RowState.Valid
                            select new ResponseTrSnTraceDetails
                            {
                                SeqID = d.SeqID,
                                SN = d.SN,
                                Item = d.Item,
                                Item2 = d.Item2,
                                Item3 = d.Item3,
                                Value = d.Value,
                                Result = d.Result,
                                Remarks = d.Remarks,
                                Remarks2 = d.Remarks2,
                                Remarks3 = d.Remarks3,
                                TransDateTime = d.TransDateTime,
                                LastUpdateTime = d.LastUpdateTime,
                                Line = h.Line,
                                LineTitle = l.title,
                                Station = h.Station,
                                StationTitle = s.title,
                                ProductId = h.ProductID,
                            };
                ret = query.OrderByDescending(o => o.TransDateTime).ToList();
                return ret;
            });
        }
        /// <summary>
        /// 获取工站过站明细的检查项
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="sectionId"></param>
        /// <param name="item">检查项</param>
        /// <param name="count">样本数</param>
        /// <returns></returns>
        public IEnumerable<ResponseDtsItem> GetDtsItem(int projectId, int sectionId, string item, int count)
        {
            var query = from d in accDbContext.siger_tr_sn_trace_detail
                        join h in accDbContext.siger_tr_sn_trace on d.SeqID equals h.SeqID
                        where h.projectId == projectId && h.projectId == d.projectId && h.Station == sectionId && d.Item == item && h.status == (int)RowState.Valid
                        select new ResponseDtsItem
                        {
                            Id = d.id,
                            Item = d.Item,

                            Value = d.Value,
                            TransDateTime = d.TransDateTime

                        };
            var data = query.Skip(0).Take(count).OrderBy(o => o.TransDateTime).ThenBy(o => o.Id).AsQueryable();
            return data;

        }
    }
}
