package cn.pluss.platform;

import cn.pluss.platform.entity.MerchantAuditRecord;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.MerchantAuditRecordMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author Djh
 * @since 2020-11-27
 */
public interface MerchantAuditRecordService extends IService<MerchantAuditRecord> {

    /**
     * 最大进件失败次数限制
     */
    int MAX_FAIL_COUNT = 3;

    /**
     * 获取商户进件失败次数
     * @param userId        用户id
     * @return              进件失败次数
     */
    Integer getFailCountByUserId(String userId);
    /**
     * 获取商户进件失败次数
     * @param merchantCode          商户code
     * @return                      进件失败次数
     */
    default Integer getFailCount(String merchantCode) {
        MerchantAuditRecordMapper mapper = (MerchantAuditRecordMapper) getBaseMapper();
        MerchantAuditRecord merchantAuditRecord = new MerchantAuditRecord();
        merchantAuditRecord.setMerchantCode(merchantCode);

        QueryWrapper<MerchantAuditRecord> queryWrapper = new QueryWrapper<>(merchantAuditRecord);
        queryWrapper.in("status", "5", "2");

        return mapper.selectCount(queryWrapper);
    }

    /**
     * 商户进件失败次数校验
     * @param merchantCode
     * @param msg
     */
    default void checkFailCount(String merchantCode, String msg) {
        Integer failCount = getFailCount(merchantCode);
        MsgException.check(failCount >= MAX_FAIL_COUNT, msg);
    }

    default MerchantAuditRecord getLastRecord(String merchantCode) {
        QueryWrapper<MerchantAuditRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("merchantCode", merchantCode);
        queryWrapper.orderByDesc("createTime");
        queryWrapper.last("limit 1");

        return getBaseMapper().selectOne(queryWrapper);
    }
}
