package com.ruoyi.bst.account.service.impl;

import com.ruoyi.bst.account.domain.AccountQuery;
import com.ruoyi.bst.account.domain.AccountVO;
import com.ruoyi.bst.account.mapper.AccountMapper;
import com.ruoyi.bst.account.service.AccountValidator;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.collection.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Objects;

@Service
public class AccountValidatorImpl implements AccountValidator {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public boolean canDelAll(List<Long> ids) {
        return canView(ids);
    }

    private boolean canView(List<Long> ids) {
        if (CollectionUtils.isEmptyElement(ids)) {
            return true;
        }
        AccountQuery query = new AccountQuery();
        query.setIds(ids);
        List<Long> idList = accountMapper.selectIdList(query);
        return new HashSet<>(idList).containsAll(ids);
    }

    @Override
    public void validate(Long id) {
        AccountVO account = accountMapper.selectAccountById(id);
        ServiceUtil.assertion(account == null, "ID为" + id + "的收款账户不存在");
        ServiceUtil.assertion(account.getUserIsReal() == null || !account.getUserIsReal(), "ID为%s的用户未实名", account.getUserId());
        ServiceUtil.assertion(!Objects.equals(account.getUserRealName(), account.getName()), "收款人姓名与实名姓名不符");
        ServiceUtil.assertion(!Objects.equals(account.getUserRealIdCard(), account.getIdCard()), "收款人身份证号码与实名身份证号码不符");
        ServiceUtil.assertion(!Objects.equals(account.getUserRealPhone(), account.getMobile()), "收款人手机号与实名手机号不符");

        // 查重
        ServiceUtil.assertion(this.isRepeat(account), "ID为%s的收款账户重复", account.getId());
    }

    private boolean isRepeat(AccountVO account) {
        if (account.getType() == null || StringUtils.isBlank(account.getNo())) {
            return false;
        }
        AccountQuery query = new AccountQuery();
        query.setType(account.getType());
        query.setNo(account.getNo());
        query.setExcludeId(account.getId());
        return accountMapper.selectCount(query) > 0;
    }
}
