using System.Collections.Generic;
using System.Linq;
using System.Text;
using ASHermed.SinoInterface.Api.ContractModel.BlindBox.Entity;
using ASHermed.SinoInterface.Api.IRepository.BlindBox;
using System.Threading.Tasks;
using ASHermed.SinoInterface.Api.ContractModel.BlindBox.Dto;
using ASHermed.SinoInterface.Repository.MySql;

namespace ASHermed.SinoInterface.Api.MySqlRepository.BlindBox
{
    public class BlindBoxRepository : BaseRepositoryToASHermed_SinoInterface<PubBlindBox>, IBlindBoxRepository
    {
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="pubBlindBox"></param>
        /// <returns></returns>
        public async Task<int> AddAsync(PubBlindBox pubBlindBox)
        {
            const string sql = " insert into pub_blindbox (UserId,HosId,CreateTime) values(@UserId,@HosId,@CreateTime) ";
            var result = await ExecuteAsync(sql, pubBlindBox);
            return result;
        }

        /// <summary>
        /// 查询用户的领取次数
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<int> GetCountByUserIdAsync(int userId)
        {
            const string sql = "select count(1) from pub_blindbox where UserId=@userId ";
            var result = await QueryAsync<int>(sql, new { userId });

            return result.FirstOrDefault();
        }

        /// <summary>
        /// 列表查询
        /// </summary>
        /// <param name="hosId">诊所id</param>
        /// <param name="searchText"></param>
        /// <returns></returns>
        public async Task<List<BlindBoxDto>> QueryAsync(int hosId, string searchText = null)
        {
            var sqlStringBuilder = new StringBuilder();
            sqlStringBuilder.Append(@"SELECT
                                      	box.Id AS Id,
                                      	box.HosId AS HosId,
                                      	box.CreateTime AS CreateTime,
                                      	box.UserId AS UserId,
                                      	u.NICK_NAME AS UserName,
                                      	u.PHONE AS Phone
                                      FROM
                                      	pub_blindbox AS box
                                      	LEFT JOIN pub_user_info AS u ON box.UserId = u.Id 
                                      WHERE box.HosId=@hosId ");

            if (!string.IsNullOrEmpty(searchText))
            {
                sqlStringBuilder.Append("AND ( u.NICK_NAME LIKE CONCAT( '%', @searchText, '%' ) OR u.PHONE LIKE CONCAT( '%', @searchText, '%' ) )  ");
            }

            sqlStringBuilder.Append(" ORDER BY box.CreateTime DESC ");

            var result = await QueryAsync<BlindBoxDto>(sqlStringBuilder.ToString(), new { hosId, searchText });

            return result?.ToList();
        }
    }
}