using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.Log;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.TlmRepository.Entities;
using Siger.Middlelayer.TlmRepository.Repositories.Interface;
using Siger.Middlelayer.TlmRepository.Request;
using Siger.Middlelayer.TlmRepository.Response;

namespace Siger.Middlelayer.TlmRepository.Repositories
{
    internal class ToollifeCabinetReceiveRepository : TlmRepositoryBase<SigerProjectToollifeCabinetReceive>, IToollifeCabinetReceiveRepository
    {
        private readonly ApiTlmDbContext _context;
        public ToollifeCabinetReceiveRepository(ApiTlmDbContext context) : base(context)
        {
            _context = context;
        }

        public IPagedCollectionResult<ResponeCabinetReceiveData> GetCabinetReceiveData(RequestCabinetReceiveData request, int pid)
        {
            Expression<Func<ResponeCabinetReceiveData, bool>> funcCabinet = f => true;
            var query = from tcr in _context.siger_project_toollife_cabinet_receive
                        join tcc in _context.siger_project_toollife_cabinet_config on tcr.Cabinetcode equals tcc.Cabinetcode
                        where tcr.project_id.Equals(pid) && tcr.Transtime >= request.Begin && tcr.Transtime <= request.End && tcr.status != (int)RowState.Invalid
                        orderby tcr.Transtime descending
                        select new ResponeCabinetReceiveData
                        {
                            Billcode = tcr.Billcode,
                            Cabinetcode = tcr.Cabinetcode,
                            CabinetName = tcc.Name,
                            Id = tcr.id,
                            Settletime = tcr.Settletime,
                            Usercode = tcr.Usercode,
                            Supplier = tcc.Suppliername,
                            Transtime = tcr.Transtime,
                            Type = tcr.Type,
                            Status = tcr.status,
                            Uid = tcr.Uid,
                            Username = "",
                            SettleUser = ""
                        };
            if (!string.IsNullOrWhiteSpace(request.CabinetName))
            {
                funcCabinet = f => f.CabinetName.Equals(request.CabinetName);
            }
            var predicate = funcCabinet;
            var totalcount = query.Where(predicate).Count();
            var data = query.Where(predicate).Skip((request.page - 1) * request.pagesize).Take(request.pagesize).AsNoTracking().ToList();
            foreach (var item in data)
            {
                var username = _context.siger_project_user
                    .FirstOrDefault(f => f.work_code.Equals(item.Usercode) && f.projectid.Equals(pid));
                if (username != null)
                {
                    item.Username = username.name;
                }
                var settleuser = _context.siger_project_user
                    .FirstOrDefault(f => f.mid.Equals(item.Uid) && f.projectid.Equals(pid));
                if (settleuser != null)
                {
                    item.SettleUser = settleuser.name;
                }
            }
            return new PagedCollectionResult<ResponeCabinetReceiveData>(data, totalcount);
        }

        public int InertCabinetReceiveData(SigerProjectToollifeCabinetReceive data)
        {
            try
            {
                _context.siger_project_toollife_cabinet_receive.Add(data);
                return _context.SaveChanges();
            }
            catch (Exception e)
            {
                Logger.WriteLineError(e.Message);
                return 0;
            }
        }

        public int UpdateCabinetReceiveData(SigerProjectToollifeCabinetReceive data)
        {
            try
            {
                _context.siger_project_toollife_cabinet_receive.Update(data);
                return _context.SaveChanges();
            }
            catch (Exception e)
            {
                Logger.WriteLineError(e.Message);
                return 0;
            }
        }

        public int DeleteCabinetReceiveData(int id)
        {
            try
            {
                var entity = _context.siger_project_toollife_cabinet_receive.FirstOrDefault(f => f.id.Equals(id));
                if (entity == null)
                {
                    return 1;
                }
                _context.siger_project_toollife_cabinet_receive.Remove(entity);
                return _context.SaveChanges();
            }
            catch (Exception e)
            {
                Logger.WriteLineError(e.Message);
                return 0;
            }
        }

        public IEnumerable<ResponeCabinetReceiveData> GetCabinetReceiveDetailData(DateTime Begin, DateTime End, IEnumerable<int> userIds, int pid)
        {
            Expression<Func<ResponeCabinetReceiveData, bool>> funcCabinet = f => true;
            var query = from tcr in _context.siger_project_toollife_cabinet_receive
                        join tcc in _context.siger_project_toollife_cabinet_receive_detail on tcr.id equals tcc.Mid
                        where tcr.project_id.Equals(pid) && tcr.Transtime >= Begin && tcr.Transtime <= End && tcr.status != (int)RowState.Invalid
                        orderby tcr.Transtime descending
                        select new ResponeCabinetReceiveData
                        {
                            Billcode = tcr.Billcode,
                            Cabinetcode = tcr.Cabinetcode,
                            CabinetName = tcc.Name,
                            Id = tcr.id,
                            Settletime = tcr.Settletime,
                            Usercode = tcr.Usercode,
                            Transtime = tcr.Transtime,
                            Type = tcr.Type,
                            Status = tcr.status,
                            Uid = tcr.Uid,
                            Username = "",
                            SettleUser = "",
                            quantity = tcc.Count
                        };
            if (userIds.Any())
            {
                funcCabinet = f => userIds.Contains(f.Uid);
            }

            var predicate = funcCabinet;
            var data = query.Where(predicate).AsNoTracking().ToList();
            return data;
        }
    }
}
