package com.guwan.controller.login;

import com.guwan.config.GlobalValue;
import com.guwan.service.TokenService;
import com.guwan.util.IPUtils;
import com.guwan.util.PathUtil;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.security.PermitAll;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
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.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private GlobalValue globalValue;

    @GetMapping("/login")
    @PermitAll
    @Operation(summary = "使用账号密码登录")
    public String login(String userId, HttpServletRequest request) {


        String test = PathUtil.path();


        System.out.println("tempPath = " + test);

        String ip = IPUtils.getIpAddr(request);
        System.out.println("ip111 = " + ip);
       return tokenService.createToken(userId, ip);

    }

    @GetMapping("/getInfo")
    @PermitAll
    @Operation(summary = "查询用户信息")
    public String getInfo(String token) {


        if (!tokenService.checkToken(token)) {
            return "token无效";
        }

        try {
            tokenService.getInfo(token);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            tokenService.validateAndExtendToken(token);
        }
        return "getInfo";
    }


    @PostMapping("/demo111")
    public void uploadFile(MultipartFile file) {


        String tempPath = System.getProperty("user.dir") + globalValue.getStaticLocations();

        try {
            // 确保临时路径存在
            File tempDir = new File(tempPath);
            if (!tempDir.exists()) {
                tempDir.mkdirs(); // 创建目录
            }

            // 构建文件的完整路径
            File serverFile = new File(tempPath + File.separator + file.getOriginalFilename());

            // 将上传的文件保存到服务器
            file.transferTo(serverFile);

            System.out.println("文件上传成功，保存路径为：" + serverFile.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件上传失败：" + e.getMessage());
        }
    }


}
