package com.hzy.project.task;

import com.hzy.common.enums.EDelFlag;
import com.hzy.project.business.balance.domain.UserBalance;
import com.hzy.project.business.balance.mapper.UserBalanceMapper;
import com.hzy.project.business.balance.service.IUserBalanceService;
import com.hzy.project.system.user.domain.User;
import com.hzy.project.system.user.mapper.UserMapper;
import com.hzy.project.system.user.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.hzy.common.utils.DateUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @program: 华智昀
 * @description: 按月创建用户结余。
 * @author: baolei
 * @create: 2026-01-04
 */
@Slf4j
@Component("createBalanceTask")
public class CreateBalanceTask
{

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserBalanceMapper userBalanceMapper;

    public void run() {

        log.info("按月创建用户结余===============>");

        String duration = DateFormatUtils.format(DateUtils.getNowDate(), "yyyyMM");
        String preDuration = DateFormatUtils.format(DateUtils.addMonths(DateUtils.getNowDate(),-1) , "yyyyMM");
        log.info("duration={}", duration);
        UserBalance condition = new UserBalance();
        condition.setDuration(duration);

        List<User> userList = userMapper.selectUserList(new User());
        for (User user : userList) {
            condition.setUserId(user.getUserId());
            List<UserBalance> balanceList = userBalanceMapper.selectUserBalanceList(condition);

            if (balanceList == null || balanceList.isEmpty()) {
                UserBalance preBalance = new UserBalance();
                preBalance.setUserId(user.getUserId());
                preBalance.setDuration(preDuration);

                List<UserBalance> preUserBalanceList = userBalanceMapper.selectUserBalanceList(preBalance);
                BigDecimal preClosingBalance = BigDecimal.ZERO;
                if (preUserBalanceList != null && !preUserBalanceList.isEmpty()) {
                    preClosingBalance = preUserBalanceList.get(0).getClosingBalance();
                }

                UserBalance userBalance = new UserBalance();
                userBalance.setUserId(user.getUserId());
                userBalance.setDuration(duration);
                userBalance.setOpeningBalance(preClosingBalance);
                userBalance.setIncome(BigDecimal.ZERO);
                userBalance.setPayment(BigDecimal.ZERO);
                userBalance.setClosingBalance(preClosingBalance);
                userBalance.setDelFlag(EDelFlag.NO.getVal());
                userBalance.setCreateTime(DateUtils.getNowDate());
                userBalance.setCreateBy("system");
                userBalanceMapper.insertUserBalance(userBalance);

            }
        }

        log.info("按月创建用户结余===============>");
    }
}
