package com.haha.admin.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haha.common.annotation.Log;
import com.haha.common.enums.OperationType;
import com.haha.common.vo.Result;
import com.haha.entity.User;
import com.haha.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

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

    @Autowired
    private UserService userService;

    /**
     * 分页查询客户列表
     * @param params 查询参数
     * @return 客户列表
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> list(@RequestParam Map<String, Object> params) {
        try {
            int page = 1;
            int pageSize = 10;

            Object pageObj = params.get("page");
            if (pageObj != null && !pageObj.toString().isEmpty()) {
                page = Integer.parseInt(pageObj.toString());
            }

            Object pageSizeObj = params.get("pageSize");
            if (pageSizeObj != null && !pageSizeObj.toString().isEmpty()) {
                pageSize = Integer.parseInt(pageSizeObj.toString());
            }

            IPage<User> userPage = userService.getPage(page, pageSize, params);

            // 填充额外字段
            for (User user : userPage.getRecords()) {
                fillUserLabels(user);
            }

            Map<String, Object> data = new HashMap<>();
            data.put("list", userPage.getRecords());
            data.put("total", userPage.getTotal());
            data.put("pageSize", userPage.getSize());
            data.put("currentPage", userPage.getCurrent());

            return Result.success("查询成功", data);

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

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

    /**
     * 获取客户统计数据
     * @return 统计数据
     */
    @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 操作结果
     */
    @Log(module = "客户管理", operation = OperationType.UPDATE, summary = "更新客户状态")
    @PutMapping("/{id}/status")
    public Result<String> updateStatus(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        try {
            Integer status = Integer.valueOf(params.get("status").toString());
            
            LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(User::getId, id).set(User::getStatus, status);
            
            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 操作结果
     */
    @Log(module = "客户管理", operation = OperationType.UPDATE, summary = "更新客户信用分")
    @PutMapping("/{id}/credit")
    public Result<String> updateCreditScore(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        try {
            Integer creditScore = Integer.valueOf(params.get("creditScore").toString());
            
            boolean result = userService.updateCreditScore(id, creditScore);
            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 user 客户对象
     */
    private void fillUserLabels(User user) {
        // 状态标签
        if (user.getStatus() != null) {
            switch (user.getStatus()) {
                case 1:
                    user.setStatusLabel("正常");
                    user.setStatusColor("success");
                    break;
                case 0:
                    user.setStatusLabel("禁用");
                    user.setStatusColor("danger");
                    break;
                default:
                    user.setStatusLabel("未知");
                    user.setStatusColor("info");
            }
        }
    }
}
