package link.at17.mid.tushare.robot.feishu.controller;

import org.springframework.beans.factory.annotation.Autowired;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson2.JSONObject;

import link.at17.mid.tushare.robot.feishu.ablilities.FeishuAppEvents;
import link.at17.mid.tushare.robot.feishu.ablilities.FeishuAppThrowable;
import link.at17.mid.tushare.robot.feishu.ablilities.FeishuAppVerify;
import link.at17.mid.tushare.robot.models.SweetDogAppEnv;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@Slf4j
@RestController
@RequestMapping("/feishu/sweetDogRobotV1")
public class SweetDogRobotV1 {

    @Autowired
    private SweetDogAppEnv sweetDogAppEnv;
    
    /*
     * 该接口从飞书网络端获取消息，并且识别消息后回传给飞书端。相当于一个复读机
     */
    @SuppressWarnings("serial")
    @PostMapping("/request")
    @ResponseBody
    @FeishuAppVerify(SweetDogAppEnv.class)
    private JSONObject request(@RequestBody JSONObject json) {
        
        String eventType = json.getJSONObject("header").getString("event_type");
        if (eventType.equals(FeishuAppEvents.ImReceiveMessageV1.getValue()) ) {
            JSONObject message = json.getJSONObject("event").getJSONObject("message");
            if (!message.getString("message_type").equals("text")) {
                throw new FeishuAppThrowable("Other types of messages have not been processed yet");
            }
            sweetDogAppEnv.getTenantAccessToken().ifPresent((tenantAccessToken) -> {
                OkHttpClient okHttpClient = new OkHttpClient();
                JSONObject postJson = new JSONObject() {{
                    put("receive_id", json
                            .getJSONObject("event")
                            .getJSONObject("sender")
                            .getJSONObject("sender_id").getString("open_id"));
                    put("content", message.get("content"));
                    put("msg_type", "text");
                }};
                Request request = new Request.Builder()
                        .url(sweetDogAppEnv.getLarkHost() + "/open-apis/im/v1/messages?receive_id_type=open_id")
                        .addHeader("Authorization", "Bearer " + tenantAccessToken)
                        .post(
                            okhttp3.RequestBody.create(
                                    postJson.toJSONString(),
                                    MediaType.parse("application/json; charset=utf-8")))
                        .build();
                log.info("tenantAccessToken {}, requestBody {}", tenantAccessToken, postJson);
                final Call call = okHttpClient.newCall(request);
                Response resp = null;
                try {
                    resp = call.execute();
                    JSONObject sendRespJson = JSONObject.parseObject(resp.body().string());
                    if (sendRespJson.getIntValue("code") != 0) {
                        throw new Exception (sendRespJson.getJSONObject("error").toJSONString());
                    }
                } catch (Exception e) {
                    log.error("send message error", e);
                }
                finally {
                    if (resp != null) resp.close();
                }
            });
        }
        return new JSONObject();
    }
}
