using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XYY.Core.Standard.Data.Infrastructure;
using XYY.Model.Standard.DingTalk;
using Dapper;
using XYY.Common.Standard;

namespace XYY.Data.Standard.DingTalk
{
    public interface IDingTalk_PaymentRepository : IBaseRepository<DingTalk_Payment>
    {
        Task insertDetail(int PaymentId, List<DingTalk_PaymentDetail> details);
        Task<List<DingTalk_PaymentOptions>> GetAllPaymentOptions();
        Task<bool> BatchUpdateOptionsEntiy(List<DingTalk_PaymentOptions> models);
        Task insertOptions(List<DingTalk_PaymentOptions> models);
        Task<PageResult<DingTalk_Payment>> QueryPage(QueryModel qm);
        Task<List<DingTalk_PaymentOptions>> GetOptionsByType(int OptionType);
        Task<List<DingTalk_PaymentDetail>> GetPaymentDetails(int PaymentId);
    }
    public class DingTalk_PaymentRepository : BaseRepository<DingTalk_Payment>, IDingTalk_PaymentRepository
    {
        public DingTalk_PaymentRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
        {

        }

        public async Task insertDetail(int PaymentId, List<DingTalk_PaymentDetail> details)
        {
            if (details.Count != 0)
            {
                string deleteSql = $" delete DingTalk_PaymentDetail where PaymentId = {PaymentId} ";
                await _unitOfWork.ExecuteAsync(deleteSql);
                details.ForEach(x => { x.PaymentId = PaymentId; });
                await _unitOfWork.BulkToDBAsync(details);
            }
        }
        public async Task<List<DingTalk_PaymentOptions>> GetAllPaymentOptions()
        {
            var result = await _unitOfWork.QueryAsync<DingTalk_PaymentOptions>();
            return result.ToList();
        }

        public async Task<bool> BatchUpdateOptionsEntiy(List<DingTalk_PaymentOptions> models)
        {
            bool result = true;
            try
            {
                //比逐条更新稍微快点
                string sql = " update DingTalk_PaymentOptions set DName = @DName,LevelNum=@LevelNum,DParentId=@DParentId  where DId = @DId ";
                await _unitOfWork.ExecuteAsync(sql, models);
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;


        }
        public async Task insertOptions(List<DingTalk_PaymentOptions> models)
        {
            await _unitOfWork.BulkToDBAsync(models);
        }
        public async Task<PageResult<DingTalk_Payment>> QueryPage(QueryModel qm)
        {
            #region 基础sql
            int Option = 0;

            var qmCategories = qm.QueryParamer.Where(x => x.Filed == "Option").FirstOrDefault();
            if (qmCategories != null && !string.IsNullOrEmpty(qmCategories.Value)) { Option = Convert.ToInt32(qmCategories.Value.Split(',')[1]); qm.QueryParamer.Remove(qmCategories); }

            StringBuilder sb = new StringBuilder();
            sb.Append(" select * from DingTalk_Payment(nolock) where 1=1 ");
            string where = _unitOfWork.GetWhere(qm.QueryParamer);
            if (Option > 0)
            {
                where += $" and Id in (select distinct PaymentId from DingTalk_PaymentDetail where  Categories2_Id={Option}) ";
            }
            sb.Append(where);
            #endregion
            #region 分页
            StringBuilder pager = new StringBuilder();
            string sortString = " Id desc";
            pager.Append($@"select * from (select Row_Number()over(order by  {sortString})rowId,*
            from ({sb.ToString()})a where 1=1 ) T where rowId between {(qm.PageIndex - 1) * qm.PageSize + 1} and {qm.PageSize * qm.PageIndex};");
            pager.Append(@$"select count(0)TotalCount from (select Row_Number()over(order by  {sortString})rowId,*
            from({sb.ToString()})a where 1 = 1 ) T where 1=1");
            #endregion
            #region 取值
            string sql = pager.ToString();

            var dr = await _unitOfWork.Connection.QueryMultipleAsync(sql, null, _unitOfWork.Transaction);
            //需要注意读取顺序，依据语句执行顺序进行读取
            var pageResult = new PageResult<DingTalk_Payment>()
            {
                Result = dr.Read<DingTalk_Payment>(),
                PageIndex = qm.PageIndex,
                PageSize = qm.PageIndex,
                TotalCount = dr.Read<int>().FirstOrDefault()
            };
            #endregion
            return pageResult;
        }
        public async Task<List<DingTalk_PaymentOptions>> GetOptionsByType(int OptionType)
        {
            var result = await _unitOfWork.QueryAsync<DingTalk_PaymentOptions>(x => x.OptionType == (OptionTypeEnum)OptionType);
            return result.ToList();
        }
        public async Task<List<DingTalk_PaymentDetail>> GetPaymentDetails(int PaymentId)
        {
            var result = await _unitOfWork.QueryAsync<DingTalk_PaymentDetail>(x => x.PaymentId == PaymentId);
            return result.ToList();
        }
    }
}
