package com.kxs.user.biz.task;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kxs.common.core.constant.CommonConstants;
import com.kxs.common.core.util.R;
import com.kxs.common.security.annotation.Inner;
import com.kxs.system.api.feign.RemoteOldService;
import com.kxs.user.api.model.KxsLeader;
import com.kxs.user.api.model.KxsPartner;
import com.kxs.user.api.model.KxsTotalDebt;
import com.kxs.user.api.model.KxsUserAmount;
import com.kxs.user.biz.mapper.*;
import com.kxs.user.biz.service.KxsTotalDebtService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;

/**
 * 用户模块定时任务
 *
 * @author 没秃顶的码农
 * @date 2024-03-13
 */
@RequiredArgsConstructor
@Slf4j
@RestController
@RequestMapping("user-job")
public class KxsUserTaskJob {

    private final KxsUserAmountLogMapper kxsUserAmountLogMapper;

    private final KxsTotalDebtService kxsTotalDebtService;

    private final KxsTotalDebtMapper kxsTotalDebtMapper;

    private final static String PREFIX_TABLE_NAME = "kxs_user_amount_log_";

    /**
     * 自动表创建任务
     * 每个月15号建立下个月的收支日志表
     */
    @Inner
    @GetMapping("/automaticTableCreationTasks")
    public void automaticTableCreationTasks() {
        String thisMoth = LocalDateTimeUtil.format(LocalDate.now().plusMonths(1L), DatePattern.SIMPLE_MONTH_PATTERN);
        kxsUserAmountLogMapper.automaticTableCreationTasks(CommonConstants.KXS_USER_AMOUNT_LOG_PREFIX + thisMoth);
    }

    /**
     * 每天凌晨执行：
     * 1.扫创客合伙人可提现额度，若有合伙人可提现额度，则扣除可提现额度，最大扣除金额=欠款总金额，扣除后减少欠款总金额，同时在前端增加扣除记录，备注为「预借款项还款」
     * 2.扫创客盟主可提现余额，若有盟主可提现余额，则扣除可提现余额，最大扣除金额=欠款总金额，扣除后减少欠款总金额，同时在前端增加扣除记录，备注为「预借款项还款」
     */
    @Inner
    @GetMapping("/userTotalDebtSub")
    public void userTotalDebtSub(){
        //查询所有欠款大于0的创客
        List<KxsTotalDebt> kxsTotalDebts = kxsTotalDebtMapper.selectList(Wrappers.<KxsTotalDebt>lambdaQuery().gt(KxsTotalDebt::getTotalDebt, BigDecimal.ZERO));
        for (KxsTotalDebt kxsTotalDebt : kxsTotalDebts) {
            //扣除合伙人
            kxsTotalDebtService.deductPartnerAmount(kxsTotalDebt);
            //扣除盟主
            kxsTotalDebtService.deductLeaderAmount(kxsTotalDebt);

        }

    }


}
