<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="96px">
      <!-- <el-form-item label="主键" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入主键"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目id" prop="xmid">
        <el-input
          v-model="queryParams.xmid"
          placeholder="请输入项目id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="会议名称" prop="hymc">
        <el-input v-model="queryParams.hymc" placeholder="请输入会议名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="解析状态" prop="jxzt">
        <el-input v-model="queryParams.jxzt" placeholder="请输入解析状态" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="解析完成时间" prop="jxwcsj">
        <el-date-picker clearable v-model="queryParams.jxwcsj" type="datetime" format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择解析完成时间">
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="创建人" prop="createdBy">
        <el-input v-model="queryParams.createdBy" placeholder="请输入创建人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createdTime">
        <el-date-picker clearable v-model="queryParams.createdTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="备用1" prop="ext1">
        <el-input v-model="queryParams.ext1" placeholder="请输入备用1" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="备用2" prop="ext2">
        <el-input v-model="queryParams.ext2" placeholder="请输入备用2" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="备用3" prop="ext3">
        <el-input v-model="queryParams.ext3" placeholder="请输入备用3" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['hyjyxx:hyjyxx:add']">新增</el-button>
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['hyjyxx:hyjyxx:edit']">修改</el-button>
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['hyjyxx:hyjyxx:remove']">删除</el-button>
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['hyjyxx:hyjyxx:export']">导出</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
      </el-col>
      <el-col :span="1.5">
      </el-col>
      <el-col :span="1.5">
      </el-col>
      <el-col :span="1.5">
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->

    <el-table border v-loading="loading" :data="hyjyxxList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <!-- <el-table-column label="项目id" align="center" prop="xmid" /> -->
      <el-table-column label="会议名称" align="center" prop="hymc" min-width="130" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-link type="primary" @click="goDetail(scope.row)">{{ scope.row.hymc }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="音频文件名称" align="center" prop="ypwjName" min-width="140" show-overflow-tooltip />
      <el-table-column label="会议模版名称" align="center" prop="mbmc" min-width="140" show-overflow-tooltip />
      <el-table-column label="音频开始时间" align="center" prop="jxwcsj" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.jxwcsj, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="解析状态" align="center" prop="jxzt" min-width="90" show-overflow-tooltip />
      <!-- <el-table-column label="原文" align="center" prop="yw" min-width="140" show-overflow-tooltip />
      <el-table-column label="会议纪要" align="center" prop="hyjy" min-width="140" show-overflow-tooltip />
      <el-table-column label="解析完成时间" align="center" prop="jxwcsj" min-width="100" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.jxwcsj, '{y}-{m}-{d}') }}</span>
        </template>
