package com.red.circle.other.app.command.admintask;

import com.red.circle.other.domain.admintask.AdminTaskRecord;
import com.red.circle.other.domain.admintask.AdminTaskType;
import com.red.circle.other.domain.gateway.AdminTaskGateway;
import com.red.circle.other.app.dto.cmd.AdminTaskQueryCmd;
import com.red.circle.other.infra.database.mongo.service.team.TeamBillCycleUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 管理员任务查询执行器
 *
 * @author tf
 * @date 2025-11-25
 */
@Component
@RequiredArgsConstructor
public class AdminTaskQueryCmdExe {

    private final AdminTaskGateway adminTaskGateway;

    public List<AdminTaskRecord> execute(AdminTaskQueryCmd cmd) {
        LocalDate cycleStartDate = cmd.getCycleStartDate() != null ? cmd.getCycleStartDate() :
                LocalDate.parse(TeamBillCycleUtils.getCalcBillBelong().toString(), DateTimeFormatter.ofPattern("yyyyMMdd"));
        List<AdminTaskRecord> records = adminTaskGateway.findByUserIdAndCycle(cmd.getUserId(), cycleStartDate);
        Map<String, AdminTaskRecord> taskRecordMap = records.stream().collect(Collectors.toMap(AdminTaskRecord::getTaskType, e -> e));

        List<AdminTaskRecord> recordList = new ArrayList<>();
        for (AdminTaskType value : AdminTaskType.values()) {
            AdminTaskRecord record = taskRecordMap.get(value.getCode());
            if (record != null) {
                recordList.add(record);
            }
        }
        return recordList;
    }

    /**
     * 查询单个任务
     */
    public AdminTaskRecord findByUserIdAndTaskTypeAndCycle(Long userId, String taskType, LocalDate cycleStartDate) {
        LocalDate queryDate = cycleStartDate != null ? cycleStartDate :
                LocalDate.parse(TeamBillCycleUtils.getCalcBillBelong().toString(), DateTimeFormatter.ofPattern("yyyyMMdd"));
        return adminTaskGateway.findByUserIdAndTaskTypeAndCycle(userId, taskType, queryDate);
    }

}
