using System;
using Siger.Middlelayer.KpiRespository.Repositories.Interface;
using Siger.Middlelayer.KpiRespository.Entities;
using Siger.Middlelayer.KpiRespository.Respose;
using System.Linq;
using System.Linq.Expressions;
using Siger.Middlelayer.Repository.Extensions;
using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.Utility.ImportEntities;
using System.Collections.Generic;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Share.ModuleEnum;
using NPOI.SS.Formula.Functions;

namespace Siger.Middlelayer.KpiRespository.Repositories
{
    internal class KpiItemRespository:KpiRepositoryBase<siger_project_kpi_item>,ISigerKpiItem
    {

        private ApiKpiDbContext kpiDbContext;
        public KpiItemRespository(ApiKpiDbContext context) : base(context)
        {
            kpiDbContext = context;
        }

        public IEnumerable<ResposeItemlist> GetKpiItems(int section, int projectId)
        {
            Expression<Func<ResposeItemlist, bool>> FunSection = f => true;

            var query = from i in kpiDbContext.siger_project_kpi_item
                        join d in kpiDbContext.siger_project_section on i.Section equals d.id
                        where i.projectId == projectId && i.status==(int)RowState.Valid
                        select new ResposeItemlist
                        {
                            Id = i.id,
                            Section = i.Section,
                            KpiCycle = i.KpiCycle,
                            Department = d.title,
                            Item = i.Item,
                            TargetVal = i.TargetVal,
                            Unit = i.Unit,
                            Condition = i.Condition,
                            Position = i.Position,
                            Color = i.Color,
                            Enable = i.status,
                            Createtime = i.CreateTime
                        };
            if (section != 0)
                FunSection = f => f.Section == section;

            return query.Where(FunSection).OrderBy(o => o.Section).ToList();
        }

        public IPagedCollectionResult<ResposeItemlist> GetKPItemPagedList(int section, string item, int projectid, int page, int pagesize, int position = 0)
        {
            Expression<Func<ResposeItemlist, bool>> FunSection = f => true;
            Expression<Func<ResposeItemlist, bool>> FunItem = f => true;
            Expression<Func<ResposeItemlist, bool>> FunPosition = f => true;

            var query = from i in kpiDbContext.siger_project_kpi_item
                        join d in kpiDbContext.siger_project_section on i.Section equals d.id
                        join u in kpiDbContext.siger_project_user on i.Creater equals u.mid
                        where i.projectId == projectid  //&& i.status==(int)RowState.Valid
                        select new ResposeItemlist
                        {
                            Id = i.id,
                            Section = i.Section,
                            KpiCycle=i.KpiCycle,
                            Department = d.title,
                            Item = i.Item,
                            TargetVal = i.TargetVal,
                            Unit = i.Unit,
                            Condition = i.Condition,
                            Position = i.Position,
                            Color = i.Color,
                            Enable = i.status ,
                            Creater = u.name,
                            Createtime = i.CreateTime
                        };
            if (section != 0)
                FunSection = f => f.Section == section;
            if (!string.IsNullOrEmpty(item))
                FunItem = f => f.Item.Contains(item);
            //if (position != 0)
            //    FunPosition = f => f.Position>0;

            var predicate = FunSection.And(FunItem).And(FunPosition);
            var totalCount = query.Count(predicate);
            var entities = query.Where(predicate).OrderByDescending(q => q.Id).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();
            return new PagedCollectionResult<ResposeItemlist>(entities, totalCount);
        }

        public CommonImportResult ImportKpiItem(IEnumerable<ImportKpiItem> items, int projectid)
        {
            var errors = new List<string>();
            var entities = new List<siger_project_kpi_item>();
            var rowIndex = 1;
            var moblieduplicate = new List<string>();
            var workduplicate = new List<string>();

            foreach (var it in items)
            {
                rowIndex++;
                int departId = 0;
                var depart = kpiDbContext.siger_project_section.FirstOrDefault(f => f.title == it.Department);
                if (depart == null)
                    errors.Add($"{rowIndex},{Convert.ToString((int)RequestEnum.SectionNotFound)}");
                else
                {
                    var ItemObj=kpiDbContext.siger_project_kpi_item.FirstOrDefault(q => q.Item.Contains(it.Item) && q.Section == departId && q.projectId == projectid);
                    if (ItemObj!=null)
                        errors.Add($"{rowIndex},{Convert.ToString((int)RequestEnum.DataExist)}");
                }

                var user = kpiDbContext.siger_project_user.FirstOrDefault(f => f.projectid == projectid && f.name == it.Creater);
                if (user==null)
                    errors.Add($"{rowIndex},{Convert.ToString((int)RequestEnum.UserNotFound)}");
                if (errors.Any())
                {
                    return new CommonImportResult(0, string.Join(";", errors));
                }
            }
            //add record
            foreach (var it in items)
            {
                var depart = kpiDbContext.siger_project_section.FirstOrDefault(f => f.title == it.Department);
                var user = kpiDbContext.siger_project_user.FirstOrDefault(f => f.projectid == projectid && f.name == it.Creater);
                var KpiObj= new siger_project_kpi_item
                {
                    Item=it.Item,
                    projectId=projectid,
                    Section= depart.id,
                    Position=it.Position,
                    Color=it.Color,
                    Condition=it.Condition.Contains(">")?0:1,
                    Creater=user.mid,
                    TargetVal=it.TargetVal,
                    CreateTime=DateTime.Now,
                    Unit=it.Unit,
                    status=(int)RowState.Valid

                };
                entities.Add(KpiObj);
            }

            try
            {
                kpiDbContext.siger_project_kpi_item.AddRange(entities);
                kpiDbContext.SaveChanges();
                return new CommonImportResult(1, "1");
            }
            catch
            {
                throw;
            }
        }

        public IEnumerable<ResposeItemlist> GetKpiItemList(int projectid)
        {
            var query = from i in kpiDbContext.siger_project_kpi_item
                        join d in kpiDbContext.siger_project_section on i.Section equals d.id
                        where i.projectId == projectid  && i.status==(int)RowState.Valid
                        select new ResposeItemlist
                        {
                            Id = i.id,
                            Section = i.Section,
                            KpiCycle = i.KpiCycle,
                            Department = d.title,
                            Item = i.Item,
                            TargetVal = i.TargetVal,
                            Unit = i.Unit,
                            Condition = i.Condition,
                            Position = i.Position,
                            Color = i.Color,
                            Enable = i.status,
                            Createtime = i.CreateTime
                        };
            return query.OrderBy(q => q.Section).AsNoTracking().ToList();
        }
    }
}
