package com.gitee.sop.admin.service.isv;

import com.gitee.fastmybatis.core.support.BaseLambdaService;
import com.gitee.sop.admin.common.exception.BizException;
import com.gitee.sop.admin.dao.entity.IsvMerchant;
import com.gitee.sop.admin.dao.mapper.IsvMerchantMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;


/**
 * @author tanghc
 */
@Service
public class IsvMerchantService extends BaseLambdaService<IsvMerchant, IsvMerchantMapper> {

    public Map<String, String> getAppMerchantCode(Collection<String> appIds) {
        if (CollectionUtils.isEmpty(appIds)) {
            return Collections.emptyMap();
        }
        return this.query()
                .in(IsvMerchant::getAppId, appIds)
                .map(IsvMerchant::getAppId, IsvMerchant::getMerchantCode);
    }

    public int setMerchant(String appId, String merchantCode) {
        checkMerchantCode(merchantCode);

        IsvMerchant isvMerchant = this.get(IsvMerchant::getAppId, appId);
        if (isvMerchant == null) {
            isvMerchant = new IsvMerchant();
            isvMerchant.setAppId(appId);
            isvMerchant.setMerchantCode(merchantCode);
            return this.save(isvMerchant);
        } else {
            isvMerchant.setMerchantCode(merchantCode);
            return this.update(isvMerchant);
        }
    }

    private void checkMerchantCode(String merchantCode) {
        // 检查商户code是否合法，不合法抛出 new BizException();
        boolean exist = checkMerchantExist(merchantCode);
        if (!exist) {
            throw new BizException("商户不存在");
        }
    }

    private boolean checkMerchantExist(String merchantCode) {
        return true;
    }

}