using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.AccRepository.Entities;
using Siger.Middlelayer.AccRepository.Repositories.Interface;
using Siger.Middlelayer.AccRepository.Response;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Repository.Extensions;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.Utility.ExcelImport;
using Siger.Middlelayer.Utility.ImportEntities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

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

       public  IPagedCollectionResult<ResponseSerialNum> GetPagedConfigList(string productCode, int ruleType, int page, int pagesize)
        {
            
            Expression<Func<ResponseSerialNum, bool>> funType = f => true;
            Expression<Func<ResponseSerialNum, bool>> funPrd = f => true;

            var query = from i in accDbContext.siger_tr_serinumCfg
                        where i.status == (int)RowState.Valid
                        select new ResponseSerialNum
                        {
                            id=i.id,
                            ProductId = i.ProductID,
                            RuleKey=i.Rule,
                            Code =i.ItemType,
                            Step = i.Seq,
                            CodeFormat = i.TypeFormat,
                            Length = i.Length,
                            Value =i.ItemValue,
                            LengthNull=i.Length==0?"":i.Length.ToStr()
                        };
            if (ruleType!=0)
            {
                funType = f => f.RuleKey == ruleType;
            }
            if (!string.IsNullOrEmpty(productCode))
            {
                funPrd = f => f.ProductId.Contains(productCode);
            }
            var predicate = funType.And(funPrd);
            var total = query.Where(predicate).Count();
            var data = query.Where(predicate).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();
            foreach(var d in data)
            {
                d.RuleDesc =EnumHelper.GetEnumDesc( (SerialCfgType)d.RuleKey);
                d.CodeDesc = EnumHelper.GetEnumDesc((SeriNumCfg)d.Code);
                
            }
            return new PagedCollectionResult<ResponseSerialNum>(data, total);
        }

        public CommonImportResult ImportSerinCfg(IEnumerable<SerinCfgConfigTemplate> serialnumlist, int projectid, int userId)
        {
            var errors = new List<string>();
            var rowIndex = 1;
            var formatarry = new List<string> { 
             "YYDDD",
             "YYYYMMDD",
             "YYMMDD"
            };
            foreach (var p in serialnumlist)
            {
                rowIndex++;
                var product = accDbContext.siger_project_product.FirstOrDefault(f => f.projectid == projectid && f.code == p.ProductId);
                if (product == null)
                {
                    errors.Add($"{rowIndex},{(int)ImportEnum.ProductCodeIsEmpty}");
                }
                var stationmodel = accDbContext.siger_tr_serinumCfg.FirstOrDefault(t => t.projectId == projectid 
                && t.Seq==p.Step &&t.ProductID==p.ProductId &&t.ItemType==p.Code && t.Rule==p.RuleDesc && t.status == (int)RowState.Valid);
                if (stationmodel != null)
                {
                    errors.Add($"{rowIndex},{(int)CommonEnum.RecordExits}");
                }
                if (p.Code==1)
                {
                    if(!formatarry.Contains(p.CodeFormat))
                    {
                        errors.Add($"{rowIndex},{(int)ImportEnum.DateTimeIsInValid}");
                    }
                }
            }
            if (errors.Any())
            {
                return new CommonImportResult(0, string.Join(";", errors));
            }
            var list = new List<SigerTrSerinumcfg>();
            foreach (var item in serialnumlist)
            {
                var entity = new SigerTrSerinumcfg
                {
                   Rule= item.RuleDesc,
                   projectId=projectid,
                   ProductID=item.ProductId, 
                   ItemType= item.Code,
                   TypeFormat=item.CodeFormat,
                   Seq=item.Step,
                   Length=item.Length.ToInt(),
                   status =1,
                   ItemValue= item.Value
                };
                list.Add(entity);
            }
            try
            {
                accDbContext.siger_tr_serinumCfg.AddRange(list);
                accDbContext.SaveChanges();
                return new CommonImportResult(1, "1");
            }
            catch
            {
                throw;
            }
        }
    }
}
