using Microsoft.EntityFrameworkCore;
using OfficeOpenXml.FormulaParsing.ExpressionGraph;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Request;
using Siger.Middlelayer.Repository.Response;
using Siger.Middlelayer.Utility.ImportEntities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Siger.Middlelayer.Repository.Repositories
{
    internal class SigerProjectWorkingCostRepository : ApiConfigRepositoryBase<siger_project_working_cost>, ISigerProjectWorkingCostRepository
    {
        private readonly ApiConfigDbContext _context;

        public SigerProjectWorkingCostRepository(ApiConfigDbContext context) : base(context)
        {
            _context = context;
        }
        public IPagedCollectionResult<ResponseSearchWorkingCost> GetData(RequestSearchWorkingCost condition, int pid)
        {
            var query = _context.siger_project_working_cost
                .Where(f => f.status != 0 && f.projectid == pid)
                .Select(s => new ResponseSearchWorkingCost
                {
                    complex_id = s.complex_id,
                    complex_name = s.complex_name,
                    id = s.id,
                    usergroup_id = s.usergroup_id,
                    work_cost = s.work_cost
                });
            Expression<Func<ResponseSearchWorkingCost, bool>> funcUserGroup = f => true;
            if (condition.usergroup_id != 0)
            {
                funcUserGroup = f => f.usergroup_id == condition.usergroup_id;
            }
            var predicates = funcUserGroup;
            List<ResponseSearchWorkingCost> entities;
            var count = query.Count(predicates);
            if (condition.page == 0)
            {
                entities = query.Where(predicates).AsNoTracking().ToList();
            }
            else
            {
                entities = query.Where(predicates).Skip((condition.page - 1) * condition.pagesize).Take(condition.pagesize).AsNoTracking().ToList();
            }
            var userGroups = _context.siger_project_usergroup.Where(f => f.status != 0 && f.projectid == pid).ToList();
            foreach (var item in entities)
            {
                var userGroupsModel = userGroups.FirstOrDefault(f => f.id == item.usergroup_id);
                item.usergroup_name = userGroupsModel?.title ?? "";
                item.sectionid = userGroupsModel?.sectionid ?? 0;
            }
            return new PagedCollectionResult<ResponseSearchWorkingCost>(entities, count);
        }
        public CommonImportResult ImportData(IEnumerable<ImportWorkingCost> data, int projectId, int userId)
        {
            var errors = new List<string>();
            var entities = new List<siger_project_working_cost>();
            var rowIndex = 1;
            var now = DateTime.Now;
            foreach (var item in data)
            {
                rowIndex++;
                //检查usergroup
                var usergroup = _context.siger_project_usergroup.FirstOrDefault(q => q.title == item.usergroup_name && q.projectid == projectId && q.status == (int)RowState.Valid);
                if (usergroup == null)
                {
                    errors.Add($"{rowIndex},{Convert.ToString((int)RequestEnum.UserGroupNotFound)}");
                }
                else
                {
                    //检查重复
                    var model = _context.siger_project_working_cost.FirstOrDefault(f => f.status != 0 && f.projectid == projectId && f.usergroup_id == usergroup.id);
                    if (model != null)
                    {
                        errors.Add($"{rowIndex},{Convert.ToString((int)CommonEnum.RecordExits)}");
                    }
                    var importcount = data.Count(f => f.usergroup_name == item.usergroup_name);
                    if (importcount > 1)
                    {
                        errors.Add($"{rowIndex},{Convert.ToString((int)CommonEnum.RecordExits)}");
                    }
                }
                if (errors.Any())
                {
                    return new CommonImportResult(0, string.Join(";", errors));
                }
                entities.Add(new siger_project_working_cost
                {
                    create_time = now,
                    creator = userId,
                    editor = userId,
                    projectid = projectId,
                    usergroup_id = usergroup.id,
                    work_cost = item.work_cost,
                });
            }
            foreach (var entity in entities)
            {
                _context.siger_project_working_cost.Add(entity);
            }
            try
            {
                _context.SaveChanges();
                return new CommonImportResult(1, "1");
            }
            catch
            {
                throw;
            }
        }
    }
}
