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

import com.tmerclub.cloud.api.payment.feign.AllinpayFeignClient;
import com.tmerclub.cloud.common.bean.PaySettlementConfig;
import com.tmerclub.cloud.common.cache.constant.MultishopCacheNames;
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.ServerResponseEntity;
import com.tmerclub.cloud.common.util.Json;
import com.tmerclub.cloud.multishop.mapper.ShopDetailMapper;
import com.tmerclub.cloud.multishop.service.ShopAllinpayService;
import com.tmerclub.cloud.platform.service.SysConfigService;
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 ShopAllinpayServiceImpl implements ShopAllinpayService {

    @Autowired
    private ShopDetailMapper shopDetailMapper;
    @DubboReference
    private AllinpayFeignClient allinpayFeignClient;
    @Autowired
    private SysConfigService sysConfigService;

    @Override
    @Cacheable(cacheNames = MultishopCacheNames.ALLINPAY_CONFIG_KEY, key = "'0'")
    public boolean getIsAllinpay() {
        String paySettlementConfigStr = sysConfigService.getValue(Constant.PAY_SETTLEMENT_CONFIG);
        PaySettlementConfig paySettlementConfig = Json.parseObject(paySettlementConfigStr, PaySettlementConfig.class);
        Integer paySettlementType = paySettlementConfig.getPaySettlementType();
        return Objects.equals(paySettlementType, 1);
    }

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

    @Override
    public void createAllinpayCompanyMember(Long shopId) {
        ShopAllinpayService shopAllinpayService = (ShopAllinpayService) AopContext.currentProxy();
        if (shopAllinpayService.getIsAllinpay()) {
            ServerResponseEntity<Void> serverResponse = allinpayFeignClient.batchCreateMember(Collections.singletonList(AllinpayConstant.SHOP + shopId));
            if (!serverResponse.isSuccess()) {
                throw new LuckException(serverResponse.getMsg());
            }
            // 更新店铺为已创建会员
            shopDetailMapper.updateShopIsCreate(Collections.singletonList(shopId));
        }
    }
}
