package com.jeequan.jeepay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.TransferSubjectEntity;
import com.jeequan.jeepay.service.mapper.TransferInterfaceConfigMapper;
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 TransferInterfaceConfigService extends ServiceImpl<TransferInterfaceConfigMapper, TransferInterfaceConfigEntity> {

    @Autowired
    private LocalValidatorFactoryBean validatorFactoryBean;

    @Autowired
    private TransferSubjectService subjectService;

    @Lazy
    @Autowired
    private TransferInterfaceConfigService self;

    public TransferInterfaceConfigEntity getTransferConfig(String transIfCode, String isvNo) {
        return lambdaQuery().eq(TransferInterfaceConfigEntity::getTransIfCode, transIfCode)
                .eq(TransferInterfaceConfigEntity::getIsvNo, isvNo)
                .one();
    }

    public TransferInterfaceConfigEntity getTransferConfig(String transIfCode, String isvNo, String infoType) {
        return lambdaQuery().eq(TransferInterfaceConfigEntity::getTransIfCode, transIfCode)
                .eq(TransferInterfaceConfigEntity::getIsvNo, isvNo)
                .eq(TransferInterfaceConfigEntity::getInfoType, infoType)
                .one();
    }

    @MethodLog(remark = "保存转账功能接口实例数据")
    public boolean saveConfig(TransferInterfaceConfigEntity entity) {
        if (entity.getState() == null) {
            entity.setState(CS.YES);
        }

        if (CS.SYS_ROLE_TYPE.ISV.equalsIgnoreCase(entity.getInfoType())) {
            entity.setIsvNo(entity.getInfoId());
        }

        TransferInterfaceConfigEntity existData = getTransferConfig(entity.getTransIfCode(), entity.getIsvNo());

        if (existData != null) {
            entity.setId(existData.getId());

            String transIfParams = existData.getTransIfParams();
            JSONObject configData = JSON.parseObject(transIfParams);
            String newIfParams = entity.getTransIfParams();
            JSONObject newConfigData = JSON.parseObject(newIfParams);
            configData.putAll(newConfigData);
            entity.setTransIfParams(configData.toString());
        }

        Set<ConstraintViolation<TransferInterfaceConfigEntity>> 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 removeConfig(Long id) {
        TransferInterfaceConfigEntity existData = getById(id);
        if (existData == null) {
            return false;
        }

        long count = subjectService.lambdaQuery()
                .eq(TransferSubjectEntity::getTransIfCode, existData.getTransIfCode())
                .eq(TransferSubjectEntity::getIsvNo, existData.getIsvNo()).count();

        if (count > 0) {
            throw new BizException("已存在相关转账方或被发起方，删除失败");
        }

        return self.removeById(id);
    }
}
