package io.controller;

import cn.hutool.crypto.digest.DigestUtil;
import io.annotation.Login;
import io.annotation.LoginUser;
import io.common.utils.KeyUtil;
import io.common.utils.Result;
import io.common.validator.ValidatorUtils;
import io.dto.LoginDTO;
import io.dto.RegisterDTO;
import io.entity.UserEntity;
import io.service.TokenService;
import io.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Map;

/**
 * 登录接口
 */
@RestController
@RequestMapping("/api/user")

@CrossOrigin
public class UserController {

    @Autowired
    private  UserService userService;
    @Autowired
    private  TokenService tokenService;

    @Value("${upload.path}")
    private  String path;

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

    @PostMapping("register")
    @Operation(summary = "注册")
    public Result register(@RequestBody RegisterDTO dto) throws NoSuchAlgorithmException {
        //表单校验
        ValidatorUtils.validateEntity(dto);
        if (!dto.getPassword().equals(dto.getConfirmPassword())){
            return new Result().error("两次密码输入不一致~");
        }
       if (userService.getByUsername(dto.getUsername()) != null) {
           return new Result().error("用户名已经存在~");
       }
        //表单校验
        ValidatorUtils.validateEntity(dto);
        UserEntity user = new UserEntity();
        BeanUtils.copyProperties(dto,user);
        String sha256Hex = DigestUtil.sha256Hex(dto.getPassword());
        user.setPassword(sha256Hex);
        user.setCreateDate(new Date());
        // 2. 生成RSA密钥对
        KeyPair keyPair = KeyUtil.generateKeyPair();

        String publicKey = KeyUtil.encodeKeyToString(keyPair.getPublic().getEncoded());
        //公钥
        String privateKey = KeyUtil.encodeKeyToString(keyPair.getPrivate().getEncoded());
        user.setHex(publicKey);
        userService.insert(user);
        saveStringToFile(privateKey,path,user.getUsername());
        return new Result().ok(url + user.getUsername()+ ".key");
    }

    public  static void saveStringToFile(String content, String directoryPath, String fileName) {
        try {
            // 创建文件夹，如果不存在
            File directory = new File(directoryPath);
            if (!directory.exists()) {
                directory.mkdirs(); // 多层目录一起建
            }
            // 组合完整路径
            File file = new File(directoryPath + File.separator + fileName + ".key");
            // 创建文件并写入内容
            FileWriter writer = new FileWriter(file);
            writer.write(content);
            writer.close();
            System.out.println("文件保存成功：" + file.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("login")
    @Operation(summary = "登录")
    public Result<Map<String, Object>> login(@RequestBody LoginDTO dto) {
        //表单校验
        ValidatorUtils.validateEntity(dto);
        //用户登录
        Map<String, Object> map = userService.login(dto);
        return new Result().ok(map);
    }

    @PutMapping("update")
    @Operation(summary = "修改信息")
    public Result update(@RequestBody RegisterDTO dto) {
        //表单校验
        ValidatorUtils.validateEntity(dto);
        UserEntity user = new UserEntity();
        user.setId(dto.getId());
        user.setUsername(dto.getUsername());
        user.setNickName(dto.getNickName());
        user.setHex(dto.getHex());
        user.setProfile(dto.getProfile());
        user.setPassword(DigestUtil.sha256Hex(dto.getPassword()));
        userService.updateById(user);
        return new Result();
    }


    @Login
    @PostMapping("logout")
    @Operation(summary = "退出")
    public Result logout(@Parameter(hidden = true) @RequestAttribute("userId") Long userId) {
        tokenService.expireToken(userId);
        return new Result();
    }

    @Login
    @GetMapping("userInfo")
    @Operation(summary = "获取用户信息")
    public Result<UserEntity> userInfo(@Parameter(hidden = true) @LoginUser UserEntity user) {
        return new Result<UserEntity>().ok(user);
    }
}
