package cn.com.ctop.job.kuaishou.handler;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.kuaishou.modules.app.entity.KuaishouAccountBalanceBudget;
import cn.com.ctop.kuaishou.modules.app.service.IKuaishouAccountBalanceBudgetService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouAccountBudgetService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouInterfaceService;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class KuaiShouBudgetJob {
    @Autowired
    private IKuaishouAccountBalanceBudgetService balanceBudgetService;
    @Autowired
    private IKuaishouInterfaceService iKuaishouInterfaceService;
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IKuaishouAccountBudgetService accountBudgetService;

    static ExecutorService executorService = Executors.newFixedThreadPool(8);

    /**
     * 定时更新快手账户余额和预算
     *
     * @throws
     */
    @XxlJob("kuaiShouBudgetJob")
    public void execute() throws Exception {
        if (DateUtils.getNowHour() == 2) {
            //每日凌晨2点将预算全部置为无效，避免已关闭的账户留有僵尸数据。
            balanceBudgetService.updateAllIsInvalidState();
        }
        List<CtopOauthToken> tokens = tokenService.selectKuaiShouToken();
        tokens.forEach(token -> executorService.submit(() -> {
            KuaishouAccountBalanceBudget budget = new KuaishouAccountBalanceBudget();
            JSONObject fundJson = iKuaishouInterfaceService.fundGet(token);
            JSONObject accountBudget = accountBudgetService.getAccountBudget(token);
            if (!Check.isNull(accountBudget) && !Check.isNull(fundJson)) {
                budget.setBalance(fundJson.getBigDecimal("balance"));
                budget.setDayBudget(accountBudget.getBigDecimal("day_budget").divide(new BigDecimal(1000)).setScale(2, RoundingMode.HALF_UP));
                budget.setDayBudgetSchedule(accountBudget.getString("day_budget_schedule"));
                budget.setAccountId(token.getAccountId());
                budget.setState(1);
                balanceBudgetService.replace(budget);
            }
        }));
        XxlJobHelper.log("定时更新快手账户余额和预算完成");
    }
}