</el-table-column> -->
      <!-- <el-table-column label="创建人" align="center" prop="createdBy" />
      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备用1" align="center" prop="ext1" />
      <el-table-column label="备用2" align="center" prop="ext2" />
      <el-table-column label="备用3" align="center" prop="ext3" /> -->
      <el-table-column label="操作" min-width="200" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['hyjyxx:hyjyxx:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['hyjyxx:hyjyxx:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-bottom-right" @click="handleKszr(scope.row)">开始转录</el-button>
          <el-button size="mini" type="text" icon="el-icon-document" @click="handleHyjyxxFile(scope.row)">截图管理</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改会议信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="98px">
        <!-- <el-form-item label="项目id" prop="xmid">
          <el-input v-model="form.xmid" placeholder="请输入项目id" />
        </el-form-item> -->
        <el-form-item label="会议名称" prop="hymc">
          <el-input v-model="form.hymc" placeholder="请输入内容" />
        </el-form-item>
        <!-- <el-form-item label="解析状态" prop="jxzt">
          <el-input v-model="form.jxzt" placeholder="请输入解析状态" />
        </el-form-item> -->
        <el-form-item label="会议音频上传" prop="ypwj">
          <el-upload drag :headers="upload.headers" :action="upload.url" :limit="1" :auto-upload="true"
            accept=".mp3,.wav,.wma,.aac,.3gp,.m4a" :on-success="handleAudioSuccess" :on-error="handleAudioError"
            :file-list="audioFileList">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">点击或拖动到此区域</div>
            <div class="el-upload__tip" slot="tip">格式支持: mp3,wav,wma,aac,3gp,m4a</div>
          </el-upload>
          <!-- <el-input v-if="form.ypwj" v-model="form.ypwj" placeholder="文件上传后返回的路径" readonly style="margin-top: 8px;" /> -->
        </el-form-item>
        <el-form-item label="会议模版" prop="mbmc">
          <el-select v-model="form.mbmc" placeholder="请选择会议模版" filterable style="width: 100%"
            @change="handleHymbChange">
            <el-option v-for="item in hymbOptions" :key="item.id || item.value || item.mbmc"
              :label="item.mbmc || item.label" :value="item.id || item.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="会议纪要" prop="hyjy">
          <el-input v-model="form.hyjy" type="textarea" placeholder="请输入内容" />
        </el-form-item> -->
        <el-form-item label="音频开始时间" prop="jxwcsj">
          <el-date-picker clearable v-model="form.jxwcsj" type="datetime" format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择会议开始时间" style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="创建人" prop="createdBy">
          <el-input v-model="form.createdBy" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createdTime">
          <el-date-picker clearable v-model="form.createdTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备用1" prop="ext1">
          <el-input v-model="form.ext1" placeholder="请输入备用1" />
        </el-form-item>
        <el-form-item label="备用2" prop="ext2">
          <el-input v-model="form.ext2" placeholder="请输入备用2" />
        </el-form-item>
        <el-form-item label="备用3" prop="ext3">
          <el-input v-model="form.ext3" placeholder="请输入备用3" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listHyjyxx, getHyjyxx, delHyjyxx, addHyjyxx, updateHyjyxx, getHyjyxxAll, startConvert } from "@/api/hyjyxx/hyjyxx"
import { getToken } from "@/utils/auth"

