package com.tmerclub.cloud.supplier.service.impl;

import com.tmerclub.cloud.api.payment.feign.AllinpayFeignClient;
import com.tmerclub.cloud.api.platform.feign.ConfigFeignClient;
import com.tmerclub.cloud.common.bean.PaySettlementConfig;
import com.tmerclub.cloud.common.cache.constant.SupplierCacheNames;
import com.tmerclub.cloud.common.constant.AllinpayConstant;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.response.ResponseEnum;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.util.Json;
import com.tmerclub.cloud.supplier.mapper.SupplierDetailMapper;
import com.tmerclub.cloud.supplier.service.SupplierAllinpayService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Objects;

/**
 * @author TRACK
 */
@Service
public class SupplierAllinpayServiceImpl implements SupplierAllinpayService {

    @DubboReference
    private ConfigFeignClient configFeignClient;
    @Autowired
    private SupplierDetailMapper supplierDetailMapper;
    @DubboReference
    private AllinpayFeignClient allinpayFeignClient;

    @Override
    @Cacheable(cacheNames = SupplierCacheNames.ALLINPAY_CONFIG_KEY, key = "'0'")
    public boolean getIsAllinpay() {
        // 获取是否开启通联支付
        ServerResponseEntity<String> response = configFeignClient.getConfig(Constant.PAY_SETTLEMENT_CONFIG);
        if (!response.isSuccess()) {
            throw new LuckException(ResponseEnum.EXCEPTION);
        }
        PaySettlementConfig paySettlementConfig = Json.parseObject(response.getData(), PaySettlementConfig.class);
        return Objects.equals(paySettlementConfig.getPaySettlementType(), 1);
    }

    @Override
    @CacheEvict(cacheNames = SupplierCacheNames.ALLINPAY_CONFIG_KEY, key = "'0'")
    public void deleteAllinpayCache() {
    }

    @Override
    public void createAllinpayCompanyMember(Long supplierId) {
        SupplierAllinpayService supplierAllinpayService = (SupplierAllinpayService) AopContext.currentProxy();
        if (supplierAllinpayService.getIsAllinpay()) {
            ServerResponseEntity<Void> serverResponse = allinpayFeignClient.batchCreateMember(Collections.singletonList(AllinpayConstant.SUPPLIER + supplierId));
            if (!serverResponse.isSuccess()) {
                throw new LuckException(serverResponse.getMsg());
            }
            // 更新供应商为已创建会员
            supplierDetailMapper.updateSupplierIsCreate(Collections.singletonList(supplierId));
        }
    }
}
