package com.tmerclub.cloud.user.task;

import com.tmerclub.cloud.api.payment.constant.PaySysType;
import com.tmerclub.cloud.api.payment.feign.AllinpayFeignClient;
import com.tmerclub.cloud.api.platform.feign.ConfigFeignClient;
import com.tmerclub.cloud.api.user.dto.UserExtensionDTO;
import com.tmerclub.cloud.user.service.UserExtensionService;
import com.tmerclub.cloud.user.vo.UserExtensionVO;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * 通联定时任务
 * @author gaozijie
 * @date 2023-11-10
 */
@Component
public class AllinpayTask {

    private static final Logger log = LoggerFactory.getLogger(AllinpayTask.class);

    @Autowired
    private UserExtensionService userExtensionService;

    @DubboReference
    private ConfigFeignClient configFeignClient;
    @DubboReference
    private AllinpayFeignClient allinpayFeignClient;

    /**
     * 创建通联会员
     */
    @XxlJob("createAllinpayMember")
    public void createAllinpayMember() {
        log.info("(定时)用户创建通联会员...");
        // 查询是否开启通联支付
        Integer paySysType = configFeignClient.getPaySysType().getData();
        if (!Objects.equals(paySysType, PaySysType.ALLINPAY.value())) {
            return;
        }
        // 查询未创建会员用户信息
        UserExtensionDTO userExtensionDTO = new UserExtensionDTO();
        userExtensionDTO.setAllinpayCreate(0);
        List<UserExtensionVO> userExtensions = userExtensionService.listUserExtensions(userExtensionDTO);
        if (CollectionUtils.isEmpty(userExtensions)) {
            return;
        }
        // 向通联创建会员
        List<String> bizUserIds = userExtensions.stream().map(x -> x.getUserId().toString()).toList();
        Integer successCount = allinpayFeignClient.batchCreatePersonalMember(bizUserIds).getData();
        log.info("(定时)用户创建通联会员 - 成功：{}，失败:{}", successCount, bizUserIds.size()-successCount);
    }
}
