package com.citygis.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.citygis.common.annotation.Log;
import com.citygis.common.core.domain.model.LoginBody;
import com.citygis.common.enums.BusinessType;
import com.citygis.web.domain.TabUser;
import com.citygis.web.service.ITabUserService;
import com.citygis.web.utils.AesUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

import static com.citygis.common.utils.SecurityUtils.getUserId;
import static com.citygis.common.utils.SecurityUtils.getUsername;

/**
 * @Author: zyl
 * @CreateTime: 2025-01-08
 * @Description: 获取catalogToken
 * @Version: 1.0
 */
@Api(tags = "获取catalogtoken")
@CrossOrigin
@RestController
@RequestMapping("/web")
public class GetTokenController {

    @Value("${catalog.url}")
    private String url;

    @Autowired
    private WebClient.Builder webClientBuilder;

    @Resource
    ITabUserService tabUserService;

    @Log(title = "获取catalogToken", businessType = BusinessType.OTHER)
    @ApiOperation("获取catalogToken")
    @PostMapping("/getCatalogToken")
    public Mono<ResponseEntity<String>> forwardPostRequest() {
        LoginBody loginBody = new LoginBody();
        Long userId = getUserId();

        LambdaQueryWrapper<TabUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TabUser::getUserId, userId);
        List<TabUser> list = tabUserService.list();

        TabUser one = tabUserService.getOne(wrapper);

        String s = AesUtil.aesDecrypt(one.getPassword());

        loginBody.setPassword(s);

        loginBody.setUsername(getUsername());
        // 目标URL
        String targetUrl = url + "/token";  // 替换为实际的目标URL

        // 创建WebClient实例
        WebClient webClient = webClientBuilder.baseUrl(targetUrl).build();

        // 使用WebClient发送POST请求，并携带请求体
        return webClient.post()
                .uri("")  // 目标URL的路径部分
                .bodyValue(loginBody)  // 将User对象作为请求体
                .retrieve()
                .toEntity(String.class)
                .map(response -> ResponseEntity
                        .status(response.getStatusCode())
                        .body(response.getBody()));
    }

}
