package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.common.Result;
import com.zhentao.entity.MyResource;
import com.zhentao.mapper.MyResourceMapper;
import com.zhentao.service.MyResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * 线索管理控制器
 */
@RestController
@RequestMapping("/admin/my-resource")
@CrossOrigin(origins = "*")
public class MyResourceController {
    
    @Autowired
    private MyResourceService myResourceService;
    
    /**
     * 线索列表（分页查询）
     * @param page 页码
     * @param pageSize 每页数量
     * @param name 名称（模糊查询）
     * @param phone 手机号（模糊查询）
     * @param status 审核状态（0-待审核，1-审核通过，2-审核失败）
     * @param diploma 学历
     * @param marrStatus 婚姻状况（0-未婚，1-离异，2-丧偶）
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> list(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "diploma", required = false) String diploma,
            @RequestParam(value = "marrStatus", required = false) Integer marrStatus) {
        
        try {
            Page<MyResource> pageInfo = new Page<>(page, pageSize);
            LambdaQueryWrapper<MyResource> queryWrapper = new LambdaQueryWrapper<>();
            
            // 只查询 isUser = 0 的数据
            queryWrapper.eq(MyResource::getIsUser, 0);
            
            // 名称模糊查询
            if (name != null && !name.trim().isEmpty()) {
                queryWrapper.like(MyResource::getName, name.trim());
            }
            
            // 手机号模糊查询
            if (phone != null && !phone.trim().isEmpty()) {
                queryWrapper.and(wrapper -> wrapper
                    .like(MyResource::getPhone, phone.trim())
                    .or()
                    .like(MyResource::getBackupPhone, phone.trim())
                );
            }
            
            // 审核状态查询
            if (status != null) {
                queryWrapper.eq(MyResource::getStatus, status);
            }
            
            // 学历查询
            if (diploma != null && !diploma.trim().isEmpty()) {
                queryWrapper.eq(MyResource::getDiploma, diploma.trim());
            }
            
            // 婚姻状况查询
            if (marrStatus != null) {
                queryWrapper.eq(MyResource::getMarrStatus, marrStatus);
            }
            
            // 按创建时间倒序
            queryWrapper.orderByDesc(MyResource::getCreateTime);
            
            Page<MyResource> result = myResourceService.page(pageInfo, queryWrapper);
            
            Map<String, Object> data = new HashMap<>();
            data.put("list", result.getRecords());
            data.put("total", result.getTotal());
            data.put("page", page);
            data.put("pageSize", pageSize);
            
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取线索详情
     * @param id 线索ID
     */
    @GetMapping("/{id}")
    public Result<MyResource> detail(@PathVariable Integer id) {
        try {
            MyResource resource = myResourceService.getById(id);
            if (resource == null) {
                return Result.error("线索不存在");
            }
            
            if (resource.getIsUser() != null && resource.getIsUser() != 0) {
                return Result.error("该线索不是待审核线索");
            }
            
            return Result.success(resource);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 审核线索
     * @param id 线索ID
     * @param status 审核状态（1-审核通过，2-审核失败）
     * @param rejectReason 审核原因（必填，无论通过还是失败都需要填写）
     */
    @PutMapping("/{id}/audit")
    public Result<String> audit(
            @PathVariable Integer id,
            @RequestParam("status") Integer status,
            @RequestParam("rejectReason") String rejectReason) {
        try {
            MyResource resource = myResourceService.getById(id);
            if (resource == null) {
                return Result.error("线索不存在");
            }
            
            if (status == null || (status != 1 && status != 2)) {
                return Result.error("审核状态参数错误");
            }
            
            // 审核原因必填验证
            if (rejectReason == null || rejectReason.trim().isEmpty()) {
                return Result.error("审核原因不能为空");
            }
            
            resource.setStatus(status);
            resource.setRejectReason(rejectReason.trim());
            
            boolean success = myResourceService.updateById(resource);
            if (success) {
                return Result.success(status == 1 ? "审核通过成功" : "审核失败成功");
            } else {
                return Result.error("审核失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("审核失败：" + e.getMessage());
        }
    }
}

