using System;
using System.Collections.Generic;
using System.Linq;
using Siger.Middlelayer.AccRepository.Entities;
using Siger.Middlelayer.AccRepository.Repositories.Interface;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Utility.ImportEntities;

namespace Siger.Middlelayer.AccRepository.Repositories
{
    internal class SigerCheckItemRepository : AccRepositoryBase<SigerTrCheckItem>, ISigerCheckItem
    {
        private ApiAccDbContext accDbContext;
        public SigerCheckItemRepository(ApiAccDbContext context) : base(context)
        {
            accDbContext = context;
        }

        public CommonImportResult ImportOQCCheckItem(IEnumerable<OQCCheckItemTemplate> checkitems, int projectid, int userid)
        {
            var errors = new List<string>();
            var rowIndex = 1;
            var newList = new List<OQCCheckItemTemplate>();
            foreach (var p in checkitems)
            {
                rowIndex++;
                var lines = accDbContext.siger_project_level_section.SingleOrDefault(t => t.title == p.line && t.status == (int)RowState.Valid && t.projectid == projectid);
                var stations = accDbContext.siger_project_level_section.SingleOrDefault(t => t.title == p.station && t.status == (int)RowState.Valid && t.projectid == projectid);
                var checktypes = accDbContext.siger_tr_dict.FirstOrDefault(t => t.status == (int)RowState.Valid
                        && t.cat == AccDictCostNoProjectId.checktype && t.dval == p.checktype);

                if (lines == null)
                    errors.Add($"{rowIndex},{(int)RequestEnum.LineError}");
                if (stations == null)
                    errors.Add($"{rowIndex},{(int)RequestEnum.StationError}");
                if (checktypes == null)
                    errors.Add($"{rowIndex},{(int)RequestEnum.CheckTypeNotExsitInDict}");
                if (lines != null && stations != null )
                {
                    var model = accDbContext.siger_tr_oqc_check_item.SingleOrDefault(t => t.Line == lines.id && t.Station == stations.id
                        && t.ProductID == p.productid && t.PN == p.pn && t.Item == p.item && t.status == (int)RowState.Valid && t.projectId == projectid);
                    var repeats = checkitems.Where(t => t.line == p.line && t.station == p.station && t.productid == p.productid && t.pn == p.pn && t.item == p.item);
                    if (model != null || repeats.Count() > 1)
                    {
                        errors.Add($"{rowIndex},{(int)RequestEnum.OQCCheckItemAddOrUpdateError}");
                    }
                }

                var isTranslate = GetProjectLanguage(projectid) == (int)LanguageType.EN;
                var FillInValue = isTranslate
                    ? EnumHelper.GetEnumDesc(CheckType_Status_En.V)
                    : EnumHelper.GetEnumDesc(CheckType_Status.V);
                if (p.checktype != FillInValue)
                {
                    p.max = "";
                    p.min = "";
                }
                if (p.checktype == FillInValue && (string.IsNullOrEmpty(p.min) || string.IsNullOrEmpty(p.max) || p.min.ToDouble() > p.max.ToDouble())
                    || p.min.ToDouble() < 0 || p.max.ToDouble() < 0)
                {
                    errors.Add($"{rowIndex},{(int)RequestEnum.MaxMinError}");
                }

                var seqs = newList.Count(t => t.pn == p.pn && t.line == p.line && t.station == p.station && t.productid == p.productid);
                p.seq = seqs > 0 ? seqs + 1 : 1;
                newList.Add(p);
            }
            if (errors.Any())
            {
                return new CommonImportResult(0, string.Join(";", errors));
            }

            var entities = new List<SigerTrCheckItem>();
            foreach (var p in newList)
            {
                var lines = accDbContext.siger_project_level_section.FirstOrDefault(t => t.title == p.line && t.status == (int)RowState.Valid && t.projectid == projectid);
                var stations = accDbContext.siger_project_level_section.FirstOrDefault(t => t.title == p.station && t.status == (int)RowState.Valid && t.projectid == projectid);
                if (lines != null && stations != null)
                {
                    var route = accDbContext.siger_project_product_route.FirstOrDefault(f => f.projectId == projectid && f.name == p.route);
                    var seqs = accDbContext.siger_tr_oqc_check_item.Count(t => t.projectId == projectid && t.PN == p.pn
                        && t.Line == lines.id && t.Station == stations.id && t.ProductID == p.productid && t.status == (int)RowState.Valid);
                    seqs = seqs > 0 ? seqs + p.seq : p.seq;
                    var checktypes = accDbContext.siger_tr_dict.FirstOrDefault(t => t.status == (int)RowState.Valid
                        && t.cat == AccDictCostNoProjectId.checktype && t.dval == p.checktype);
                    var psEntity = new SigerTrCheckItem
                    {
                        projectId = projectid,
                        ProductID = p.productid,
                        PN = p.pn ?? "",
                        Line = lines.id,
                        Station = stations.id,
                        Seq = seqs,
                        Item = p.item ?? "",
                        Descr = p.descr ?? "",
                        CheckType = checktypes.dkey ?? "",
                        Min = p.min ?? "",
                        Max = p.max ?? "",
                        Version = "V" + $"{DateTime.Now:yyyyMMdd}",
                        UID = userid.ToString(),
                        TransDateTime = DateTime.Now,
                        ProductRoute=route==null?0:route.id
                    };
                    entities.Add(psEntity);
                }
            }
            try
            {
                accDbContext.siger_tr_oqc_check_item.AddRange(entities);
                accDbContext.SaveChanges();
                return new CommonImportResult(1, "1");
            }
            catch
            {
                throw;
            }
        }
    }
}
