package com.ruoyi.ss.mchApply.service.impl;

import com.ruoyi.common.core.domain.BaseValidator;
import com.ruoyi.common.core.domain.ValidateResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.ss.mchApply.domain.MchApplyBO;
import com.ruoyi.ss.mchApply.domain.MchApplyQuery;
import com.ruoyi.ss.mchApply.domain.enums.MchApplyStatus;
import com.ruoyi.ss.mchApply.service.IMchApplyService;
import com.ruoyi.ss.mchApply.service.MchApplyValidator;
import com.ruoyi.ss.user.service.UserValidator;
import com.ruoyi.system.service.IVerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author wjh
 * 2024/4/28
 */
@Service
public class MchApplyValidatorImpl extends BaseValidator implements MchApplyValidator {

    @Autowired
    private IVerificationCodeService verificationCodeService;

    @Autowired
    private IMchApplyService mchApplyService;

    @Autowired
    private UserValidator userValidator;

    /**
     * 前台新增前校验
     *
     * @param data
     * @return
     */
    @Override
    public ValidateResult preInsertByApp(MchApplyBO data) {
        if (data == null) {
            return error("数据不能为空");
        }

        if (userValidator.isMch(SecurityUtils.getUserId())) {
            return error("商家不允许重复申请");
        }

        // 判断是否已提交过
        if (this.hasApprovingApply(SecurityUtils.getUserId())) {
            return error("用户的申请正在审核中，请勿重复提交");
        }

        return success();
    }

    /**
     * 用户是否有正在审核中的申请
     * @param userId
     * @return
     */
    private boolean hasApprovingApply(Long userId) {
        if (userId == null) {
            return true;
        }
        MchApplyQuery query = new MchApplyQuery();
        query.setUserId(userId);
        query.setStatus(MchApplyStatus.APPROVING.getStatus());
        return mchApplyService.selectCount(query) > 0;
    }
}
