package com.rj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.common.AudioAnalysisSceneType;
import com.rj.common.AudioManagementConstants;
import com.rj.common.DataEnrichmentUtil;
import com.rj.entity.AudioManagement;
import com.rj.entity.AudioManagementSegments;
import com.rj.entity.AudioTextAnalysisFurniture;
import com.rj.entity.CustomerManagement;
import com.rj.service.*;
import com.rj.dto.AsrRequest;
import com.rj.dto.AsrResponse;
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.apache.tika.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 录音管理表，含信息卡字段 前端控制器
 * </p>
 * 播放：   https://apig.huayang-star.com/api/audio/1957424644480905217_9e35b6ff-f198-4c42-a5c1-49fa8333fc35.mp3
 *
 * @author 李中华 ,spllzh
 * @since 2025-08-07
 */
@RestController
@RequestMapping("/api/audioManagement")
@Tag(name = "录音管理", description = "录音管理相关接口")
@Slf4j
public class AudioManagementController {

    // 场景常量，避免在解析逻辑中硬编码字符串
    public static final String SCENARIO_SOFT_SALE = "soft_sales";
    public static final String SCENARIO_FURNITURE_SALE = "furniture";
    public static final String SCENARIO_SMALL_BEEUTIFUL_SALE = "smallBeautiful_sales";
    public static final String SCENARIO_CAR_SALE = "car_sale";
    public static final String SCENARIO_SUMMARY = "summary";


    @Autowired
    private IAudioManagementService audioManagementService;

    @Autowired
    private ICustomerManagementService customerManagementService;



    @Autowired
    private IFileUploadService fileUploadService;

    @Autowired
    private MinIOService minIOService;

    @Autowired
    private ITtsRequestLogService ttsRequestLogService;

    @Autowired
    private IAudioTextAnalysisLlmService audioTextAnalysisLlmService;

