package com.rj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.entity.AudioTextAnalysisMeeting;
import com.rj.service.IAudioTextAnalysisMeetingService;
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.List;
import java.util.Map;

/**
 * <p>
 * 音频文本分析会议表 前端控制器
 * </p>
 *
 * @author system
 * @since 2025-01-XX
 */
@RestController
@RequestMapping("/api/audioTextAnalysisMeeting")
@Tag(name = "音频文本分析会议", description = "音频文本分析会议相关接口")
@Slf4j
public class AudioTextAnalysisMeetingController {

    @Autowired
    private IAudioTextAnalysisMeetingService audioTextAnalysisMeetingService;

    /**
     * 新增会议记录
     */
    @PostMapping("/add")
    @Operation(summary = "新增会议记录", description = "添加新的会议信息")
    public ResponseEntity<Map<String, Object>> addMeeting(
            @Parameter(description = "会议信息", required = true)
            @RequestBody AudioTextAnalysisMeeting meeting) {
        Map<String, Object> result = new HashMap<>();
        try {
            meeting.setCreatedAt(LocalDateTime.now());
            meeting.setUpdatedAt(LocalDateTime.now());
            boolean success = audioTextAnalysisMeetingService.save(meeting);
            if (success) {
                result.put("success", true);
                result.put("message", "会议记录添加成功");
                result.put("data", meeting);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "会议记录添加失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            log.error("新增会议记录异常：", e);
            result.put("success", false);
            result.put("message", "会议记录添加异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据ID查询会议记录
     */
    @GetMapping("/get/{id}")
    @Operation(summary = "根据ID查询会议记录", description = "根据会议ID获取会议详细信息")
    public ResponseEntity<Map<String, Object>> getMeetingById(
            @Parameter(description = "会议ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            AudioTextAnalysisMeeting meeting = audioTextAnalysisMeetingService.getById(id);
            if (meeting != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", meeting);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "会议记录不存在");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("根据ID查询会议记录异常：", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 更新会议记录
     */
    @PutMapping("/update")
    @Operation(summary = "更新会议记录", description = "更新会议详细信息")
    public ResponseEntity<Map<String, Object>> updateMeeting(
            @Parameter(description = "会议信息", required = true)
            @RequestBody AudioTextAnalysisMeeting meeting) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (meeting.getId() == null || meeting.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "会议ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            meeting.setUpdatedAt(LocalDateTime.now());
            boolean success = audioTextAnalysisMeetingService.updateById(meeting);
            
            if (success) {
                result.put("success", true);
                result.put("message", "会议记录更新成功");
                result.put("data", meeting);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "会议记录更新失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            log.error("更新会议记录异常：", e);
            result.put("success", false);
            result.put("message", "更新异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据ID删除会议记录
     */
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除会议记录", description = "根据会议ID删除会议信息")
    public ResponseEntity<Map<String, Object>> deleteMeeting(
            @Parameter(description = "会议ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = audioTextAnalysisMeetingService.removeById(id);
            if (success) {
                result.put("success", true);
                result.put("message", "会议记录删除成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "会议记录删除失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            log.error("删除会议记录异常：", e);
            result.put("success", false);
            result.put("message", "删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 分页条件查询会议记录列表
     */
    @GetMapping("/list")
    @Operation(summary = "分页条件查询会议记录列表", description = "分页查询会议信息列表，支持多条件查询")
    public ResponseEntity<Map<String, Object>> getMeetingList(
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10")
            @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "租户ID")
            @RequestParam(required = false) String tenantId,
            @Parameter(description = "父ID")
            @RequestParam(required = false) String parentId,
            @Parameter(description = "会议类型")
            @RequestParam(required = false) String meetingType,
            @Parameter(description = "会议成员（模糊查询）")
            @RequestParam(required = false) String meetingMember,
            @Parameter(description = "会议议题（模糊查询）")
            @RequestParam(required = false) String meetingItem,
            @Parameter(description = "会议风格")
            @RequestParam(required = false) String decorationStyle,
            @Parameter(description = "所有者电话")
            @RequestParam(required = false) String ownerPhone,
            @Parameter(description = "所有者ID")
            @RequestParam(required = false) String ownerId,
            @Parameter(description = "客户电话")
            @RequestParam(required = false) String customerPhone,
            @Parameter(description = "客户ID")
            @RequestParam(required = false) String customerId,
            @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<AudioTextAnalysisMeeting> page = new Page<>(current, size);
            LambdaQueryWrapper<AudioTextAnalysisMeeting> queryWrapper = new LambdaQueryWrapper<>();

            // 添加查询条件
            if (tenantId != null && !tenantId.trim().isEmpty()) {
                queryWrapper.eq(AudioTextAnalysisMeeting::getTenantId, tenantId);
            }
            if (parentId != null && !parentId.trim().isEmpty()) {
                queryWrapper.eq(AudioTextAnalysisMeeting::getParentId, parentId);
            }
            if (meetingType != null && !meetingType.trim().isEmpty()) {
                queryWrapper.eq(AudioTextAnalysisMeeting::getMeetingType, meetingType);
            }
            if (meetingMember != null && !meetingMember.trim().isEmpty()) {
                queryWrapper.like(AudioTextAnalysisMeeting::getMeetingMember, meetingMember);
            }
            if (meetingItem != null && !meetingItem.trim().isEmpty()) {
                queryWrapper.like(AudioTextAnalysisMeeting::getMeetingItem, meetingItem);
            }
            if (decorationStyle != null && !decorationStyle.trim().isEmpty()) {
                queryWrapper.eq(AudioTextAnalysisMeeting::getDecorationStyle, decorationStyle);
            }
            if (ownerPhone != null && !ownerPhone.trim().isEmpty()) {
                queryWrapper.eq(AudioTextAnalysisMeeting::getOwnerPhone, ownerPhone);
            }
            if (ownerId != null && !ownerId.trim().isEmpty()) {
                queryWrapper.eq(AudioTextAnalysisMeeting::getOwnerId, ownerId);
            }
            if (customerPhone != null && !customerPhone.trim().isEmpty()) {
                queryWrapper.eq(AudioTextAnalysisMeeting::getCustomerPhone, customerPhone);
            }
            if (customerId != null && !customerId.trim().isEmpty()) {
                queryWrapper.eq(AudioTextAnalysisMeeting::getCustomerId, customerId);
            }
            if (createdStart != null) {
                queryWrapper.ge(AudioTextAnalysisMeeting::getCreatedAt, createdStart);
            }
            if (createdEnd != null) {
                queryWrapper.le(AudioTextAnalysisMeeting::getCreatedAt, createdEnd);
            }

            // 按更新时间倒序排列
            queryWrapper.orderByDesc(AudioTextAnalysisMeeting::getUpdatedAt);

            Page<AudioTextAnalysisMeeting> meetingPage = audioTextAnalysisMeetingService.page(page, queryWrapper);

            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", meetingPage.getRecords());
            result.put("total", meetingPage.getTotal());
            result.put("current", meetingPage.getCurrent());
            result.put("size", meetingPage.getSize());
            result.put("pages", meetingPage.getPages());

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("分页查询会议记录异常：", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 不分页条件查询会议记录列表
     */
    @GetMapping("/listAll")
    @Operation(summary = "不分页条件查询会议记录列表", description = "查询所有符合条件的会议信息列表，不支持分页")
    public ResponseEntity<Map<String, Object>> getAllMeetingList(
            @Parameter(description = "租户ID")
            @RequestParam(required = false) String tenantId,
            @Parameter(description = "父ID")
            @RequestParam(required = false) String parentId,
            @Parameter(description = "会议类型")
            @RequestParam(required = false) String meetingType,
            @Parameter(description = "会议成员（模糊查询）")
            @RequestParam(required = false) String meetingMember,
            @Parameter(description = "会议议题（模糊查询）")
            @RequestParam(required = false) String meetingItem,
            @Parameter(description = "会议风格")
            @RequestParam(required = false) String decorationStyle,
            @Parameter(description = "所有者电话")
            @RequestParam(required = false) String ownerPhone,
            @Parameter(description = "所有者ID")
            @RequestParam(required = false) String ownerId,
            @Parameter(description = "客户电话")
            @RequestParam(required = false) String customerPhone,
            @Parameter(description = "客户ID")
            @RequestParam(required = false) String customerId,
            @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 {
            LambdaQueryWrapper<AudioTextAnalysisMeeting> queryWrapper = new LambdaQueryWrapper<>();

            // 添加查询条件
            if (tenantId != null && !tenantId.trim().isEmpty()) {
                queryWrapper.eq(AudioTextAnalysisMeeting::getTenantId, tenantId);
            }
            if (parentId != null && !parentId.trim().isEmpty()) {
                queryWrapper.eq(AudioTextAnalysisMeeting::getParentId, parentId);
            }
            if (meetingType != null && !meetingType.trim().isEmpty()) {
                queryWrapper.eq(AudioTextAnalysisMeeting::getMeetingType, meetingType);
            }
            if (meetingMember != null && !meetingMember.trim().isEmpty()) {
                queryWrapper.like(AudioTextAnalysisMeeting::getMeetingMember, meetingMember);
            }
            if (meetingItem != null && !meetingItem.trim().isEmpty()) {
                queryWrapper.like(AudioTextAnalysisMeeting::getMeetingItem, meetingItem);
            }
            if (decorationStyle != null && !decorationStyle.trim().isEmpty()) {
                queryWrapper.eq(AudioTextAnalysisMeeting::getDecorationStyle, decorationStyle);
            }
            if (ownerPhone != null && !ownerPhone.trim().isEmpty()) {
                queryWrapper.eq(AudioTextAnalysisMeeting::getOwnerPhone, ownerPhone);
            }
            if (ownerId != null && !ownerId.trim().isEmpty()) {
                queryWrapper.eq(AudioTextAnalysisMeeting::getOwnerId, ownerId);
            }
            if (customerPhone != null && !customerPhone.trim().isEmpty()) {
                queryWrapper.eq(AudioTextAnalysisMeeting::getCustomerPhone, customerPhone);
            }
            if (customerId != null && !customerId.trim().isEmpty()) {
                queryWrapper.eq(AudioTextAnalysisMeeting::getCustomerId, customerId);
            }
            if (createdStart != null) {
                queryWrapper.ge(AudioTextAnalysisMeeting::getCreatedAt, createdStart);
            }
            if (createdEnd != null) {
                queryWrapper.le(AudioTextAnalysisMeeting::getCreatedAt, createdEnd);
            }

            // 按更新时间倒序排列
            queryWrapper.orderByDesc(AudioTextAnalysisMeeting::getUpdatedAt);

            List<AudioTextAnalysisMeeting> meetingList = audioTextAnalysisMeetingService.list(queryWrapper);

            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", meetingList);
            result.put("count", meetingList.size());

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("查询会议记录异常：", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}

