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.ScheduleGroupRuleConfigService;
import jnpf.base.ActionResult;
import jnpf.model.attendance.dto.scheduling.ScheduleGroupRuleConfigDto;
import jnpf.model.attendance.vo.scheduling.ScheduleGroupRuleConfigVo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 智能排班：考勤组维度「排班规则配置」查询与保存（仅固定排班核心参数 + 划线排班参数）。
 * 控制器只负责打印接口入参与耗时（JNPF 日志规范）。
 *
 * @author xiaofeng
 * @since 2026-05-13
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/attendance/schedule")
@Tag(name = "排班规则配置", description = "考勤组固定排班与划线排班参数 GET/POST")
public class ScheduleGroupRuleConfigController {

    @Resource
    private ScheduleGroupRuleConfigService scheduleGroupRuleConfigService;

    /**
     * 获取排班规则配置。无表记录时各子块返回与表 DEFAULT 一致的默认结构。
     *
     * @param groupId 考勤组 ID
     * @return 配置
     */
    @SneakyThrows
    @Operation(summary = "获取排班规则配置")
    @GetMapping("/getRuleConfig")
    public ActionResult<ScheduleGroupRuleConfigVo> getRuleConfig(
            @RequestParam("groupId") @NotBlank(message = "考勤组ID不能为空") String groupId) {
        log.info("获取排班规则配置，入参=>{}", groupId);
        long st = System.currentTimeMillis();
        ScheduleGroupRuleConfigVo data = scheduleGroupRuleConfigService.getRuleConfig(groupId);
        log.info("获取排班规则配置，耗时=>{} 毫秒", System.currentTimeMillis() - st);
        return ActionResult.success(data);
    }

    /**
     * 保存排班规则配置。请求体根与各子块为 DTO；GET/POST 成功响应根与各子块均为 VO（JSON 字段名不变）。
     * 服务端在事务内 upsert 固定排班与划线排班参数表。
     *
     * @param dto 配置（{@code groupId}、{@code fixedScheduling}、{@code lineScheduling} 必填）
     * @return 保存后的配置
     */
    @SneakyThrows
    @Operation(summary = "保存排班规则配置")
    @PostMapping("/saveRuleConfig")
    public ActionResult<ScheduleGroupRuleConfigVo> saveRuleConfig(
            @RequestBody @Valid ScheduleGroupRuleConfigDto dto) {
        log.info("保存排班规则配置，入参=>{}", JSONObject.toJSON(dto));
        long st = System.currentTimeMillis();
        ScheduleGroupRuleConfigVo data = scheduleGroupRuleConfigService.saveRuleConfig(dto.getGroupId(), dto);
        log.info("保存排班规则配置，耗时=>{} 毫秒", System.currentTimeMillis() - st);
        return ActionResult.success(data);
    }
}
