<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="内容名称" prop="contentName">
        <el-input
          v-model="queryParams.contentName"
          placeholder="请输入内容名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="内容分类" prop="contentType">
        <el-select v-model="queryParams.contentType" placeholder="请选择内容分类" clearable>
          <el-option
            v-for="dict in broadcast_content_content_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="启用状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择启用状态" clearable>
          <el-option label="启用" value="1" />
          <el-option label="停用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['base:broadcastContent:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['base:broadcastContent:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['base:broadcastContent:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['base:broadcastContent:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="VideoPlay"
          :disabled="single"
          @click="handleTestBroadcast"
          v-hasPermi="['base:broadcastContent:test']"
        >测试播报</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="broadcastContentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="内容名称" align="center" prop="contentName" min-width="160" show-overflow-tooltip />
      <el-table-column label="内容分类" align="center" prop="contentType" width="120">
        <template #default="scope">
          <dict-tag :options="broadcast_content_content_type" :value="scope.row.contentType"/>
        </template>
      </el-table-column>
      <el-table-column label="播报文本摘要" align="left" prop="broadcastText" min-width="260" show-overflow-tooltip>
        <template #default="scope">
          <span>{{ formatTextSummary(scope.row.broadcastText) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="启用状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag v-if="String(scope.row.status) === '1'" type="success">启用</el-tag>
          <el-tag v-else type="info">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="160" />
      <el-table-column label="操作" align="center" width="220" fixed="right" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="VideoPlay" @click="handleTestBroadcast(scope.row)" v-hasPermi="['base:broadcastContent:test']">测试</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['base:broadcastContent:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['base:broadcastContent:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改播报内容对话框 -->
    <el-dialog :title="title" v-model="open" width="680px" append-to-body>
      <el-form ref="broadcastContentRef" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="内容名称" prop="contentName">
              <el-input v-model="form.contentName" placeholder="请输入内容名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容分类" prop="contentType">
              <el-select v-model="form.contentType" placeholder="请选择内容分类">
                <el-option
                  v-for="dict in broadcast_content_content_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="播报文本" prop="broadcastText">
              <el-input
                v-model="form.broadcastText"
                type="textarea"
                :rows="5"
                maxlength="2000"
                show-word-limit
                placeholder="请输入播报文本"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="启用状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="1">启用</el-radio>
                <el-radio label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="3"
                maxlength="500"
                show-word-limit
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BroadcastContent">
import { listBroadcastContent, getBroadcastContent, delBroadcastContent, addBroadcastContent, updateBroadcastContent } from "@/api/base/broadcastContent"

const { proxy } = getCurrentInstance()
const { broadcast_content_content_type } = useDict('broadcast_content_content_type')

const broadcastContentList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contentName: undefined,
    contentType: undefined,
    status: undefined,
  },
  rules: {
    contentName: [
      { required: true, message: "内容名称不能为空", trigger: "blur" }
    ],
    contentType: [
      { required: true, message: "内容分类不能为空", trigger: "change" }
    ],
    broadcastText: [
      { required: true, message: "播报文本不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "请选择启用状态", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询播报内容列表 */
function getList() {
  loading.value = true
  listBroadcastContent(queryParams.value).then(response => {
    broadcastContentList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    contentName: null,
    contentType: null,
    broadcastText: null,
    status: "1",
    remark: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("broadcastContentRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加播报内容"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value[0]
  getBroadcastContent(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改播报内容"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["broadcastContentRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBroadcastContent(form.value).then(() => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addBroadcastContent(form.value).then(() => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除播报内容编号为"' + _ids + '"的数据项？').then(function() {
    return delBroadcastContent(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 文本摘要格式化 */
function formatTextSummary(text) {
  if (!text) return "-"
  return text.length > 40 ? text.slice(0, 40) + "..." : text
}

/** 测试播报 */
function handleTestBroadcast(row) {
  const target = row && row.id ? row : broadcastContentList.value.find(item => item.id === ids.value[0])
  if (!target) {
    proxy.$modal.msgWarning("请选择一条需要测试播报的内容")
    return
  }
  if (!target.broadcastText) {
    proxy.$modal.msgWarning("当前播报内容为空，无法测试")
    return
  }
  proxy.$modal.confirm('确认下发测试播报："' + target.contentName + '"？').then(() => {
    // TODO 后端接口完成后，在这里调用测试播报接口
    proxy.$modal.msgSuccess("测试播报指令已下发")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('base/broadcastContent/export', {
    ...queryParams.value
  }, `播报内容_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped>
.app-container {
  padding: 20px;
}
:deep(.el-table .cell) {
  line-height: 22px;
}
</style>
