package com.qqchen.deploy.backend.system.api;

import com.qqchen.deploy.backend.system.model.query.UserQuery;
import com.qqchen.deploy.backend.system.model.request.DepartmentAssignRequest;
import com.qqchen.deploy.backend.framework.controller.BaseController;
import com.qqchen.deploy.backend.framework.api.Response;
import com.qqchen.deploy.backend.system.entity.User;
import com.qqchen.deploy.backend.system.model.UserDTO;
import com.qqchen.deploy.backend.system.model.request.LoginRequest;
import com.qqchen.deploy.backend.system.model.response.LoginResponse;
import com.qqchen.deploy.backend.system.service.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

@RestController
@RequestMapping("/api/v1/user")
public class UserApiController extends BaseController<User, UserDTO, Long, UserQuery> {

    @Resource
    private IUserService userService;


    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Response<LoginResponse> login(@Validated @RequestBody LoginRequest request) {
        return Response.success(userService.login(request));
    }

    @Operation(summary = "获取当前用户信息")
    @GetMapping("/current")
    public Response<LoginResponse> getCurrentUser() {
        return Response.success(userService.getCurrentUserResponse());
    }

    @Operation(summary = "重置用户密码")
    @PostMapping("/{id}/reset-password")
    public Response<Void> resetPassword(@PathVariable Long id, @RequestBody String newPassword) {
        userService.resetPassword(id, newPassword);
        return Response.success();
    }

    @PutMapping("/{id}/department")
    @Operation(summary = "分配用户部门")
    public Response<Void> assignDepartment(
        @PathVariable Long id,  // 用户ID
        @RequestBody DepartmentAssignRequest request
    ) {
        userService.assignDepartment(id, request.getDepartmentId());
        return Response.success();
    }

    @Override
    protected void exportData(HttpServletResponse response, List<UserDTO> data) {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=users.xlsx");

        try (OutputStream out = response.getOutputStream()) {
            // ExcelUtils.export(data, out);
        } catch (IOException e) {
            throw new RuntimeException("Export failed", e);
        }
    }

}