package jnpf.attendance.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jnpf.attendance.service.SmartPreScheduleService;
import jnpf.base.ActionResult;
import jnpf.exception.HandleException;
import jnpf.exception.QueryException;
import jnpf.model.attendance.dto.scheduling.PreScheduleTableQueryDto;
import jnpf.model.attendance.vo.scheduling.PreScheduleTableVo;
import jnpf.util.StringUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * AI 智能排班确认：预排班主表生成与提交保存接口层。
 *
 * @author xiaofeng
 * @create 2026-05-13
 */
@Slf4j
@RestController
@RequestMapping("/attendance/smartSchedule")
@Tag(name = "智能排班预排班", description = "预排班主表生成与整包保存")
public class SmartPreScheduleController {

    @Resource
    private SmartPreScheduleService smartPreScheduleService;

    /**
     * 预排班生成主表：返回 rows，每行含 posts、stations 预览。
     *
     * @param dto 日期范围、按日预估营业额、人效目标、考勤组
     * @return 主表数据
     */
    @SneakyThrows
    @Operation(summary = "预排班功能")
    @PostMapping("/preScheduling")
    public ActionResult<PreScheduleTableVo> buildTable(@RequestBody @Valid PreScheduleTableQueryDto dto) {
        log.error("预排班生成主表，入参=>{}", JSONObject.toJSON(dto));
        long startMs = System.currentTimeMillis();
        PreScheduleTableVo data = smartPreScheduleService.buildPreScheduleTable(dto);
        log.error("预排班生成主表，耗时=>{}毫秒", System.currentTimeMillis() - startMs);
        ActionResult<PreScheduleTableVo> result = ActionResult.success(data);
        if (data != null && StringUtil.isNotBlank(data.getMsg())) {
            result.setMsg(data.getMsg());
        }
        return result;
    }

    /**
     * 预排班主表提交保存：按 rows 过滤 Redis 中 byEmployee 并写回，返回 redisKeySuffix。
     *
     * @param vo groupId + rows
     * @return redisKeySuffix（考勤组:日期区间，不含租户）
     */
    @Operation(summary = "预排班主表提交保存")
    @PostMapping("/saveSchedul")
    public ActionResult<String> saveTable(@RequestBody @Valid PreScheduleTableVo vo)
            throws HandleException, QueryException {
        log.error("预排班主表提交保存，入参=>{}", JSONObject.toJSON(vo));
        long startMs = System.currentTimeMillis();
        String redisKeySuffix = smartPreScheduleService.savePreScheduleTable(vo);
        log.error("预排班主表提交保存，耗时=>{}毫秒", System.currentTimeMillis() - startMs);
        return ActionResult.success(redisKeySuffix);
    }
}
