package com.jeequan.jeepay.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.validate.Add;
import com.jeequan.jeepay.core.validate.Update;
import com.jeequan.jeepay.db.entity.TransferInterfaceConfigEntity;
import com.jeequan.jeepay.db.entity.TransferInterfaceDefineEntity;
import com.jeequan.jeepay.service.mapper.TransferInterfaceDefineMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

import javax.validation.ConstraintViolation;
import java.util.Date;
import java.util.Set;

/**
 * <p>
 * 转账功能接口定义 服务实现类
 * </p>
 *
 * @author deng
 * @since 2024-04-25
 */
@Service
public class TransferInterfaceDefineService extends ServiceImpl<TransferInterfaceDefineMapper, TransferInterfaceDefineEntity> {

    @Autowired
    private LocalValidatorFactoryBean validatorFactoryBean;

    @Lazy @Autowired
    private TransferInterfaceDefineService self;

    @Autowired
    private TransferInterfaceConfigService instanceService;

    public TransferInterfaceDefineEntity getByCode(String ifCode) {
        return lambdaQuery().eq(TransferInterfaceDefineEntity::getTransIfCode, ifCode)
                .one();
    }

    @MethodLog(remark = "保存转账功能接口定义数据")
    public boolean saveDefine(TransferInterfaceDefineEntity entity) {
        if (entity.getState() == null) {
            entity.setState(CS.YES);
        }

        Set<ConstraintViolation<TransferInterfaceDefineEntity>> validate;
        if (entity.getId() == null) {
            validate = validatorFactoryBean.validate(entity, Add.class);
        } else {
            entity.setUpdateTime(new Date());
            validate = validatorFactoryBean.validate(entity, Update.class);
        }

        if (!validate.isEmpty()) {
            StringBuilder validError = new StringBuilder();
            validate.forEach(item -> {
                validError.append(item.getMessage()).append(",");
            });
            throw new BizException(validError.subSequence(0, validError.length() - 1).toString());
        }

        return self.saveOrUpdate(entity);
    }

    public boolean removeDefine(Long id) {
        TransferInterfaceDefineEntity existData = getById(id);
        if (existData == null) {
            return false;
        }

        long count = instanceService.lambdaQuery()
                .eq(TransferInterfaceConfigEntity::getTransIfCode, existData.getTransIfCode())
                .count();

        if (count > 0) {
            throw new BizException("存在通道示例，删除失败");
        }

        return self.removeById(id);
    }
}
