using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Extensions;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Response;

namespace Siger.Middlelayer.Repository.Repositories
{
    internal class SigerProjectBussineseUserRepository : ApiConfigRepositoryBase<siger_project_bussinese_user>, ISigerProjectBussineseUserRepository
    {
        private readonly ApiConfigDbContext _context;
        public SigerProjectBussineseUserRepository(ApiConfigDbContext context) : base(context)
        {
            _context = context;
        }

        public IPagedCollectionResult<ResponseBussineseUser> GetPagedList(int bussineseid, int userid, int projectId, int page, int pagesize)
        {
            var query = from q in _context.siger_project_bussinese_user
                        join u in _context.siger_project_user on q.userid equals u.mid
                        join u1 in _context.siger_project_user on q.updator equals u1.mid into uu1
                        from u1 in uu1.DefaultIfEmpty()
                        join c in _context.siger_wms_bussinese_contacts on q.bussineseid equals c.id
                        where q.status == (int)RowState.Valid && q.projectid == projectId
                        select new ResponseBussineseUser
                        {
                            id = q.id,
                            userid = q.userid,
                            bussineseid = q.bussineseid,
                            name = c.name,
                            username = u.name,
                            workcode = u.work_code,
                            mobile = u.mobile,
                            duns = c.duns,
                            updator = u1.name ?? "",
                            updatetime = q.updatetime.ToString(ParameterConstant.DateTimeFormat)
                        };

            Expression<Func<ResponseBussineseUser, bool>> bussineseExpression = q => true;
            if (bussineseid > 0)
            {
                bussineseExpression = q => q.bussineseid == bussineseid;
            }
            Expression<Func<ResponseBussineseUser, bool>> userExpression = q => true;
            if (userid > 0)
            {
                userExpression = q => q.userid == userid;
            }

            var predicate = bussineseExpression.And(userExpression);

            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<ResponseBussineseUser>(entities, totalCount);
        }
    }
}
