package com.ruoyi.web.controller.base;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.base.domain.RobotOpsBroadcastContent;
import com.ruoyi.base.service.IRobotOpsBroadcastContentService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 播报内容Controller
 *
 * @author ruoyi
 * @date 2026-04-27
 */
@RestController
@RequestMapping("/base/broadcastContent")
public class RobotOpsBroadcastContentController extends BaseController
{
    @Autowired
    private IRobotOpsBroadcastContentService robotOpsBroadcastContentService;

    /**
     * 查询播报内容列表
     */
    @PreAuthorize("@ss.hasPermi('base:broadcastContent:list')")
    @GetMapping("/list")
    public TableDataInfo list(RobotOpsBroadcastContent robotOpsBroadcastContent)
    {
        startPage();
        List<RobotOpsBroadcastContent> list = robotOpsBroadcastContentService.selectRobotOpsBroadcastContentList(robotOpsBroadcastContent);
        return getDataTable(list);
    }

    /**
     * 导出播报内容列表
     */
    @PreAuthorize("@ss.hasPermi('base:broadcastContent:export')")
    @Log(title = "播报内容", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RobotOpsBroadcastContent robotOpsBroadcastContent)
    {
        List<RobotOpsBroadcastContent> list = robotOpsBroadcastContentService.selectRobotOpsBroadcastContentList(robotOpsBroadcastContent);
        ExcelUtil<RobotOpsBroadcastContent> util = new ExcelUtil<RobotOpsBroadcastContent>(RobotOpsBroadcastContent.class);
        util.exportExcel(response, list, "播报内容数据");
    }

    /**
     * 获取播报内容详细信息
     */
    @PreAuthorize("@ss.hasPermi('base:broadcastContent:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(robotOpsBroadcastContentService.selectRobotOpsBroadcastContentById(id));
    }

    /**
     * 新增播报内容
     * 新增时会自动触发音频合成
     */
    @PreAuthorize("@ss.hasPermi('base:broadcastContent:add')")
    @Log(title = "播报内容", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RobotOpsBroadcastContent robotOpsBroadcastContent)
    {
        // 如果传入了播报文本，设置默认状态
        if (robotOpsBroadcastContent.getAudioStatus() == null)
        {
            robotOpsBroadcastContent.setAudioStatus("0");
        }
        int rows = robotOpsBroadcastContentService.insertRobotOpsBroadcastContent(robotOpsBroadcastContent);
        if (rows > 0)
        {
            // 返回成功消息，提示音频合成将在后台进行
            return success("播报内容新增成功，音频合成任务已提交")
                    .put("data", robotOpsBroadcastContent);
        }
        return error("新增失败");
    }

    /**
     * 修改播报内容
     * 修改播报文本时会自动触发重新合成
     */
    @PreAuthorize("@ss.hasPermi('base:broadcastContent:edit')")
    @Log(title = "播报内容", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RobotOpsBroadcastContent robotOpsBroadcastContent)
    {
        int rows = robotOpsBroadcastContentService.updateRobotOpsBroadcastContent(robotOpsBroadcastContent);
        if (rows > 0)
        {
            // 检查是否正在合成
            boolean synthesizing = robotOpsBroadcastContentService.isSynthesizing(robotOpsBroadcastContent.getId());
            if (synthesizing)
            {
                return success("播报内容修改成功，音频正在重新合成中");
            }
            return success("播报内容修改成功");
        }
        return error("修改失败");
    }

    /**
     * 删除播报内容
     */
    @PreAuthorize("@ss.hasPermi('base:broadcastContent:remove')")
    @Log(title = "播报内容", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(robotOpsBroadcastContentService.deleteRobotOpsBroadcastContentByIds(ids));
    }

    /**
     * 合成音频（异步）
     * POST /base/broadcastContent/synthesize/{id}
     */
    @PreAuthorize("@ss.hasPermi('base:broadcastContent:edit')")
    @Log(title = "播报内容-合成音频", businessType = BusinessType.UPDATE)
    @PostMapping("/synthesize/{id}")
    public AjaxResult synthesizeAudio(@PathVariable Long id)
    {
        // 检查内容是否存在
        RobotOpsBroadcastContent content = robotOpsBroadcastContentService.selectRobotOpsBroadcastContentById(id);
        if (content == null)
        {
            return error("播报内容不存在");
        }

        // 检查是否正在合成中
        if (robotOpsBroadcastContentService.isSynthesizing(id))
        {
            return warn("正在合成中，请稍后再试");
        }

        // 检查播报文本是否为空
        if (content.getBroadcastText() == null || content.getBroadcastText().trim().isEmpty())
        {
            return error("播报文本不能为空");
        }

        // 触发异步合成
        robotOpsBroadcastContentService.synthesizeAudio(id);
        return success("音频合成任务已提交，请在列表中查看合成状态");
    }

    /**
     * 重新合成音频（异步）
     * POST /base/broadcastContent/regenerate/{id}
     */
    @PreAuthorize("@ss.hasPermi('base:broadcastContent:edit')")
    @Log(title = "播报内容-重新合成音频", businessType = BusinessType.UPDATE)
    @PostMapping("/regenerate/{id}")
    public AjaxResult regenerateAudio(@PathVariable Long id)
    {
        // 检查内容是否存在
        RobotOpsBroadcastContent content = robotOpsBroadcastContentService.selectRobotOpsBroadcastContentById(id);
        if (content == null)
        {
            return error("播报内容不存在");
        }

        // 检查是否正在合成中
        if (robotOpsBroadcastContentService.isSynthesizing(id))
        {
            return warn("正在合成中，请稍后再试");
        }

        // 检查播报文本是否为空
        if (content.getBroadcastText() == null || content.getBroadcastText().trim().isEmpty())
        {
            return error("播报文本不能为空");
        }

        // 触发异步重新合成
        robotOpsBroadcastContentService.regenerateAudio(id);
        return success("音频重新合成任务已提交，请在列表中查看合成状态");
    }
}
