package com.gxwebsoft.open.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.gxwebsoft.common.core.utils.JSONUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.Setting;
import com.gxwebsoft.common.system.service.SettingService;
import com.gxwebsoft.oa.entity.Notice;
import com.gxwebsoft.oa.param.NoticeParam;
import com.gxwebsoft.oa.service.NoticeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.gxwebsoft.oa.constants.NoticeConstants.CHAT_GPT;

/**
 * ChatGPT控制器
 *
 * @author WebSoft
 * @since 2018-12-24 16:10:24
 */
@Api(tags = "ChatGPT")
@RestController
@RequestMapping("/api/open/chat")
public class OpenChatGptController extends BaseController {
    @Resource
    private NoticeService noticeService;
    @Resource
    private SettingService settingService;

    @ApiOperation("向chatGPT提问")
    @PostMapping("/send")
    public ApiResult<?> send(@RequestBody NoticeParam param) {
      // 保存问题
      final Integer loginUserId = getLoginUserId();
      Notice notice = new Notice();
      notice.setType(CHAT_GPT);
      notice.setUserId(loginUserId);
      notice.setChannel(0);
      notice.setContent(param.getContent());
      noticeService.save(notice);
      // 保存回答
      Notice answer = new Notice();
      answer.setUserId(loginUserId);
      answer.setType(CHAT_GPT);
      answer.setChannel(1);
      answer.setContent("|");
      noticeService.save(answer);
      // 查询消息并返回
      param.setUserId(loginUserId);
      return success(answer.getNoticeId());
    }

  @ApiOperation("chatGPT")
  @PostMapping("/chat")
  public ApiResult<?> chat(@RequestBody NoticeParam param) {
    String endpoint = "https://api.openai.com/v1/chat/completions";
    final Setting setting = settingService.getData("chatGPT");
    final String content1 = setting.getContent();
    final JSONObject jsonObject1 = JSONObject.parseObject(content1);
    final String chatKey = jsonObject1.getString("chatKey");
    String apiKey = "Bearer ".concat(chatKey);
    System.out.println("apiKey = " + apiKey);
    if(StrUtil.isEmpty(apiKey)){
      return fail("请配置有效的KEY！");
    }
    Map<String, Object> paramMap = new HashMap<>();
    paramMap.put("model", "gpt-3.5-turbo");
    List<Map<String, String>> dataList = new ArrayList<>();
    dataList.add(new HashMap<String, String>(){{
      put("role", "user");
      put("content", param.getContent());
    }});
    paramMap.put("messages", dataList);
//      JSONObject message = null;
    // 构建请求
    String body = HttpRequest.post(endpoint)
      .header("Authorization", apiKey)
      .header("Content-Type", "application/json")
      .body(JSONUtil.toJSONString(paramMap)).execute().body();
    JSONObject jsonObject = JSONObject.parseObject(body);
    // 内容解析(代币)
    String usage = jsonObject.getString("usage");
    JSONObject jsonUsage = JSONObject.parseObject(usage);
    String total_tokens = jsonUsage.getString("total_tokens");
    // 内容解析(消息内容)
    JSONObject choices = jsonObject.getJSONArray("choices").getJSONObject(0);
    String message = choices.getString("message");
    JSONObject jsonMessage = JSONObject.parseObject(message);
    String content = jsonMessage.getString("content");

    // 保存回答
    Notice notice = noticeService.getById(param.getNoticeId());
    notice.setTokens(new Long(total_tokens));
    notice.setContent(content);
    noticeService.updateById(notice);
    return success(content);
  }
}