    /**
     * 新增录音
     */
    @PostMapping("/uploadAndSubmit")
    @Operation(summary = "新增录音", description = "添加新的录音信息")
    public ResponseEntity<Map<String, Object>> addAudio(
            @Parameter(description = "录音文件", required = true)
            @RequestParam("file") MultipartFile file,
            @Parameter(description = "录音名称", required = false)
            @RequestParam(value = "recordingName", required = false) String recordingName,
            @Parameter(description = "录音时间", required = false)
            @RequestParam(value = "recordingTime", required = false) String recordingTime,
            @Parameter(description = "所属销售ID", required = false)
            @RequestParam(value = "salesId", required = false) String salesId,
            @Parameter(description = "所属销售名称", required = false)
            @RequestParam(value = "salesName", required = false) String salesName,
            @Parameter(description = "销售人员电话", required = false)
            @RequestParam(value = "salesPhone", required = false) String salesPhone,
            @Parameter(description = "录音时长(分钟)", required = false)
            @RequestParam(value = "duration", required = false) BigDecimal duration,
            @Parameter(description = "客户ID", required = false)
            @RequestParam(value = "customerId", required = false) String customerId,
            @Parameter(description = "客户姓名", required = false)
            @RequestParam(value = "customerName", required = false) String customerName,
            @Parameter(description = "客户手机号", required = false)
            @RequestParam(value = "customerPhone", required = false) String customerPhone,
            @Parameter(description = "意向级别", required = false)
            @RequestParam(value = "intentionLevel", required = false) String intentionLevel,
            @Parameter(description = "所属门店ID", required = false)
            @RequestParam(value = "dealershipId", required = false) String dealershipId,
            @Parameter(description = "所属门店名称", required = false)
            @RequestParam(value = "dealershipName", required = false) String dealershipName,
            @Parameter(description = "所属项目ID", required = false)
            @RequestParam(value = "projectId", required = false) String projectId,
            @Parameter(description = "所属项目名称", required = false)
            @RequestParam(value = "projectName", required = false) String projectName,
            @Parameter(description = "话术模型", required = false)
            @RequestParam(value = "scriptModel", required = false) String scriptModel,
            @Parameter(description = "场景", required = false)
            @RequestParam(value = "scenario", required = false) String scenario,
            @Parameter(description = "录音备注", required = false)
            @RequestParam(value = "remarks", required = false) String remarks,
            @Parameter(description = "录音文本内容", required = false)
            @RequestParam(value = "recordingText", required = false) String recordingText) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 验证文件
            if (file == null || file.isEmpty()) {
                result.put("success", false);
                result.put("message", "录音文件不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || (!contentType.startsWith("audio/"))) {
                result.put("success", false);
                result.put("message", "只支持音频文件格式");
                return ResponseEntity.badRequest().body(result);
            }

            // 验证文件大小（限制为100MB）
            if (file.getSize() > 100 * 1024 * 1024) {
                result.put("success", false);
                result.put("message", "文件大小不能超过100MB");
                return ResponseEntity.badRequest().body(result);
            }

            // 生成录音ID
            String audioId = UUID.randomUUID().toString();
            
            // 先将音频文件上传到MinIO
            String minioUrl;
            try {
                minioUrl = minIOService.uploadFile(file);
                log.info("音频文件上传到MinIO成功，URL: {}", minioUrl);
            } catch (Exception e) {
                log.error("音频文件上传到MinIO失败: {}", e.getMessage(), e);
                result.put("success", false);
                result.put("message", "音频文件上传失败：" + e.getMessage());
                return ResponseEntity.internalServerError().body(result);
            }
            
            // 创建录音管理对象
            AudioManagement audioManagement = new AudioManagement();
            
            // 设置录音ID
            audioManagement.setId(audioId);
            
            // 设置基本信息
            audioManagement.setRecordingName(recordingName);
            if (recordingTime != null && !recordingTime.trim().isEmpty()) {
                audioManagement.setRecordingTime(LocalDateTime.parse(recordingTime));
            } else {
                audioManagement.setRecordingTime(LocalDateTime.now());
            }
            audioManagement.setSalesId(salesId);
            audioManagement.setSalesName(salesName);
            audioManagement.setSalesPhone(salesPhone);
            audioManagement.setDuration(duration);
            audioManagement.setCustomerId(customerId);
            audioManagement.setCustomerName(customerName);
            audioManagement.setCustomerPhone(customerPhone);
            audioManagement.setIntentionLevel(intentionLevel);
            audioManagement.setDealershipId(dealershipId);
            audioManagement.setDealershipName(dealershipName);
            audioManagement.setProjectId(projectId);
            audioManagement.setProjectName(projectName);
            audioManagement.setScriptModel(scriptModel);
            audioManagement.setScenario(scenario);
            audioManagement.setRemarks(remarks);
            audioManagement.setRecordingText(recordingText);
            
            // 设置文件信息（MinIO返回的URL和文件信息）
            audioManagement.setAudioFileOriginalName(file.getOriginalFilename());
            audioManagement.setAudioFileSize(file.getSize());
            audioManagement.setAudioFileExtension(getFileExtension(file.getOriginalFilename()));
            audioManagement.setAudioFileUrl(minioUrl); // 保存MinIO返回的URL
            
            // 设置时间
            audioManagement.setCreateTime(LocalDateTime.now());
            audioManagement.setUpdateTime(LocalDateTime.now());
            audioManagement.setUploadTime(LocalDateTime.now());
            
            // 设置同步状态默认值
            if (audioManagement.getServiceStatus() == null || audioManagement.getServiceStatus().trim().isEmpty()) {
                audioManagement.setServiceStatus(AudioManagementConstants.SERVICE_STATUS_IN_SERVICE);
            }
            
            // 保存录音记录到数据库
            boolean success = audioManagementService.save(audioManagement);
            if (success) {
                result.put("success", true);
                result.put("message", "录音添加成功");
                result.put("data", audioManagement);
                result.put("minioUrl", minioUrl);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "录音添加失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "录音添加异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String filename) {
        if (filename == null || filename.isEmpty()) {
            return "";
        }
        int lastDotIndex = filename.lastIndexOf('.');
        if (lastDotIndex == -1 || lastDotIndex == filename.length() - 1) {
            return "";
        }
        return filename.substring(lastDotIndex + 1).toLowerCase();
    }

    @PostMapping("/difyCallbackPLForCustomerProfile")
    @Operation(summary = "dify回调，为了客户画像完善", description = "dify回调，为了客户画像完善")
    public Map<String, Object> difyCallbackPLForCustomerProfile(@RequestBody String message){
        Map<String, Object> result = new HashMap<>();

        log.info("difyCallbackPLForCustomerProfile msg:  "+message.toString());
        result.put("code", 0);
        result.put("msg", "成功");
        result.put("data", "dify回调，为了客户画像完善,成功。");
        return result;
    }



    /**
     * 根据ID查询录音
     */
    @GetMapping("/get/{id}")
    @Operation(summary = "根据ID查询录音", description = "根据录音ID获取录音详细信息")
    public ResponseEntity<Map<String, Object>> getAudioById(
            @Parameter(description = "录音ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            AudioManagement audio = audioManagementService.getById(id);
            if (audio != null) {
                // 检查音频文件是否存在
                boolean fileExists = fileUploadService.audioFileExists(id);
                
                Map<String, Object> audioInfo = new HashMap<>();
                audioInfo.put("audio", audio);
                audioInfo.put("fileExists", fileExists);
                audioInfo.put("fileUrl", audio.getAudioFileUrl());
                audioInfo.put("fileSize", audio.getAudioFileSize());
                audioInfo.put("originalFileName", audio.getAudioFileOriginalName());
                
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", audioInfo);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "录音不存在");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据客户手机号查询录音
     */
    @GetMapping("/getByCustomerPhone")
    @Operation(summary = "根据客户手机号查询录音", description = "根据客户手机号查询录音信息")
    public ResponseEntity<Map<String, Object>> getAudioByCustomerPhone(
            @Parameter(description = "客户手机号", required = true)
            @RequestParam String customerPhone) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<AudioManagement> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AudioManagement::getCustomerPhone, customerPhone);
            List<AudioManagement> audioList = audioManagementService.list(queryWrapper);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", audioList);
            result.put("count", audioList.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
    @Autowired
    private DataEnrichmentUtil dataEnrichmentUtil;

    /**
     * 分页查询录音列表
     */
    @PostMapping("/list")
    @Operation(summary = "分页查询录音列表", description = "分页查询录音信息列表")
    public ResponseEntity<Map<String, Object>> getAudioList(
            @Parameter(description = "页码", example = "1")             @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10")             @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "录音名称（模糊查询）")             @RequestParam(required = false) String recordingName,
            @Parameter(description = "客户手机号（模糊查询）")             @RequestParam(required = false) String customerPhone,
            @Parameter(description = "客户姓名（模糊查询）")             @RequestParam(required = false) String customerName,
            @Parameter(description = "所属销售姓名（模糊查询）")            @RequestParam(required = false) String salesName,
            @Parameter(description = "所属门店ID")             @RequestParam(required = false) String dealershipId,
            @Parameter(description = "意向级别")             @RequestParam(required = false) String intentionLevel,
            @Parameter(description = "服务状态")             @RequestParam(required = false) String serviceStatus ,
            @Parameter(description = "销售人员电话（模糊查询）")             @RequestParam(required = false) String salesPhone,
            @Parameter(description = "场景")             @RequestParam(required = false) String scenario,
            @RequestHeader(value = "X-Role-Name", required = false) String roleName) {
        Map<String, Object> result = new HashMap<>();
        try {

            Page<AudioManagement> page = new Page<>(current, size);
            LambdaQueryWrapper<AudioManagement> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (recordingName != null && !recordingName.trim().isEmpty()) {
                queryWrapper.like(AudioManagement::getRecordingName, recordingName);
            }
            if (customerPhone != null && !customerPhone.trim().isEmpty()) {
                queryWrapper.like(AudioManagement::getCustomerPhone, customerPhone);
            }
            if (customerName != null && !customerName.trim().isEmpty()) {
                queryWrapper.like(AudioManagement::getCustomerName, customerName);
            }
            if (salesName != null && !salesName.trim().isEmpty()) {
                queryWrapper.like(AudioManagement::getSalesName, salesName);
            }
            if (dealershipId != null && !dealershipId.trim().isEmpty()) {
                queryWrapper.eq(AudioManagement::getDealershipId, dealershipId);
            }
            if (intentionLevel != null && !intentionLevel.trim().isEmpty()) {
                queryWrapper.eq(AudioManagement::getIntentionLevel, intentionLevel);
            }
            // 如果角色不包含admin，必须添加salesPhone查询条件
            if (!roleName.equalsIgnoreCase("admin")) {
                if (salesPhone != null && !salesPhone.trim().isEmpty()) {
                    queryWrapper.like(AudioManagement::getSalesPhone, salesPhone);
                }else {
                    log.warn("不是admin角色时, 必须通过手机号查询,  角色是：{}" ,roleName);

                    return ResponseEntity.ok(result);
                }
            } else if (roleName.contains("admin")) {
                // admin角色可以按salesPhone查询，但不强制
                if (salesPhone != null && !salesPhone.trim().isEmpty()) {
                    queryWrapper.like(AudioManagement::getSalesPhone, salesPhone);
                }
            }

            if (serviceStatus != null && !serviceStatus.trim().isEmpty()) { //AudioManagementConstants.SERVICE_STATUS_SERVICE_FINISH
                queryWrapper.eq(AudioManagement::getServiceStatus, serviceStatus);
            }
            if (scenario != null && !scenario.trim().isEmpty()) {
                queryWrapper.eq(AudioManagement::getScenario, scenario);
            }
            
            // 按创建时间倒序排列
            queryWrapper.orderByDesc(AudioManagement::getUpdateTime);
            
            Page<AudioManagement> audioPage = audioManagementService.page(page, queryWrapper);

            // 使用工具类提取ID列表
            List<String> dealershipIds = DataEnrichmentUtil.extractIds(audioPage.getRecords(), AudioManagement::getDealershipId);
            List<String> saleIds = DataEnrichmentUtil.extractIds(audioPage.getRecords(), AudioManagement::getSalesId);
            List<String> projectIds = DataEnrichmentUtil.extractIds(audioPage.getRecords(), AudioManagement::getProjectId);


            // 使用工具类批量获取关联数据
            Map<String, String> dealershipNameMap = dataEnrichmentUtil.getDealershipIdNameMap(dealershipIds);
            Map<String, String> saleNameMap = dataEnrichmentUtil.getSalesIdNameMap(saleIds);
            Map<String, String> salePhoneMap = dataEnrichmentUtil.getSalesIdPhoneMap(saleIds);
            Map<String, String> projectNameMap = dataEnrichmentUtil.getProjectIdNameMap(projectIds);
//            Map<String, String> customerNameMap = dataEnrichmentUtil.getCustomerNameMap(customerIds);

            audioPage.getRecords().forEach(audio -> {
                audio.setDealershipName(dealershipNameMap.getOrDefault(audio.getDealershipId(), ""));
                if (StringUtils.isEmpty( audio.getSalesName())) {
                    audio.setSalesName(saleNameMap.getOrDefault(audio.getSalesId(), ""));
                }
                audio.setSalesPhone(salePhoneMap.getOrDefault(audio.getSalesId(), ""));
                audio.setProjectName(projectNameMap.getOrDefault(audio.getProjectId(), ""));
//                audio.setCustomerName(customerNameMap.getOrDefault(audio.getCustomerId(), ""));
                //音频的url不要暴露对前端。
                if (audio.getAudioFileUrl() != null) {
                    audio.setAudioFileUrl( audio.getId());
                }
                // 注意：这里不需要检查文件存在性，因为实体类中已经有这些字段了
            });

            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", audioPage.getRecords());
            result.put("total", audioPage.getTotal());
            result.put("current", audioPage.getCurrent());
            result.put("size", audioPage.getSize());
            result.put("pages", audioPage.getPages());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("查询异常：{}", e.getMessage());
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

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

    @PutMapping("/updateForCustomerInfo")
    @Operation(summary = "更新录音信息", description = "更新录音详细信息")
    public ResponseEntity<Map<String, Object>> updateAudioForCustomer(
            @Parameter(description = "录音信息", required = true)
            @RequestBody AudioManagement audioManagement) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (audioManagement.getId() == null || audioManagement.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "录音ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            AudioManagement audioManagementDB = new AudioManagement();
            audioManagementDB.setUpdateTime(LocalDateTime.now());
            audioManagementDB.setCustomerName(audioManagement.getCustomerName());
            audioManagementDB.setCustomerPhone(audioManagement.getCustomerPhone());
            audioManagementDB.setRecordingName(audioManagement.getRecordingName());
            audioManagementDB.setId(audioManagement.getId());
            audioManagementDB.setRemarks(audioManagement.getRemarks());
            boolean success = audioManagementService.updateById(audioManagementDB);

            if (success) {
                // 同步更新客户信息
                try {
                    CustomerManagement customerToUpdate = null;
                    
                    // 优先通过 customerId 查找客户
                    if (audioManagement.getCustomerId() != null && !audioManagement.getCustomerId().trim().isEmpty()) {
                        customerToUpdate = customerManagementService.getById(audioManagement.getCustomerId());
                    }
                    
                    // 如果通过 customerId 没找到，且提供了 customerPhone，则通过联系方式查找
                    if (customerToUpdate == null && audioManagement.getCustomerPhone() != null && !audioManagement.getCustomerPhone().trim().isEmpty()) {
                        LambdaQueryWrapper<CustomerManagement> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(CustomerManagement::getContact, audioManagement.getCustomerPhone().trim());
                        List<CustomerManagement> customers = customerManagementService.list(queryWrapper);
                        if (customers != null && !customers.isEmpty()) {
                            customerToUpdate = customers.get(0);
                        }
                    }
                    
                    // 如果找到了客户，更新客户信息 ,录音总数加1
                    if (customerToUpdate != null) {
                        customerToUpdate.setCustomerName(audioManagement.getCustomerName());
                        customerToUpdate.setContact(audioManagement.getCustomerPhone());
                        customerToUpdate.setDetailedAddress(audioManagement.getRemarks());
                        customerToUpdate.setSalesPhone(audioManagement.getSalesPhone());
                        customerToUpdate.setSalesName(audioManagement.getSalesName());
                        customerToUpdate.setRecordingCount(customerToUpdate.getRecordingCount()+1);
                        customerToUpdate.setUpdateTime(LocalDateTime.now());
                        customerManagementService.updateById(customerToUpdate);
                        log.info("同步更新客户信息成功，客户ID: {}", customerToUpdate.getId());
                    } else {
                        log.warn("未找到对应的客户信息，无法同步更新。customerId: {}, customerPhone: {}",
                        audioManagement.getCustomerId(),   audioManagement.getCustomerPhone());

                        customerToUpdate = new CustomerManagement();
                        customerToUpdate.setCustomerName(audioManagement.getCustomerName());
                        customerToUpdate.setContact(audioManagement.getCustomerPhone());
                        customerToUpdate.setDetailedAddress(audioManagement.getRemarks());
                        customerToUpdate.setUpdateTime(LocalDateTime.now());
                        customerToUpdate.setRecordingCount(1);
                        customerToUpdate.setSalesPhone(audioManagement.getSalesPhone());
                        customerToUpdate.setSalesName(audioManagement.getSalesName());
                        customerManagementService.save(customerToUpdate);
                    }
                } catch (Exception e) {
                    // 客户信息更新失败不影响音频信息更新的结果，只记录日志
                    log.error("同步更新客户信息时发生异常: {}", e.getMessage(), e);
                }
                
                result.put("success", true);
                result.put("message", "录音信息更新成功");
                result.put("data", audioManagement);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "录音信息更新失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }


    @Autowired
    private com.rj.service.IAudioManagementSegmentsService audioManagementSegmentsService;

    /**
     * 更新录音信息
     */
    @PostMapping("/finishServiceById")
    @Operation(summary = "finishService", description = "finishService")
    public ResponseEntity<Map<String, Object>> finishServiceById(
            @Parameter(description = "录音信息", required = true)
            @RequestBody AudioManagement audioManagement) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (audioManagement.getId() == null || audioManagement.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "录音ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 先从数据库查询完整的录音信息
            AudioManagement audioManagementFromDB = audioManagementService.getById(audioManagement.getId());
            if (audioManagementFromDB == null) {
                result.put("success", false);
                result.put("message", "录音不存在");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 查询客户表 customer_management，如果客户手机号或客户名称为空，不允许结束服务
            String customerId = audioManagementFromDB.getCustomerId();
            CustomerManagement customer = null;
            if (customerId != null && !customerId.trim().isEmpty()) {
                customer = customerManagementService.getById(customerId);
                if (customer != null) {
                    // 检查客户手机号（contact）和客户名称（customerName）是否为空
                    String contact = customer.getContact();
                    String customerName = customer.getCustomerName();
                    
                    if ((contact == null || contact.trim().isEmpty()) || 
                        (customerName == null || customerName.trim().isEmpty())) {
                        result.put("success", false);
                        result.put("message", "客户信息不完整，请先补充客户手机号和客户名称");
                        return ResponseEntity.badRequest().body(result);
                    }
                }
            }

            LambdaQueryWrapper<AudioManagementSegments> audioQuery = new LambdaQueryWrapper<>();
            audioQuery.eq(AudioManagementSegments::getParentId, audioManagement.getId()) ; // 关联这个id的所有录音片段
            List<AudioManagementSegments> segmentsList = audioManagementSegmentsService.list(audioQuery);
            BigDecimal total = BigDecimal.ZERO;
            for (AudioManagementSegments segment2 : segmentsList) {
                if (segment2.getDuration() != null) {
                    total = total.add(segment2.getDuration());//分钟
                }
            }

            AudioManagement audio = new AudioManagement();
            audio.setUpdateTime(LocalDateTime.now());
            audio.setServiceStatus(AudioManagementConstants.SERVICE_STATUS_SERVICE_FINISH);
            audio.setId(audioManagement.getId());
            audio.setDuration(total);
            audio.setEndTime( LocalDateTime.now());

            boolean success = audioManagementService.updateById(audio);
            
            // 根据已校验的客户记录，将 customer_management.recording_count 加 1（无客户或查不到客户则跳过）
            if (customer != null) {
                try {
                    CustomerManagement customerForUpdate = new CustomerManagement();
                    customerForUpdate.setId(customer.getId());
                    customerForUpdate.setUpdateTime(LocalDateTime.now());
                    Integer rc = customer.getRecordingCount();
                    customerForUpdate.setRecordingCount(rc == null ? 1 : rc + 1);
                    customerManagementService.updateById(customerForUpdate);
                    log.info("更新客户录音数成功，客户ID: {}", customer.getId());
                } catch (Exception e) {
                    // 客户录音数更新失败不影响录音服务结束的结果，只记录日志
                    log.error("更新客户录音数时发生异常: {}", e.getMessage(), e);
                }
            }


            if (success) {
                result.put("success", true);
                result.put("message", "录音finishServiceById更新成功");
                result.put("data", audioManagement);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "录音finishServiceById更新失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
    /**
     * 更新录音信息
     */
    @PostMapping("/AIAnlyzById")
    @Operation(summary = "AI分析", description = "AI分析的总入口")
    public ResponseEntity<Map<String, Object>> AIAnlyById(
            @Parameter(description = "录音信息", required = true)
            @RequestBody AudioManagement audioManagement) {
        Map<String, Object> result = new HashMap<>();
        boolean success = true;
        try {
            if (audioManagement.getId() == null || audioManagement.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "录音ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            // 1. 根据ID查询家具意向分析记录
            AudioManagement audioManagementFromDB = audioManagementService.getById(audioManagement.getId());
            if (audioManagementFromDB == null) {
                result.put("success", false);
                result.put("message", "记录不存在");
                return ResponseEntity.badRequest().body(result);
            }
            // 2. 检查summary字段，如果已存在总结内容，直接返回提示，不进行AI分析
            String summary = audioManagement.getSummary();
            if (summary != null && !summary.trim().isEmpty()) {
                result.put("success", true);
                result.put("message", "AI分析已完成");
                result.put("data", audioManagement);
                return ResponseEntity.ok(result);
            }
            // 3. 获取录音文本；如主表为空，则从分段表拼接
            String recordingText = audioManagementFromDB.getRecordingText();
            if (recordingText == null || recordingText.trim().isEmpty()) {
                LambdaQueryWrapper<AudioManagementSegments> segQuery = new LambdaQueryWrapper<>();
                segQuery.eq(AudioManagementSegments::getParentId, audioManagementFromDB.getId())
                        .orderByAsc(AudioManagementSegments::getChunkIndex);
                List<AudioManagementSegments> segmentList = audioManagementSegmentsService.list(segQuery);
                int  emptyCount = 0 ;
                StringBuilder mergedText = new StringBuilder();
                if (segmentList != null && !segmentList.isEmpty()) {
                    for (AudioManagementSegments seg : segmentList) {
                        String segText = seg.getRecordingText();
                        if (segText != null && !segText.trim().isEmpty()) {
                            if (mergedText.length() > 0) {
                                mergedText.append("\n");
                            }
                            mergedText.append(segText.trim());
                        }else {
                            emptyCount ++;
                        }
                    }
                }
                if (mergedText.length() > 0) {
                    recordingText = mergedText.toString();
                    audioManagementFromDB.setRecordingText(recordingText);
                }
                log.info(" AudioManagementSegments 总数是：  {} ，未转文本记录条数是： {}",segmentList.size(), emptyCount);
            }

            if (recordingText == null || recordingText.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "录音文本为空");
                return ResponseEntity.badRequest().body(result);
            }

            // 4. 根据场景动态选择业务场景类型，调用业务层通用服务生成总结
            AudioAnalysisSceneType sceneType = resolveSceneType(audioManagementFromDB.getScenario());


            // 4. 通过业务层通用服务调用大模型生成总结并保存数据
//            AudioTextAnalysisFurniture furniture = audioTextAnalysisLlmService.generateSummaryAndSave(
//                    sceneType,
//                    recordingText,
//                    audioManagement.getId(),
//                    audioManagement.getSalesName(),
//                    audioManagement.getSalesPhone(),
//                    audioManagement.getCustomerName(),
//                    audioManagement.getCustomerPhone()
//            );
            AudioTextAnalysisFurniture furniture = audioTextAnalysisLlmService.generateSummaryAndSave_V2(
                    sceneType,
                    recordingText,
                    audioManagement.getId(),
                    audioManagement.getSalesName(),
                    audioManagement.getSalesPhone(),
                    audioManagement.getCustomerName(),
                    audioManagement.getCustomerPhone()
            );
            log.info("llm return  furniture Analysis   : ",furniture.toString() );
            if (recordingText == null || recordingText.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "录音文本为空");
                return ResponseEntity.badRequest().body(result);
            } else {
                result.put("success", true);
                result.put("message", "录音finishServiceById更新成功");
                result.put("data", audioManagement);
                return ResponseEntity.ok(result);
            }


        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }


    @PostMapping("/AIAnlyzByIdForDetail")
    @Operation(summary = "AI分析", description = "AI分析的总入口")
    public ResponseEntity<Map<String, Object>> AIAnlyByIdForDetail(
            @Parameter(description = "录音信息", required = true)
            @RequestBody AudioManagement audioManagement) {
        Map<String, Object> result = new HashMap<>();
        boolean success = true;
        try {
            if (audioManagement.getId() == null || audioManagement.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "录音ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            // 1. 根据ID查询家具意向分析记录
            AudioManagement audioManagementFromDB = audioManagementService.getById(audioManagement.getId());
            if (audioManagementFromDB == null) {
                result.put("success", false);
                result.put("message", "记录不存在");
                return ResponseEntity.badRequest().body(result);
            }
            // 2. 检查summary字段，如果已存在总结内容，直接返回提示，不进行AI分析
            String summary = audioManagement.getSummary();
            if (summary != null && !summary.trim().isEmpty()) {
                result.put("success", true);
                result.put("message", "AI分析已完成");
                result.put("data", audioManagement);
//                return ResponseEntity.ok(result);
            }
            // 3. 获取录音文本；如主表为空，则从分段表拼接
            String recordingText = audioManagementFromDB.getRecordingText();


            if (recordingText == null || recordingText.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "录音文本为空");
                return ResponseEntity.badRequest().body(result);
            }

            // 4. 根据场景动态选择业务场景类型，调用业务层通用服务生成总结
            AudioAnalysisSceneType sceneType = resolveSceneType(audioManagementFromDB.getScenario());

            AudioTextAnalysisFurniture furniture = audioTextAnalysisLlmService.generateSummaryAndSaveForDetail(
                    sceneType,
                    recordingText,
                    audioManagement.getId(),
                    audioManagement.getSalesName(),
                    audioManagement.getSalesPhone(),
                    audioManagement.getCustomerName(),
                    audioManagement.getCustomerPhone()
            );
            log.info("llm return  furniture Analysis   : ",furniture.toString() );
            if (recordingText == null || recordingText.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "录音文本为空");
                return ResponseEntity.badRequest().body(result);
            } else {
                result.put("success", true);
                result.put("message", "录音finishServiceById更新成功");
                result.put("data", audioManagement);
                return ResponseEntity.ok(result);
            }


        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据录音场景字符串解析为大模型分析场景类型
     */
    private AudioAnalysisSceneType resolveSceneType(String scenario) {

        String s = scenario.trim().toUpperCase();
        // 根据约定的大写场景值进行映射

        if (SCENARIO_SOFT_SALE.equals(s)) {
            return AudioAnalysisSceneType.SCENARIO_SOFT_SALE;
        }
        if (SCENARIO_SMALL_BEEUTIFUL_SALE.equals(s)) {
            return AudioAnalysisSceneType.SCENARIO_SMALL_BEEUTIFUL_SALE;
        }

        if (SCENARIO_FURNITURE_SALE.equals(s)) {
            return AudioAnalysisSceneType.SCENARIO_FURNITURE_SALE;
        }
        if (SCENARIO_SUMMARY.equals(s)) {
            return AudioAnalysisSceneType.SCENARIO_SUMMARY;
        }
        if (SCENARIO_CAR_SALE.equals(s)) {
            return AudioAnalysisSceneType.SCENARIO_CAR_SALE;
        }
        // 未识别场景时，默认按会议场景处理
        return AudioAnalysisSceneType.SCENARIO_SOFT_SALE;
    }


    /**
     * 根据ID删除录音
     */
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除录音", description = "根据录音ID删除录音信息")
    public ResponseEntity<Map<String, Object>> deleteAudio(
            @Parameter(description = "录音ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = audioManagementService.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) {
            result.put("success", false);
            result.put("message", "删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 批量删除录音
     */
    @DeleteMapping("/batchDelete")
    @Operation(summary = "批量删除录音", description = "根据录音ID列表批量删除录音信息")
    public ResponseEntity<Map<String, Object>> batchDeleteAudios(
            @Parameter(description = "录音ID列表", required = true)
            @RequestBody List<String> ids) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (ids == null || ids.isEmpty()) {
                result.put("success", false);
                result.put("message", "录音ID列表不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            boolean success = audioManagementService.removeByIds(ids);
            if (success) {
                result.put("success", true);
                result.put("message", "批量删除成功，共删除 " + ids.size() + " 条记录");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "批量删除失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取录音统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取录音统计信息", description = "获取录音总数等统计信息")
    public ResponseEntity<Map<String, Object>> getAudioStatistics() {
        Map<String, Object> result = new HashMap<>();
        try {
            long totalCount = audioManagementService.count();
            
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalAudios", totalCount);
            
            result.put("success", true);
            result.put("message", "统计信息获取成功");
            result.put("data", statistics);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "统计信息获取异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取音频文件的预签名URL
     * 短期播放: 1小时（3600秒）
       正常使用: 7天（604800秒）
       长期访问: 30天（2592000秒）

     */
    @PostMapping("/presigned-url")
    @Operation(summary = "获取音频文件预签名URL", description = "根据录音ID和URL获取音频文件的预签名访问URL")
    public ResponseEntity<Map<String, Object>> getAudioPresignedUrl(
            @Parameter(description = "录音ID", required = false)
            @RequestParam(required = false) String audioId,
            @Parameter(description = "录音文件URL", required = false)
            @RequestParam(required = false) String audioFileUrl,
            @Parameter(description = "过期时间（秒），默认1小时")
            @RequestParam(defaultValue = "3600") int expires){
        Map<String, Object> result = new HashMap<>();
        try {
            String finalAudioFileUrl = null;
            String finalAudioId = null;
            

            // 如果录音文件URL为空，则通过录音ID查询数据库
             if (audioId != null && !audioId.trim().isEmpty()) {
                AudioManagement audio = audioManagementService.getById(audioId);
                if (audio == null) {
                    result.put("success", false);
                    result.put("message", "录音不存在");
                    return ResponseEntity.notFound().build();
                }
                
                finalAudioFileUrl = audio.getAudioFileUrl();
                finalAudioId = audioId;
                log.info("从数据库查询录音文件URL: {}", finalAudioFileUrl);
            } 
            // 如果两个参数都为空，返回错误
            else {
                result.put("success", false);
                result.put("message", "录音ID和录音文件URL不能同时为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 检查最终的文件URL是否有效
            if (finalAudioFileUrl == null || finalAudioFileUrl.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "音频文件URL为空");
                return ResponseEntity.badRequest().body(result);
            }

            // 提取文件名
            String fileName = finalAudioFileUrl.substring(finalAudioFileUrl.lastIndexOf("/") + 1);
            
            // 生成新的预签名URL
            String presignedUrl = minIOService.getPresignedUrl(fileName, expires);
            
            if (presignedUrl != null) {
                result.put("success", true);
                result.put("message", "预签名URL生成成功");
                result.put("audioId", finalAudioId);
                result.put("fileName", fileName);
                result.put("presignedUrl", presignedUrl);
                result.put("expires", expires);
                result.put("expiresInHours", expires / 3600);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "预签名URL生成失败");
                return ResponseEntity.internalServerError().body(result);
            }
        } catch (Exception e) {
            log.error("获取音频文件预签名URL异常：{}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "获取预签名URL异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 批量分配录音到项目
     */
    @PostMapping("/allocateProject")
    @Operation(summary = "批量分配录音到项目", description = "将多个录音批量分配到指定项目")
    public ResponseEntity<Map<String, Object>> allocateProject(
            @Parameter(description = "录音ID列表", required = true)
            @RequestParam List<String> audioIds,
            @Parameter(description = "项目ID", required = true)
            @RequestParam String projectId,
            @Parameter(description = "项目名称", required = true)
            @RequestParam String projectName) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 验证参数
            if (audioIds == null || audioIds.isEmpty()) {
                result.put("success", false);
                result.put("message", "录音ID列表不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            if (projectId == null || projectId.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "项目ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            if (projectName == null || projectName.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "项目名称不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            // 批量更新录音记录
            int successCount = 0;
            int failureCount = 0;
            List<String> failedIds = new java.util.ArrayList<>();
            
            for (String audioId : audioIds) {
                try {
                    AudioManagement audio = audioManagementService.getById(audioId);
                    if (audio != null) {
                        audio.setProjectId(projectId);
                        audio.setProjectName(projectName);
                        audio.setUpdateTime(LocalDateTime.now());
                        
                        boolean updated = audioManagementService.updateById(audio);
                        if (updated) {
                            successCount++;
                            log.info("录音分配项目成功：audioId={}, projectId={}, projectName={}", 
                                    audioId, projectId, projectName);
                        } else {
                            failureCount++;
                            failedIds.add(audioId);
                            log.warn("录音分配项目失败：audioId={}", audioId);
                        }
                    } else {
                        failureCount++;
                        failedIds.add(audioId);
                        log.warn("录音不存在：audioId={}", audioId);
                    }
                } catch (Exception e) {
                    failureCount++;
                    failedIds.add(audioId);
                    log.error("录音分配项目异常：audioId={}, error={}", audioId, e.getMessage());
                }
            }
            
            // 构建返回结果
            result.put("success", true);
            result.put("message", "批量分配完成");
            result.put("totalCount", audioIds.size());
            result.put("successCount", successCount);
            result.put("failureCount", failureCount);
            result.put("projectId", projectId);
            result.put("projectName", projectName);
            
            if (failureCount > 0) {
                result.put("failedIds", failedIds);
                result.put("message", String.format("批量分配完成，成功：%d，失败：%d", successCount, failureCount));
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("批量分配录音到项目异常：{}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "批量分配异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 批量分配录音到销售人员
     */
    @PostMapping("/allocateSales")
    @Operation(summary = "批量分配录音到销售人员", description = "将多个录音批量分配到指定销售人员")
    public ResponseEntity<Map<String, Object>> allocateSales(
            @Parameter(description = "录音ID列表", required = true)
            @RequestParam List<String> audioIds,
            @Parameter(description = "销售人员ID", required = true)
            @RequestParam String salesId,
            @Parameter(description = "销售人员姓名", required = true)
            @RequestParam String salesName) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 验证参数
            if (audioIds == null || audioIds.isEmpty()) {
                result.put("success", false);
                result.put("message", "录音ID列表不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            if (salesId == null || salesId.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "销售人员ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            if (salesName == null || salesName.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "销售人员姓名不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            // 批量更新录音记录
            int successCount = 0;
            int failureCount = 0;
            List<String> failedIds = new java.util.ArrayList<>();
            
            for (String audioId : audioIds) {
                try {
                    AudioManagement audio = audioManagementService.getById(audioId);
                    if (audio != null) {
                        audio.setSalesId(salesId);
                        audio.setSalesName(salesName);
                        audio.setUpdateTime(LocalDateTime.now());
                        
                        boolean updated = audioManagementService.updateById(audio);
                        if (updated) {
                            successCount++;
                            log.info("录音分配销售人员成功：audioId={}, salesId={}, salesName={}", 
                                    audioId, salesId, salesName);
                        } else {
                            failureCount++;
                            failedIds.add(audioId);
                            log.warn("录音分配销售人员失败：audioId={}", audioId);
                        }
                    } else {
                        failureCount++;
                        failedIds.add(audioId);
                        log.warn("录音不存在：audioId={}", audioId);
                    }
                } catch (Exception e) {
                    failureCount++;
                    failedIds.add(audioId);
                    log.error("录音分配销售人员异常：audioId={}, error={}", audioId, e.getMessage());
                }
            }
            
            // 构建返回结果
            result.put("success", true);
            result.put("message", "批量分配完成");
            result.put("totalCount", audioIds.size());
            result.put("successCount", successCount);
            result.put("failureCount", failureCount);
            result.put("salesId", salesId);
            result.put("salesName", salesName);
            
            if (failureCount > 0) {
                result.put("failedIds", failedIds);
                result.put("message", String.format("批量分配完成，成功：%d，失败：%d", successCount, failureCount));
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("批量分配录音到销售人员异常：{}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "批量分配异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 录音转文本
     */
    @PostMapping("/convertAudioToText")
    @Operation(summary = "录音转文本", description = "将录音文件转换为文本内容")
    public ResponseEntity<Map<String, Object>> convertAudioToText(
            @Parameter(description = "录音ID", required = true)
            @RequestParam String audioId,
            @Parameter(description = "录音名称", required = true)
            @RequestParam String audioName) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 验证参数
            if (audioId == null || audioId.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "录音ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            if (audioName == null || audioName.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "录音名称不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            // 检查录音是否存在
            AudioManagement audio = audioManagementService.getById(audioId);
            if (audio == null) {
                result.put("success", false);
                result.put("message", "录音不存在");
                return ResponseEntity.notFound().build();
            }

            // 检查录音文件URL是否存在
            String audioFileUrl = audio.getAudioFileUrl();
            if (audioFileUrl == null || audioFileUrl.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "录音文件不存在");
                return ResponseEntity.badRequest().body(result);
            }

            // 提取文件名
            String fileName = audioFileUrl.substring(audioFileUrl.lastIndexOf("/") + 1);
            
            // 生成音频文件的预签名URL用于ASR服务
            String presignedUrl = minIOService.getPresignedUrl(fileName, 3600); // 1小时有效期
            
            if (presignedUrl == null) {
                result.put("success", false);
                result.put("message", "生成音频文件访问URL失败");
                return ResponseEntity.internalServerError().body(result);
            }
            
            // 创建ASR请求对象
            AsrRequest asrRequest = new AsrRequest();
            asrRequest.setAudioUrl(presignedUrl);
            asrRequest.setAudioName(audioName);
            asrRequest.setModel("paraformer-v2"); // 使用默认模型
            asrRequest.setFormat("wav"); // 默认格式
            asrRequest.setSampleRate(16000); // 默认采样率
            asrRequest.setEnablePunctuation(true); // 启用标点符号
            asrRequest.setEnableNumberConversion(true); // 启用数字转换
            asrRequest.setEnableSpeakerDiarization(false); // 不启用说话人分离
            
            // 调用ASR服务进行语音识别
            AsrResponse asrResponse = ttsRequestLogService.speechToText(asrRequest);
            
            if (!asrResponse.isSuccess()) {
                result.put("success", false);
                result.put("message", "语音识别失败：" + asrResponse.getMessage());
                return ResponseEntity.internalServerError().body(result);
            }
            
            String recognizedText = asrResponse.getText();
            
            // 更新录音记录中的文本内容
            audio.setRecordingText(recognizedText);
            audio.setUpdateTime(LocalDateTime.now());
            
            boolean updated = audioManagementService.updateById(audio);
            
            if (updated) {
                result.put("success", true);
                result.put("message", "录音转文本成功");
                result.put("audioId", audioId);
                result.put("audioName", audioName);
                result.put("recognizedText", recognizedText);
                result.put("textLength", recognizedText.length());
                result.put("taskId", asrResponse.getTaskId());
                result.put("requestId", asrResponse.getRequestId());
                result.put("duration", asrResponse.getDuration());
                result.put("processingTimeMs", asrResponse.getProcessingTimeMs());
                
                log.info("录音转文本成功：audioId={}, audioName={}, textLength={}, taskId={}", 
                        audioId, audioName, recognizedText.length(), asrResponse.getTaskId());
                
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "录音转文本成功但更新数据库失败");
                result.put("recognizedText", recognizedText);
                result.put("taskId", asrResponse.getTaskId());
                return ResponseEntity.internalServerError().body(result);
            }
            
        } catch (Exception e) {
            log.error("录音转文本异常：{}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "录音转文本异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }


    /**
     * 获取录音的音频文件信息
     */
    @GetMapping("/{id}/audio-info")
    @Operation(summary = "获取录音的音频文件信息", description = "根据录音ID获取音频文件信息")
    public ResponseEntity<Map<String, Object>> getAudioFileInfo(
            @Parameter(description = "录音ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查录音是否存在
            AudioManagement audio = audioManagementService.getById(id);
            if (audio == null) {
                result.put("success", false);
                result.put("message", "录音不存在");
                return ResponseEntity.notFound().build();
            }

            // 检查音频文件是否存在
            boolean fileExists = fileUploadService.audioFileExists(id);
            String fileUrl = null;
            
            if (fileExists) {
                fileUrl = fileUploadService.getAudioFileUrl(id);
            }

            Map<String, Object> audioInfo = new HashMap<>();
            audioInfo.put("audioId", id);
            audioInfo.put("fileExists", fileExists);
            audioInfo.put("fileUrl", fileUrl);
            audioInfo.put("audioInfo", audio);

            result.put("success", true);
            result.put("message", "获取成功");
            result.put("data", audioInfo);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取音频文件信息异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 删除录音及其音频文件
     */
    @DeleteMapping("/deleteWithFile/{id}")
    @Operation(summary = "删除录音及其音频文件", description = "根据录音ID删除录音信息及其关联的音频文件")
    public ResponseEntity<Map<String, Object>> deleteAudioWithFile(
            @Parameter(description = "录音ID", required = true)
            @PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取录音记录
            AudioManagement audio = audioManagementService.getById(id);
            if (audio == null) {
                result.put("success", false);
                result.put("message", "录音记录不存在");
                return ResponseEntity.notFound().build();
            }

            // 先删除音频文件
            boolean fileDeleted = fileUploadService.deleteAudioFile(id);
            
            // 清空录音记录中的文件信息
            audio.setAudioFilePath(null);
            audio.setAudioFileUrl(null);
            audio.setAudioFileSize(null);
            audio.setAudioFileOriginalName(null);
            audio.setAudioFileExtension(null);
            audio.setUpdateTime(LocalDateTime.now());
            
            boolean recordUpdated = audioManagementService.updateById(audio);
            
            if (recordUpdated) {
                result.put("success", true);
                result.put("message", "录音及其音频文件删除成功");
                result.put("fileDeleted", fileDeleted);
                result.put("recordUpdated", recordUpdated);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "录音记录更新失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}
