package com.haha.admin.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haha.entity.dto.CreditScoreDTO;
import com.haha.entity.dto.StatusDTO;
import com.haha.entity.dto.UserQueryDTO;
import com.haha.admin.annotation.RequirePermission;
import com.haha.common.annotation.Log;
import com.haha.common.enums.OperationType;
import com.haha.common.vo.PageResult;
import com.haha.common.vo.Result;
import com.haha.entity.User;
import com.haha.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 客户管理控制器
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/users")
public class UserController {

    private final UserService userService;

    /**
     * 分页查询客户列表
     * @param params 查询参数
     * @return 客户列表
     */
    @RequirePermission("user:read")
    @GetMapping("/list")
    public Result<PageResult<User>> list(UserQueryDTO queryDTO) {
        try {
            queryDTO.validate();

            IPage<User> userPage = userService.getPage(
                    queryDTO.getPage(), queryDTO.getPageSize(), queryDTO);

            // 填充标签字段（由Service层处理）
            userService.fillUserLabels(userPage.getRecords());

            return Result.success("查询成功", PageResult.of(userPage));

        } catch (Exception e) {
            log.error("查询客户列表失败: {}", e.getMessage(), e);
            return Result.error(500, "查询客户列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取客户详情
     * @param id 客户ID
     * @return 客户详情
     */
    @RequirePermission("user:read")
    @GetMapping("/{id}")
    public Result<User> getById(@PathVariable Long id) {
        try {
            User user = userService.getById(id);
            if (user == null) {
                return Result.error(404, "客户不存在");
            }
            userService.fillUserLabels(List.of(user));
            return Result.success("查询成功", user);
        } catch (Exception e) {
            log.error("查询客户详情失败: id={}, error={}", id, e.getMessage(), e);
            return Result.error(500, "查询客户详情失败: " + e.getMessage());
        }
    }

    /**
     * 获取客户统计数据
     * @return 统计数据
     */
    @RequirePermission("user:read")
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getStatistics() {
        try {
            Map<String, Object> statistics = userService.getStatistics();
            return Result.success("查询成功", statistics);
        } catch (Exception e) {
            log.error("查询客户统计失败: {}", e.getMessage(), e);
            return Result.error(500, "查询客户统计失败: " + e.getMessage());
        }
    }

    /**
     * 更新客户状态
     * @param id 客户ID
     * @param params 状态参数
     * @return 操作结果
     */
    @RequirePermission("user:update")
    @Log(module = "客户管理", operation = OperationType.UPDATE, summary = "更新客户状态")
    @PutMapping("/{id}/status")
    public Result<String> updateStatus(@PathVariable Long id, @RequestBody StatusDTO dto) {
        try {
            LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(User::getId, id).set(User::getStatus, dto.getStatus());
            
            boolean result = userService.update(wrapper);
            if (result) {
                return Result.success("状态更新成功");
            } else {
                return Result.error(500, "状态更新失败");
            }
        } catch (Exception e) {
            log.error("更新客户状态失败: id={}, error={}", id, e.getMessage(), e);
            return Result.error(500, "更新客户状态失败: " + e.getMessage());
        }
    }

    /**
     * 更新客户信用分
     * @param id 客户ID
     * @param params 信用分参数
     * @return 操作结果
     */
    @RequirePermission("user:update")
    @Log(module = "客户管理", operation = OperationType.UPDATE, summary = "更新客户信用分")
    @PutMapping("/{id}/credit")
    public Result<String> updateCreditScore(@PathVariable Long id, @RequestBody CreditScoreDTO dto) {
        try {
            boolean result = userService.updateCreditScore(id, dto.getCreditScore());
            if (result) {
                return Result.success("信用分更新成功");
            } else {
                return Result.error(500, "信用分更新失败");
            }
        } catch (Exception e) {
            log.error("更新客户信用分失败: id={}, error={}", id, e.getMessage(), e);
            return Result.error(500, "更新客户信用分失败: " + e.getMessage());
        }
    }

}
