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.HttpStatus;
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 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;

//    @Resource
//    SingleLoginService singleLoginService;


    @Log(title = "获取catalogToken", businessType = BusinessType.OTHER)
    @ApiOperation("获取catalogToken")
    @PostMapping("/getCatalogToken")
    public Mono<ResponseEntity<String>> forwardPostRequest() {
        // 获取当前用户ID和用户名
        Long userId = getUserId();
        String username = getUsername();

        // 查询用户信息
        TabUser user = getUserById(userId);
        if (user == null) {
            return Mono.just(ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found"));
        }

        // 解密密码
        String decryptedPassword;
        try {
            decryptedPassword = AesUtil.aesDecrypt(user.getPassword());
        } catch (Exception e) {
            return Mono.just(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to decrypt password"));
        }

        // 构建请求体
        LoginBody loginBody = new LoginBody();
        loginBody.setUsername(username);
        loginBody.setPassword(decryptedPassword);

        // 目标URL
        String targetUrl = url + "/token";  // 替换为实际的目标URL

        // 使用WebClient发送POST请求
        return webClientBuilder.baseUrl(targetUrl).build()
                .post()
                .uri("")
                .bodyValue(loginBody)
                .retrieve()
                .toEntity(String.class)
                .map(response -> ResponseEntity.status(response.getStatusCode()).body(response.getBody()));
    }

    // 提取获取用户信息的方法
    private TabUser getUserById(Long userId) {
        LambdaQueryWrapper<TabUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TabUser::getUserId, userId);
        return tabUserService.getOne(wrapper);
    }

//    /**
//     * 单点登录，页面初始化调用
//     *
//     * @param request
//     * @param response
//     * @throws IOException
//     */
//    @RequestMapping("/singleLogin")
//    public void singleLogin(HttpServletRequest request,
//                            HttpServletResponse response) throws IOException {
//        singleLoginService.singleLogin(request, response);
//    }

}
