using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.QmsRepository.Entities;
using Siger.Middlelayer.QmsRepository.Repositories.Interface;
using Siger.Middlelayer.QmsRepository.Response;
using Siger.Middlelayer.Repository.Extensions;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.Utility.ImportEntities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Siger.Middlelayer.QmsRepository.Repositories
{
    internal class QmsmanufacturingMaterial : QMSRepositoryBase<siger_qms_cell_manufacturing>, IQmsmanufacturingMaterial
    {
        private ApiQmsDbContext _context;
        public QmsmanufacturingMaterial(ApiQmsDbContext context) : base(context)
        {
            _context = context;
        }

        public IPagedCollectionResult<ResponseManufacturingMaterial> GetManufacturingPagedList(List<int> sectionId, int materialId, int productId, int projectId, int page, int pagesize)
        {

            Expression<Func<ResponseManufacturingMaterial, bool>> funProduct = f => true;
            Expression<Func<ResponseManufacturingMaterial, bool>> funMaterial = f => true;

            var query = from q in _context.siger_qms_cell_manufacturing
                        join p in _context.siger_project_product on q.productId equals p.id
                        join m in _context.siger_tr_materials on q.materail equals m.id
                        join s in _context.siger_project_level_section on q.section equals s.id
                        where sectionId.Contains(q.section) && q.status == (int)RowState.Valid
                        select new ResponseManufacturingMaterial
                        {
                            Id = q.id,
                            ProductId = q.productId,
                            ProductCode=p.code,
                            ProdcutName = p.name,
                            MaterialId = q.materail,
                            Pn=m.pn,
                            MaterialName = m.name,
                            Line=s.parentid,
                            Section = q.section,
                            MaterialSpec = m.spec,
                            Count = q.count

                        };
            if (productId != 0)
                funProduct = f => f.ProductId == productId;
            if (materialId != 0)
                funMaterial = f => f.MaterialId == materialId;

            var predicate = funProduct.And(funMaterial);
            var total = query.Count(predicate);
            var entities = query.Where(predicate).OrderBy(s => s.Id).Skip((page - 1) * pagesize).Take(pagesize).ToList();
            return new PagedCollectionResult<ResponseManufacturingMaterial>(entities, total);

        }

        public IEnumerable<ResponseMaterialByCell> GetMaterialByCells(int projectId, int productId, IEnumerable<int> sections)
        {
            var query = from q in _context.siger_qms_cell_manufacturing
                        join m in _context.siger_tr_materials on q.materail equals m.id
                        where q.projectid == projectId && q.productId == productId && sections.Contains(q.section) &&
                        q.status == (int)RowState.Valid && m.status == (int)RowState.Valid
                        select new ResponseMaterialByCell
                        {
                            id = q.materail,
                            name = m.name,
                            pn = m.pn,
                            spec = m.spec,
                            qty = q.count
                        };
            return query;
        }

        public CommonImportResult ImportManufacturingMaterial(IEnumerable<ImportManufacturingMaterial> datas, int projectid)
        {
            var errors = new List<string>();
            var rowIndex = 1;

            var dataArry = new List<siger_qms_cell_manufacturing>();
            foreach (var d in datas)
            {

                var objLine = _context.siger_project_level_section.FirstOrDefault(f => f.projectid == projectid && f.title == d.Line);
                if (objLine == null)
                {
                    errors.Add($"{rowIndex},{(int)ConfigEnum.StationNotFound}");
                    return new CommonImportResult(0, string.Join(";", errors));
                }
                var objSection = _context.siger_project_level_section.FirstOrDefault(f => f.projectid == projectid && f.title == d.Section && f.parentid == objLine.id);
                if (objSection == null)
                {
                    errors.Add($"{rowIndex},{(int)ConfigEnum.StationNotFound}");
                    return new CommonImportResult(0, string.Join(";", errors));
                }
                var objProduct = _context.siger_project_product.FirstOrDefault(f => f.projectid == projectid && f.name==d.Product && f.code==d.ProductCode);
                if (objProduct == null)
                {
                    errors.Add($"{rowIndex},{(int)CommonEnum.RecordNotFound}");
                    return new CommonImportResult(0, string.Join(";", errors));
                }
                var objMaterial = _context.siger_tr_materials.FirstOrDefault(f => f.projectId == projectid && f.pn == d.Material);
                if (objMaterial == null)
                {
                    errors.Add($"{rowIndex},{(int)CommonEnum.RecordNotFound}");
                    return new CommonImportResult(0, string.Join(";", errors));
                }
                var exitsObj = _context.siger_qms_cell_manufacturing.FirstOrDefault(f => f.projectid == projectid && f.productId ==objProduct.id && f.section == objSection.id && f.materail == objMaterial.id);
                if (exitsObj != null)
                {
                    errors.Add($"{rowIndex},{(int)CommonEnum.RecordExits}");
                    return new CommonImportResult(0, string.Join(";", errors));
                }
                dataArry.Add(new siger_qms_cell_manufacturing
                {
                    projectid = projectid,
                    section = objSection.id,
                    productId=objProduct.id,
                    materail=objMaterial.id,
                    count=d.Qty,
                    status = (int)RowState.Valid
                });
            }
            if (errors.Any())
                return new CommonImportResult(0, string.Join(";", errors));

            if (dataArry.Any())
            {
                _context.siger_qms_cell_manufacturing.AddRange(dataArry);
                _context.SaveChanges();
                return new CommonImportResult(1, "1");
            }
            return new CommonImportResult(0, "0");
           
        }
    }
}
