
using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Repository.Extensions;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.TpmRepository.Entities;
using Siger.Middlelayer.TpmRepository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Request;
using Siger.Middlelayer.TpmRepository.Response;
using System;
using System.Linq;
using System.Linq.Expressions;

namespace Siger.Middlelayer.TpmRepository.Repositories
{
    /// <summary>
	/// SigerProjectSparepartOrder
	/// </summary>
    internal class SigerProjectSparepartOrder : TpmRepositoryBase<siger_project_sparepart_order>, ISigerProjectSparepartOrder
    {
        private readonly ApiTpmDbContext _context;

        public SigerProjectSparepartOrder(ApiTpmDbContext context) : base(context)
        {
            _context = context;
        }
        public string GengrateCode(int pid)
        {
            var no = 0;
            var str = DateTime.Now.ToString("yyyyMMdd");
            str = $"PO{str}_";
            var data = _context.siger_project_sparepart_order.Where(f => f.projectid.Equals(pid) && f.status == (int)RowState.Valid && f.order_code.StartsWith(str));
            if (data.Any())
            {
                var maxid = data.Max(m => m.id);
                var order = _context.siger_project_sparepart_order.First(f => f.id == maxid).order_code;
                if (!string.IsNullOrEmpty(order))
                {
                    if (order.Split('_').Length > 1)
                    {
                        no = order.Split('_')[1].ToInt();
                    }
                }
            }
            if (no != 0)
            {
                no += 1;
                str += no.ToStr();
            }
            else
            {
                str += "1";
            }
            return str;
        }

        public IPagedCollectionResult<ResponseSparepartOrderInfo> GetSparepartOrderInfo(RequestSparepartOrder condition, int pid)
        {
            Expression<Func<ResponseSparepartOrderInfo, bool>> funcCode = f => true;
            if (!string.IsNullOrEmpty(condition.order_code))
            {
                funcCode = f => f.order_code.Equals(condition.order_code);
            }
            Expression<Func<ResponseSparepartOrderInfo, bool>> funcOrderstatus = f => true;
            if (condition.order_status != 0)
            {
                funcOrderstatus = f => f.order_status.Equals(condition.order_status);
            }
            Expression<Func<ResponseSparepartOrderInfo, bool>> funcType = f => true;
            if (condition.order_type != 0)
            {
                funcType = f => f.order_type.Equals(condition.order_type);
            }
            Expression<Func<ResponseSparepartOrderInfo, bool>> funcApprove = f => true;
            if (condition.approve_status != 0)
            {
                funcApprove = f => f.approve_status.Equals(condition.approve_status);
            }
            Expression<Func<ResponseSparepartOrderInfo, bool>> funcOrders = f => true;
            if (condition.orders != null && condition.orders.Any())
            {
                funcOrders = f => condition.orders.Contains(f.order_code);
            }
            var query = _context.siger_project_sparepart_order.Where(f => f.projectid.Equals(pid) && f.status == (int)RowState.Valid).OrderByDescending(o => o.id);
            var querylist = from q in query
                            select new ResponseSparepartOrderInfo
                            {
                                approve_node = q.approve_node,
                                approve_status = q.approve_status,
                                id = q.id,
                                cost = q.cost,
                                mid = q.mid,
                                order_code = q.order_code,
                                order_status = q.order_status,
                                order_type = q.order_type,
                                edit_time = q.edit_time
                            };
            var predicate = funcType.And(funcOrderstatus).And(funcApprove).And(funcCode).And(funcOrders);
            var count = querylist.Count(predicate);
            var entities = querylist.Where(predicate).Skip((condition.page - 1) * condition.pagesize).Take(condition.pagesize).AsNoTracking().ToList();
            var order_types = EnumHelper.EnumToList<OrderType>();
            var approve_status = EnumHelper.EnumToList<ApproveStatus>();
            var order_status = EnumHelper.EnumToList<OrderStatus>();
            foreach (var item in entities)
            {
                item.user = GetUserByMid(item.mid)?.name ?? "";
                item.order_status_name = order_status.FirstOrDefault(f => f.EnumValue.Equals(item.order_status))?.Description ?? "";
                item.order_type_name = order_types.FirstOrDefault(f => f.EnumValue.Equals(item.order_type))?.Description ?? "";
                item.approve_status_name = approve_status.FirstOrDefault(f => f.EnumValue.Equals(item.approve_status))?.Description ?? "";
                var approval = _context.siger_project_sparepart_order_approval.Where(q => q.order_id == item.id)
                    .OrderByDescending(q => q.approval_time)
                    .FirstOrDefault();
                item.approve_node = approval == null
                    ? item.approve_node
                    : item.approve_node + "" + approval.approval_time.ToString(ParameterConstant.DateFormat);
            }
            return new PagedCollectionResult<ResponseSparepartOrderInfo>(entities, count);
        }
    }
}
