package com.snack.server.module.user.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.snack.server.common.Result;
import com.snack.server.module.order.entity.Order;
import com.snack.server.module.order.enums.OrderStatusEnum;
import com.snack.server.module.order.mapper.OrderMapper;
import com.snack.server.module.order.vo.OrderDetailVO;
import com.snack.server.module.user.dto.req.UserPageReq;
import com.snack.server.module.user.dto.req.UserSaveReq;
import com.snack.server.module.user.service.UserService;
import com.snack.server.module.user.vo.UserVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * 用户管理（管理端）
 */
@Tag(name = "06. 用户管理")
@RestController
@RequestMapping("/api/admin/user")
@RequiredArgsConstructor
public class UserAdminController {

    private final UserService userService;
    private final OrderMapper orderMapper;

    @Operation(summary = "分页查询用户列表")
    @SaCheckLogin
    @GetMapping("/page")
    public Result<Page<UserVO>> page(UserPageReq req) {
        return Result.ok(userService.pageUsers(req));
    }

    @Operation(summary = "获取用户详情")
    @SaCheckLogin
    @GetMapping("/{id}")
    public Result<UserVO> detail(@Parameter(description = "用户 ID") @PathVariable Long id) {
        return Result.ok(userService.getUserById(id));
    }

    @Operation(summary = "创建用户")
    @SaCheckLogin
    @PostMapping
    public Result<Long> create(@Valid @RequestBody UserSaveReq req) {
        return Result.ok(userService.createUser(req));
    }

    @Operation(summary = "更新用户")
    @SaCheckLogin
    @PutMapping
    public Result<Void> update(@Valid @RequestBody UserSaveReq req) {
        userService.updateUser(req);
        return Result.ok();
    }

    @Operation(summary = "删除用户")
    @SaCheckLogin
    @DeleteMapping("/{id}")
    public Result<Void> delete(@Parameter(description = "用户 ID") @PathVariable Long id) {
        userService.deleteUser(id);
        return Result.ok();
    }

    @Operation(summary = "重置用户密码")
    @SaCheckLogin
    @PutMapping("/{id}/password/reset")
    public Result<Void> resetPassword(
            @Parameter(description = "用户 ID") @PathVariable Long id,
            @Parameter(description = "新密码") @RequestParam String newPassword) {
        userService.resetPassword(id, newPassword);
        return Result.ok();
    }

    @Operation(summary = "启用 / 禁用用户")
    @SaCheckLogin
    @PutMapping("/{id}/status/{status}")
    public Result<Void> updateStatus(
            @Parameter(description = "用户 ID") @PathVariable Long id,
            @Parameter(description = "状态：0-禁用 1-启用") @PathVariable Integer status) {
        userService.updateStatus(id, status);
        return Result.ok();
    }

    @Operation(summary = "用户历史订单（分页）")
    @SaCheckLogin
    @GetMapping("/{id}/orders")
    public Result<Page<OrderDetailVO>> ordersOfUser(
            @Parameter(description = "用户 ID") @PathVariable Long id,
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") Long current,
            @Parameter(description = "每页条数", example = "10") @RequestParam(defaultValue = "10") Long size) {
        Page<Order> page = new Page<>(current, size);
        Page<Order> result = orderMapper.selectPage(page,
                new LambdaQueryWrapper<Order>()
                        .eq(Order::getUserId, id)
                        .orderByDesc(Order::getId));
        Page<OrderDetailVO> voPage = new Page<>(result.getCurrent(), result.getSize(), result.getTotal());
        voPage.setRecords(result.getRecords().stream().map(this::toOrderDetailVO).toList());
        return Result.ok(voPage);
    }

    private OrderDetailVO toOrderDetailVO(Order o) {
        OrderDetailVO vo = new OrderDetailVO();
        // 复用 OrderServiceImpl 同款字段映射
        cn.hutool.core.bean.BeanUtil.copyProperties(o, vo);
        int s = o.getStatus() == null ? 0 : o.getStatus();
        OrderStatusEnum[] vals = OrderStatusEnum.values();
        if (s >= 0 && s < vals.length) {
            OrderStatusEnum statusEnum = vals[s];
            vo.setStatusText(statusEnum.getDesc());
            vo.setStatusTagType(statusEnum.tagType());
        }
        return vo;
    }
}
