package com.rj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.entity.AudioTextAnalysisSop;
import com.rj.service.IAudioTextAnalysisSopService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 音频文本分析SOP评分 控制器
 */
@RestController
@RequestMapping("/api/audioTextAnalysisSop")
@Tag(name = "语音分析-SOP评分", description = "音频文本分析SOP评分接口")
@Slf4j
public class AudioTextAnalysisSopController {

    @Autowired
    private IAudioTextAnalysisSopService sopService;

    @PostMapping("/add")
    @Operation(summary = "新增记录", description = "新增一条SOP评分记录")
    public ResponseEntity<Map<String, Object>> add(@RequestBody AudioTextAnalysisSop sop) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (sop.getId() == null || sop.getId().trim().isEmpty()) {
                sop.setId(UUID.randomUUID().toString());
            }
            LocalDateTime now = LocalDateTime.now();
            sop.setCreatedAt(now);
            sop.setUpdatedAt(now);
            boolean success = sopService.save(sop);
            result.put("success", success);
            result.put("data", sop);
            result.put("message", success ? "新增成功" : "新增失败");
            return success ? ResponseEntity.ok(result) : ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            log.error("新增SOP评分失败", e);
            result.put("success", false);
            result.put("message", "新增异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @PutMapping("/update")
    @Operation(summary = "修改记录", description = "更新一条SOP评分记录")
    public ResponseEntity<Map<String, Object>> update(@RequestBody AudioTextAnalysisSop sop) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (sop.getId() == null || sop.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            sop.setUpdatedAt(LocalDateTime.now());
            boolean success = sopService.updateById(sop);
            result.put("success", success);
            result.put("message", success ? "更新成功" : "更新失败");
            result.put("data", sop);
            return success ? ResponseEntity.ok(result) : ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            log.error("更新SOP评分失败", e);
            result.put("success", false);
            result.put("message", "更新异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除记录", description = "根据ID删除SOP评分记录")
    public ResponseEntity<Map<String, Object>> delete(@PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = sopService.removeById(id);
            result.put("success", success);
            result.put("message", success ? "删除成功" : "删除失败");
            return success ? ResponseEntity.ok(result) : ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            log.error("删除SOP评分失败", e);
            result.put("success", false);
            result.put("message", "删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @GetMapping("/get/{id}")
    @Operation(summary = "根据ID查询", description = "根据ID查询SOP评分记录")
    public ResponseEntity<Map<String, Object>> getById(@PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            AudioTextAnalysisSop sop = sopService.getById(id);
            if (sop != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", sop);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "记录不存在");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("查询SOP评分失败", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询", description = "根据条件分页查询SOP评分记录，支持根据父ID查询")
    public ResponseEntity<Map<String, Object>> page(
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10")
            @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "父ID，UUID，用于树状结构关联")
            @RequestParam(required = false) String parentId,
            @Parameter(description = "行业类型")
            @RequestParam(required = false) String industryType,
            @Parameter(description = "所属人姓名")
            @RequestParam(required = false) String ownerName,
            @Parameter(description = "所属人电话")
            @RequestParam(required = false) String ownerPhone,
            @Parameter(description = "客户姓名")
            @RequestParam(required = false) String customerName,
            @Parameter(description = "客户电话")
            @RequestParam(required = false) String customerPhone,
            @Parameter(description = "创建开始时间", example = "2025-01-01 00:00:00")
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime createdStart,
            @Parameter(description = "创建结束时间", example = "2025-12-31 23:59:59")
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime createdEnd) {
        Map<String, Object> result = new HashMap<>();
        try {
            Page<AudioTextAnalysisSop> page = new Page<>(current, size);
            LambdaQueryWrapper<AudioTextAnalysisSop> wrapper = new LambdaQueryWrapper<>();
            
            // 根据父ID查询（必选条件之一，但这里设为可选）
            if (parentId != null && !parentId.trim().isEmpty()) {
                wrapper.eq(AudioTextAnalysisSop::getParentId, parentId);
            }
            
            // 其他可选查询条件
            if (industryType != null && !industryType.trim().isEmpty()) {
                wrapper.eq(AudioTextAnalysisSop::getIndustryType, industryType);
            }
            if (ownerName != null && !ownerName.trim().isEmpty()) {
                wrapper.like(AudioTextAnalysisSop::getOwnerName, ownerName);
            }
            if (ownerPhone != null && !ownerPhone.trim().isEmpty()) {
                wrapper.like(AudioTextAnalysisSop::getOwnerPhone, ownerPhone);
            }
            if (customerName != null && !customerName.trim().isEmpty()) {
                wrapper.like(AudioTextAnalysisSop::getCustomerName, customerName);
            }
            if (customerPhone != null && !customerPhone.trim().isEmpty()) {
                wrapper.like(AudioTextAnalysisSop::getCustomerPhone, customerPhone);
            }
            if (createdStart != null) {
                wrapper.ge(AudioTextAnalysisSop::getCreatedAt, createdStart);
            }
            if (createdEnd != null) {
                wrapper.le(AudioTextAnalysisSop::getCreatedAt, createdEnd);
            }
            
            // 按更新时间倒序排列
            wrapper.orderByDesc(AudioTextAnalysisSop::getUpdatedAt);

            Page<AudioTextAnalysisSop> dataPage = sopService.page(page, wrapper);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", dataPage.getRecords());
            result.put("total", dataPage.getTotal());
            result.put("current", dataPage.getCurrent());
            result.put("size", dataPage.getSize());
            result.put("pages", dataPage.getPages());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("分页查询SOP评分失败", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @GetMapping("/listByParentId")
    @Operation(summary = "根据父ID查询列表", description = "根据父ID查询所有SOP评分记录（不分页）")
    public ResponseEntity<Map<String, Object>> listByParentId(
            @Parameter(description = "父ID，UUID，用于树状结构关联")
            @RequestParam String parentId) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<AudioTextAnalysisSop> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AudioTextAnalysisSop::getParentId, parentId);
            wrapper.orderByDesc(AudioTextAnalysisSop::getUpdatedAt);

            AudioTextAnalysisSop one = sopService.getOne(wrapper);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", one);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("根据父ID查询SOP评分失败", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}

