using Mall.Model.Extend.User;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Mall.Model.Entity.User;
using VT.FW.DB.Dapper;

namespace Mall.Repository.User
{
    /// <summary>
    /// 商户用户仓储层
    /// </summary>
    public partial  class RB_Member_UserRepository2 : BaseRepository<RB_Member_User>
    {
        /// <summary>
        /// 获取商户用户列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Member_User_Extend> GetMemberUserListExtRepository(RB_Member_User_Extend dmodel)
        {
            DynamicParameters dynamicParameters = new DynamicParameters();
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat(@"
SELECT  IFNULL(B.Id,0) AS ShopId,IFNULL(B.Name,'') AS ShopName,A.* 
FROM rb_member_user AS A LEFT JOIN rb_smallshops_info AS B ON A.Id=B.UserId
WHERE 1=1
"); 
            if (dmodel.TenantId > 0)
            {
                builder.AppendFormat($@" and A.{nameof(RB_Member_User.TenantId)}={dmodel.TenantId}");
            }
            if (dmodel.MallBaseId > 0)
            {
                builder.AppendFormat($@" and A.{nameof(RB_Member_User.MallBaseId)}={dmodel.MallBaseId}");
            }
            if (!string.IsNullOrEmpty(dmodel.Name.Trim()))
            {
                builder.AppendFormat($@" and A.Name like @Name ");
                dynamicParameters.Add("Name", "%" + dmodel.Name.Trim() + "%");
            }
            return Get<RB_Member_User_Extend>(builder.ToString(), dynamicParameters).ToList();
        }

        /// <summary>
        /// 统计员工登录【总人数，内部员工人数，领队导游人数】
        /// </summary>
        /// <param name="dmodel">查询条件</param>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <returns></returns>
        public List<RB_Member_User_Extend> GetMemberUserStatisticsRepository(RB_Member_User_Extend dmodel, string startDate, string endDate)
        {
            StringBuilder where = new StringBuilder();
            if (dmodel.TenantId > 0)
            {
                where.AppendFormat($@" and A.{nameof(RB_Member_User.TenantId)}={dmodel.TenantId}");
            }
            if (dmodel.MallBaseId > 0)
            {
                where.AppendFormat($@" and A.{nameof(RB_Member_User.MallBaseId)}={dmodel.MallBaseId}");
            }
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat(@"
SELECT A.SuperiorId,A.PostId,B.LoginTime AS CreateDate
FROM rb_member_user AS A
INNER JOIN
(
		SELECT UserId,DATE_FORMAT(LoginTime,'%Y/%m/%d') AS LoginTime
		FROM rb_login_log
		WHERE  LoginTime>='{0}'  AND LoginTime<='{1} 23:59:59'
    GROUP BY UserId,DATE_FORMAT(LoginTime,'%Y/%m/%d')
) AS B ON A.Id=B.UserId
WHERE 1=1 {2}
", startDate,endDate, where.ToString());
            var list = Get<RB_Member_User_Extend>(builder.ToString()).ToList();
            return list;
        }
    }
}
