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

namespace Siger.Middlelayer.QmsRepository.Repositories
{
    internal class QmsProductWarehousingRepository : QMSRepositoryBase<siger_qms_product_warehousing>, IQmsProductWarehousing
    {
        private ApiQmsDbContext qmsDbContext;
        public QmsProductWarehousingRepository(ApiQmsDbContext context) : base(context)
        {
            qmsDbContext = context;
        }

        public IPagedCollectionResult<ResponseProductWarehous> GetWarehousPagedList(string productCode,
            List<int> sections, string startdate, string enddate, int projectId, int page, int pagesize)
        {
            Expression<Func<ResponseProductWarehous, bool>> funCode = f => true;
            Expression<Func<ResponseProductWarehous, bool>> funDate = f => true;
            var query = from w in qmsDbContext.siger_qms_product_warehousing
                join p in qmsDbContext.siger_project_product on w.productid equals p.id
                join s in qmsDbContext.siger_project_level_section on w.section equals s.id
                join u in qmsDbContext.siger_project_user on w.mid equals u.mid
                where w.projectid == projectId && sections.Contains(w.section) && w.status == (int) RowState.Valid
                select new ResponseProductWarehous
                {
                    Id = w.id,
                    Section = w.section,
                    SectoinDesc = s.title,
                    ProductId = p.id,
                    ProductCode = p.code,
                    Mid = w.mid,
                    UserName = u.name,
                    CreateTimeDt = w.createtime,
                    CreateTime = w.createtime.ToString(ParameterConstant.DateFormat),
                    Operate = w.operate,
                    Qty = w.qty
                };

            if (!string.IsNullOrEmpty(productCode))
            {
                funCode = f => f.ProductCode.Contains(productCode);
            }
            if (!string.IsNullOrWhiteSpace(startdate) && !string.IsNullOrWhiteSpace(enddate))
            {
                funDate = f => f.CreateTimeDt >= startdate.ToDateTime() && f.CreateTimeDt <= enddate.ToDateTime();
            }

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

        public CommonImportResult ImportWarehouse(IEnumerable<ImportProductWarehouse> datas, int mid,int projectid)
        {

            int rowIndex = 0;
            List<string> messages = new List<string>();
            List<siger_qms_product_warehousing> entities = new List<siger_qms_product_warehousing>();
            foreach (var it in datas)
            {
                rowIndex += 1;
                var productObj = qmsDbContext.siger_project_product.FirstOrDefault(f => f.projectid == projectid && f.code == it.ProductCode);
                if (productObj == null)
                {
                    messages.Add($"{rowIndex},{(int)RequestEnum.ProductCodeIsNull}");
                    return new CommonImportResult(0, string.Join(";", messages));
                }

                var section = qmsDbContext.siger_project_level_section.FirstOrDefault(f => f.title == it.Section);
                if (section==null)
                {
                    messages.Add($"{rowIndex},{(int)RequestEnum.SectionNotFound}");
                    return new CommonImportResult(0, string.Join(";", messages));
                }

                //var obj = qmsDbContext.siger_qms_product_warehousing.FirstOrDefault(f => f.projectid == projectid && f.productid == productObj.id && f.section==section.id);
                //if (obj != null)
                //{
                //    messages.Add($"{rowIndex},{(int)CommonEnum.RecordExits}");
                //    return new CommonImportResult(0, string.Join(";", messages));
                //}

                entities.Add(new siger_qms_product_warehousing
                {
                    projectid=projectid,
                    productid=productObj.id,
                    operate=DateTime.Now,
                    createtime=it.CreateDate.ToDateTime(),
                    qty=it.Qty,
                    section=section.id,
                    type=1,
                    mid=mid,
                    status = (int)RowState.Valid,
                });
            }
            try
            {
                qmsDbContext.siger_qms_product_warehousing.AddRange(entities);
                if (qmsDbContext.SaveChanges() > 0)
                    return new CommonImportResult(1, "1");
                else
                    throw new BadRequestException(CommonEnum.Fail);
            }
            catch
            {
                throw;
            }
        }
    }
}
