package cn.iocoder.yudao.module.system.job;

import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ElderlyInfoDO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ExpenseOrderDO;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ElderlyInfoMapper;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ExpenseOrderMapper;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class ExpenseOrderLockJob implements JobHandler {
    private final static Logger logger = LoggerFactory.getLogger(ElderContractUpdateJob.class);

    @Resource
    private ExpenseOrderMapper expenseOrderMapper;

    @Override
    @TenantIgnore
    public String execute(String param) throws Exception {
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(param, JsonObject.class);
        JsonElement tenantIdElement = jsonObject.get("tenantId");
        if (tenantIdElement == null) {
            return "参数错误，tenantId为空！";
        }
        StringBuilder msg = new StringBuilder();
        for (JsonElement jsonElement : tenantIdElement.getAsJsonArray()) {
            Long tenantId = jsonElement.getAsLong();
            logger.info("租户{},=====================账单锁定===================", tenantId);
            handleLockExpenseOrder(tenantId);
            msg.append("租户").append(tenantId).append("账单锁定情况");
        }
        return msg.toString();
    }
    private void handleLockExpenseOrder(Long tenantId){
        YearMonth currentYearMonth = YearMonth.now();
        List<ExpenseOrderDO> expenseOrderDOS = expenseOrderMapper.selectList(new LambdaQueryWrapperX<ExpenseOrderDO>()
                .eq(ExpenseOrderDO::getBillingMonth, currentYearMonth.toString())
                .eq(ExpenseOrderDO::getTenantId, tenantId));
        expenseOrderDOS = expenseOrderDOS.stream().map(e->e.setIsLock(Boolean.TRUE)).collect(Collectors.toList());
        expenseOrderMapper.updateBatch(expenseOrderDOS);
    }
}
