package com.hzs.member.account.provider;

import cn.hutool.core.collection.CollUtil;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.utils.ThreadUtils;
import com.hzs.common.domain.system.config.BdWithdrawal;
import com.hzs.member.account.IMemberJobServiceApi;
import com.hzs.member.account.service.ICuMemberAccountDetailService;
import com.hzs.member.account.service.ICuMemberWithdrawService;
import com.hzs.system.config.IWithdrawalServiceApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.concurrent.ExecutorService;

/**
 * 会员模块定时任务服务提供
 */
@Slf4j
@DubboService
public class IMemberJobServiceProvider implements IMemberJobServiceApi {

    @Autowired
    private ICuMemberAccountDetailService memberAccountDetailService;
    @Autowired
    private ICuMemberWithdrawService memberWithdrawService;

    @DubboReference
    IWithdrawalServiceApi withdrawalServiceApi;

    @Override
    public R insertAccountDetail() {
        try {
            memberAccountDetailService.insertAccountDetail();
        } catch (Exception e) {
            log.info("定时插入账户详情数据失败：", e);
            return R.fail(e.getMessage());
        }
        return R.ok();
    }


    @Override
    public R automaticWithdrawal() {
        //查询自动配置的信息
        List<BdWithdrawal> withdrawalConfigs = withdrawalServiceApi.queryWithdrawalByIsAuto().getData();
        if (CollUtil.isNotEmpty(withdrawalConfigs)) {
            ExecutorService executorService = ThreadUtils.executorService;
            for (BdWithdrawal withdrawal : withdrawalConfigs) {
                Integer pkCountry = withdrawal.getPkCountry();
                executorService.submit(() -> {
                    try {
                        log.info("自动提现国家{}", pkCountry);
                        memberWithdrawService.autoWithdraw(withdrawal);
                    } catch (Exception e) {
                        log.info("自动提现国家{} 报错：", pkCountry, e);
                    }
                });
            }
        }
        return R.ok();
    }

}
