package com.hz.pm.api.external.todo;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.hz.pm.api.external.todo.dto.AddSingleWkHandleDTO;
import com.hz.pm.api.external.todo.dto.TodoDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 王仁康
 * @date 2024-01-02 16:55:51
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TodoServiceClient {

    /**
     * 外部系统域名
     */
    @Value("${sms.client-url:}")
    private String todoUrl;

    // 发送待办
    public static final String TODO_ADD = "/single_wk_handle/addWkhandle";

    // 完成待办
    public static final String TODO_COMPLETE = "/single_wk_handle/completeHandle";


    /**
     * 添加待办方法
     * @param addSingleWkHandleDTO
     * @return 接口返回待办ID
     */
    public TodoDto addTodo(AddSingleWkHandleDTO addSingleWkHandleDTO) {
        String url = todoUrl + TODO_ADD;
        Map<String,Object> map = new HashMap<>();
        JSONObject json = (JSONObject) JSONObject.toJSON(addSingleWkHandleDTO.getParams());
        String jsonString = JSON.toJSONString(json);
        map.put("params", jsonString);
        map.put("wkContent",addSingleWkHandleDTO.getWkContent());
        map.put("wkType",addSingleWkHandleDTO.getWkType());
        map.put("wkUser",addSingleWkHandleDTO.getWkUser());
        String responseResult = HttpUtil.post(url, JSON.toJSONString(map));
        return JSON.parseObject(responseResult, new TypeReference<TodoDto>() {
        });
    }

    /**
     * 完成待办
     * @param wkhandleId 待办ID
     */
    public TodoDto completeTodo(String wkhandleId){
        String url = todoUrl + TODO_COMPLETE;
        HashMap<String,Object> map = new HashMap<>();
        map.put("wkhandleId",wkhandleId);
        // 发送PUT请求
        HttpRequest request = HttpUtil.createRequest(Method.PUT,url)
                .form("wkhandleId",wkhandleId);
        HttpResponse response = request.execute();
        String responseBody = response.body();
        return JSON.parseObject(responseBody, new TypeReference<TodoDto>() {
        });
    }


}