package com.cyksj.web.controller.gpt;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.model.entity.Account;
import com.cyksj.service.chatgpt.ChatGptAuthService;
import com.cyksj.service.mange.CmsAccountService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author chan
 * @date 2023/6/2 5:19 PM
 */

@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/manage/chat")
public class ChatGptController {
    private final ChatGptAuthService chatGptAuthService;

    private final CmsAccountService accountService;

    @GetMapping("/getAccessToken")
    private Result<String> getAccessToken(String username) throws Exception {

        log.info("获取chatgpt 凭证 username:{}",username);
        String accessToken = chatGptAuthService.getAccessToken(username);
        log.info("获取chatgpt 凭证返回 token:{}",accessToken);

        return GatewayResponse.SUCCESS.newBuilder().toResult(accessToken);
    }

    @GetMapping("/init")
    private Result<String> init() throws Exception {
        List<Account> list = accountService.list(Wrappers.lambdaQuery(Account.class).eq(Account::getGoodsId, 18).eq(Account::getGptRefreshToken, ""));
        for (Account account : list) {
            log.info("账号:{} 正在执行获取token", account.getAccount());
            try {
                chatGptAuthService.getRefreshToken(account);
            }catch (Exception e){
                log.error("账号:{} 获取token 错误:{}",account.getAccount(), e.getMessage());
            }
        }
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

}
