package org.jeecg.modules.app.controller.weixin;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.app.vo.weixin.NotificationRequest;
import org.jeecg.modules.app.vo.weixin.NotificationResult;
import org.jeecg.modules.app.weixinService.WechatNotificationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.validation.Valid;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/api/wechat/notification")
public class WechatNotificationController {
    private static final Logger logger = LoggerFactory.getLogger(WechatNotificationController.class);
    private final WechatNotificationService notificationService;

    public WechatNotificationController(WechatNotificationService notificationService) {
        this.notificationService = notificationService;
    }

    @PostMapping("/send")
    public ResponseEntity<Result<String>> sendNotification(@Valid @RequestBody NotificationRequest request) {
        logger.info("发送请求参数："+JSONObject.toJSONString(request));
        JSONObject data = new JSONObject();
        // 根据模板内容设置数据项
        data.put("time3", new JSONObject().fluentPut("value", "19:00"));
        data.put("thing4", new JSONObject().fluentPut("value", "观山湖区第一中学"));
        data.put("thing11", new JSONObject().fluentPut("value", "尽快到场,准备上课"));
        request.setTemplateId("Yi1Z1IKRwgF6-mpiFcOUTvavc4TUAsfsLynK_3Yu350");
        request.setData(data);
        NotificationResult result = notificationService.sendSubscribeMessage(request);
        if (result.isSuccess()) {
            logger.info("发送成功返回结果："+JSONObject.toJSONString(result));
            return ResponseEntity.ok(Result.ok("发送成功"));
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(Result.error(result.getErrorMsg()));
        }
    }

    @PostMapping("/batch-send")
    public ResponseEntity<Result<String>> batchSendNotification(@Valid @RequestBody List<NotificationRequest> requests) {
        logger.info("发送请求参数："+JSONObject.toJSONString(requests));
        if (requests.size() > 1000) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(Result.error("单次批量发送不能超过1000条"));
        }
        notificationService.batchSendSubscribeMessages(requests);
        return ResponseEntity.ok(Result.ok("批量发送任务已提交"));
    }
}