
package com.pavis.admin.controller.system;

import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.RestController;
import com.pavis.admin.common.controller.BaseController;
import com.pavis.admin.system.enums.NoticeScopeEnum;
import com.pavis.admin.system.model.query.NoticeQuery;
import com.pavis.admin.system.model.req.NoticeReq;
import com.pavis.admin.system.model.resp.NoticeDetailResp;
import com.pavis.admin.system.model.resp.NoticeResp;
import com.pavis.admin.system.service.NoticeService;
import top.continew.starter.core.validation.ValidationUtils;
import top.continew.starter.extension.crud.annotation.CrudApi;
import top.continew.starter.extension.crud.annotation.CrudRequestMapping;
import top.continew.starter.extension.crud.enums.Api;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 公告管理 API
 *
 * 
 * @since 2023/8/20 10:55
 */
@Tag(name = "公告管理 API")
@RestController
@CrudRequestMapping(value = "/system/notice", api = {Api.PAGE, Api.GET, Api.CREATE, Api.UPDATE, Api.DELETE})
public class NoticeController extends BaseController<NoticeService, NoticeResp, NoticeDetailResp, NoticeQuery, NoticeReq> {

    @Override
    public void preHandle(CrudApi crudApi, Object[] args, Method targetMethod, Class<?> targetClass) throws Exception {
        super.preHandle(crudApi, args, targetMethod, targetClass);
        Api api = crudApi.value();
        if (!(Api.CREATE.equals(api) || Api.UPDATE.equals(api))) {
            return;
        }
        NoticeReq req = (NoticeReq)args[0];
        // 校验生效时间
        LocalDateTime effectiveTime = req.getEffectiveTime();
        LocalDateTime terminateTime = req.getTerminateTime();
        if (null != effectiveTime && null != terminateTime) {
            ValidationUtils.throwIf(terminateTime.isBefore(effectiveTime), "终止时间必须晚于生效时间");
        }
        // 校验通知范围
        if (NoticeScopeEnum.USER.equals(req.getNoticeScope())) {
            ValidationUtils.throwIfEmpty(req.getNoticeUsers(), "通知用户不能为空");
        }
    }
}