export default {
  name: "Hyjyxx",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 会议信息表格数据
      hyjyxxList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 模版下拉选项
      hymbOptions: [],
      // 音频上传配置
      upload: {
        headers: { Authorization: "Bearer " + getToken() },
        url: process.env.VUE_APP_BASE_API + "/common/upload"
      },
      // el-upload 文件列表（用于编辑时回显）
      audioFileList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        xmid: null,
        hymc: null,
        jxzt: null,
        ypwj: null,
        yw: null,
        hyjy: null,
        jxwcsj: null,
        createdBy: null,
        createdTime: null,
        ext1: null,
        ext2: null,
        ext3: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        hymc: [
          { required: true, message: "会议名称不能为空", trigger: "blur" }
        ],
        ypwj: [
          { required: true, message: "会议音频文件不能为空", trigger: "change" }
        ],
        mbmc: [
          { required: true, message: "会议模版不能为空", trigger: "change" }
        ],
        jxwcsj: [
          { required: true, message: "音频开始时间不能为空", trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.getList()
    // 获取会议模版下拉
    getHyjyxxAll().then(res => {
      // 兼容不同返回结构，优先 data
      this.hymbOptions = res.data || res.rows || []
    })
  },
  methods: {
    /** 查询会议信息列表 */
    getList() {
      this.loading = true
      const qp = { ...this.queryParams }
      // 转换为字符串再请求，避免后端无法解析 Date
      if (qp.jxwcsj instanceof Date) {
        qp.jxwcsj = this.parseTime(qp.jxwcsj, '{y}-{m}-{d} {h}:{i}:{s}')
      }
      listHyjyxx(qp).then(response => {
        this.hyjyxxList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        xmid: null,
        hymc: null,
        jxzt: null,
        ypwj: null,
        ypwjName: null,
        yw: null,
        hyjy: null,
        jxwcsj: null,
        createdBy: null,
        createdTime: null,
        updateBy: null,
        updateTime: null,
        mbid: null,
        mbmc: null,
        ext1: null,
        ext2: null,
        ext3: null
      }
      this.resetForm("form")
      this.audioFileList = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加会议信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getHyjyxx(id).then(response => {
        this.form = response.data
        // 兼容后端仅返回 mbid 的情况
        if (this.form && this.form.mbid && !this.form.mbmc) {
          const found = (this.hymbOptions || []).find(o => (o.id || o.value) === this.form.mbid)
          this.form.mbmc = found ? (found.mbmc || found.label) : this.form.mbmc
        }
        // 回显已上传的音频文件
        this.audioFileList = []
        if (this.form && this.form.ypwj) {
          this.audioFileList = [{
            name: this.form.ypwjName || this.getFileName(this.form.ypwj),
            url: this.getAudioUrl(this.form.ypwj)
          }]
        }
        this.open = true
        this.title = "修改会议信息"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const payload = { ...this.form }
          if (payload.jxwcsj instanceof Date) {
            payload.jxwcsj = this.parseTime(payload.jxwcsj, '{y}-{m}-{d} {h}:{i}:{s}')
          }
          if (this.form.id != null) {
            updateHyjyxx(payload).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addHyjyxx(payload).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    handleHymbChange(value) {
      const found = (this.hymbOptions || []).find(o => (o.id || o.value) === value)
      this.form.mbmc = found ? (found.mbmc || found.label) : null
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除会议信息编号为"' + ids + '"的数据项？').then(function () {
        return delHyjyxx(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    handleKszr(row) {
      if (!row || !row.id) {
        this.$modal.msgError("未找到ID，无法开始转录")
        return
      }
      const id = row.id
      this.$modal.confirm('确认对编号为"' + id + '"的数据开始转录？').then(() => {
        return startConvert(id)
      }).then(() => {
        this.$modal.msgSuccess("已开始转录")
        this.getList()
      }).catch(() => { })
    },
    // 跳转到详情页
    goDetail(row) {
      if (!row || !row.id) return
      this.$router.push({ path: `/hyjyxx/hyjyxx/detail/${row.id}` })
    },
    // 音频上传成功
    handleAudioSuccess(response) {
      if (response && response.code === 200) {
        // 后端返回的文件名或url字段可能为 fileName/url
        this.form.ypwj = response.fileName || response.url || ""
        // 取文件名用于显示/保存到 ypwjName
        this.form.ypwjName = response.originalFilename || ""
        // 同步到文件列表用于回显
        const displayName = this.form.ypwjName || this.getFileName(this.form.ypwj)
        this.audioFileList = this.form.ypwj ? [{ name: displayName, url: this.getAudioUrl(this.form.ypwj) }] : []
        this.$modal.msgSuccess("上传成功")
      } else {
        this.$modal.msgError((response && response.msg) || "上传失败")
      }
    },
    // 音频上传失败
    handleAudioError() {
      this.$modal.msgError("上传失败，请重试")
    },
    // 获取音频绝对地址
    getAudioUrl(path) {
      if (!path) return ""
      if (/^https?:\/\//i.test(path)) return path
      const base = process.env.VUE_APP_BASE_API || ""
      return `${base}${path}`
    },
    getFileName(fullPath) {
      if (!fullPath) return ""
      const idx = fullPath.lastIndexOf('/')
      return idx >= 0 ? fullPath.slice(idx + 1) : fullPath
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('hyjyxx/hyjyxx/export', {
        ...this.queryParams
      }, `hyjyxx_${new Date().getTime()}.xlsx`)
    },
    /** 截图管理按钮操作 */
    handleHyjyxxFile(row) {
      if (!row || !row.id) {
        this.$modal.msgError("未找到会议ID")
        return
      }
      this.$router.push({ path: `/hyjyxxFile/file/index`, query: { hyid: row.id } })
    }
  }
}
</script>
