package com.tashow.cloud.app.controller;

import cn.hutool.json.JSONObject;
import com.lark.oapi.core.utils.Decryptor;
import com.tashow.cloud.app.service.feishu.FeiShuCardDataService;
import com.tashow.cloud.sdk.feishu.client.FeiShuAlertClient;
import com.tashow.cloud.sdk.feishu.config.LarkConfig;
import jakarta.annotation.security.PermitAll;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

@RestController
public class FeishuController {
    private static final Logger log = LoggerFactory.getLogger(FeishuController.class);
    private static final String ACTION_COMPLETE_ALARM = "complete_alarm";
    private final FeiShuAlertClient feiShuAlertClient;
    private final FeiShuCardDataService feiShuCardDataService;
    private final LarkConfig larkConfig;

    @Autowired
    public FeishuController(FeiShuAlertClient feiShuAlertClient, FeiShuCardDataService feiShuCardDataService, LarkConfig larkConfig) {
        this.feiShuAlertClient = feiShuAlertClient;
        this.feiShuCardDataService = feiShuCardDataService;
        this.larkConfig = larkConfig;
    }

    @RequestMapping("/card")
    @PermitAll
    public String card(@RequestBody JSONObject data) {
        try {
            if (data.containsKey("app_id") && data.containsKey("action")) {
                JSONObject action = data.getJSONObject("action");
                JSONObject value = action.getJSONObject("value");
                if (value != null && ACTION_COMPLETE_ALARM.equals(value.getStr("action"))) {
                    String messageId = data.getStr("open_message_id");
                    Map<String, Object> templateData = feiShuCardDataService.getCardData(messageId);
                    templateData.put("open_id", data.getStr("open_id"));
                    templateData.put("complete_time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    JSONObject fromValue = action.getJSONObject("form_value");
                    templateData.put("notes", fromValue.getStr("notes_input"));
                    return feiShuAlertClient.buildCardWithData(larkConfig.getSuccessCards(), templateData);
                }
            }
            if (data.containsKey("encrypt")) {
                Decryptor decryptor = new Decryptor(larkConfig.getEncryptKey());
                return decryptor.decrypt(data.getStr("encrypt"));
            }
            return "{}";
        } catch (Exception e) {
            log.error("卡片处理异常", e);
            return "{\"code\":1,\"msg\":\"处理异常: " + e.getMessage() + "\"}";
        }
    }


}
