<template>
  <div class="voice-broadcast-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <i class="el-icon-microphone header-icon" />
        <span class="header-title">语音播报管理</span>
      </div>
      <el-button type="primary" icon="el-icon-plus" @click="openAddDialog">
        新增播报
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="hover">
      <el-table
        v-loading="loading"
        :data="tableData"
        :header-cell-style="{background:'#f5f7fa',color:'#606266',fontWeight:'bold'}"
        element-loading-text="数据加载中..."
        element-loading-spinner="el-icon-loading"
        style="width: 100%"
        border
        stripe
        highlight-current-row
      >
        <el-table-column align="center" label="启用状态" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.enableStatus"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="toggleEnable(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="播报内容" min-width="200" show-overflow-tooltip>
          <template slot-scope="scope">
            <span class="content-text">{{ scope.row.播报内容 }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="播报周期" width="120">
          <template slot-scope="scope">
            <el-tag :type="scope.row.播报周期 === '每日' ? 'primary' : 'success'" effect="plain">
              {{ scope.row.播报周期 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="播报时间段" width="140">
          <template slot-scope="scope">
            <span class="time-range">
              <i class="el-icon-time" />
              {{ scope.row.开始时间 || '--' }} ~ {{ scope.row.结束时间 || '--' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="生效日期" width="220">
          <template slot-scope="scope">
            <span v-if="scope.row.播报周期 === '定期'" class="date-range">
              <i class="el-icon-date" />
              {{ scope.row.开始日期 || '--' }} 至 {{ scope.row.结束日期 || '--' }}
            </span>
            <span v-else class="date-range">每天生效</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作时间" width="160">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.操作时间) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="150" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              circle
              @click="openEditDialog(scope.row)"
            />
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              circle
              @click="deleteRecord(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      width="550px"
      center
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="播报内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="4"
            placeholder="请输入播报内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="播报周期" prop="cycle">
          <el-radio-group v-model="form.cycle" @change="onCycleChange">
            <el-radio-button label="每日">
              <i class="el-icon-refresh" /> 每日
            </el-radio-button>
            <el-radio-button label="定期">
              <i class="el-icon-date" /> 定期
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="播报时间" prop="timeRange">
          <el-time-picker
            v-model="form.startTime"
            placeholder="开始时间"
            format="HH:mm"
            value-format="HH:mm"
            style="width: 150px"
          />
          <span class="time-separator">至</span>
          <el-time-picker
            v-model="form.endTime"
            placeholder="结束时间"
            format="HH:mm"
            value-format="HH:mm"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item v-if="form.cycle === '定期'" label="生效日期" prop="dateRange">
          <el-date-picker
            v-model="form.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch
            v-model="form.enable"
            active-text="启用"
            inactive-text="禁用"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitForm">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'VoiceBroadcastSetting',
  data() {
    return {
      loading: false,
      tableData: [],
      dialogVisible: false,
      dialogTitle: '新增播报',
      submitLoading: false,
      editingId: null,
      form: {
        content: '',
        cycle: '每日',
        startTime: '',
        endTime: '',
        dateRange: [],
        enable: true
      },
      formRules: {
        content: [
          { required: true, message: '请输入播报内容', trigger: 'blur' }
        ],
        cycle: [
          { required: true, message: '请选择播报周期', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    // 加载数据
    loadData() {
      this.loading = true
      const param = []
      const Data = this.CreateData('11', 'TV_定时语音播报_查询', param)
      this.ExecDatabase(Data).then(response => {
        this.tableData = response.data.map(item => ({
          ...item,
          enableStatus: item.是否启用 === 1
        }))
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '--'
      const date = new Date(dateTime)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },

    // 打开新增弹窗
    openAddDialog() {
      this.dialogTitle = '新增播报'
      this.editingId = null
      this.form = {
        content: '',
        cycle: '每日',
        startTime: '',
        endTime: '',
        dateRange: [],
        enable: true
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.formRef && this.$refs.formRef.clearValidate()
      })
    },

    // 打开编辑弹窗
    openEditDialog(row) {
      this.dialogTitle = '编辑播报'
      this.editingId = row.ID
      this.form = {
        content: row.播报内容 || '',
        cycle: row.播报周期 || '每日',
        startTime: row.开始时间 || '',
        endTime: row.结束时间 || '',
        dateRange: row.开始日期 && row.结束日期 ? [row.开始日期, row.结束日期] : [],
        enable: row.是否启用 === 1
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.formRef && this.$refs.formRef.clearValidate()
      })
    },

    // 周期变化时清空日期范围
    onCycleChange(val) {
      if (val === '每日') {
        this.form.dateRange = []
      }
    },

    // 提交表单
    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return

        if (!this.form.content.trim()) {
          this.$message.error('请输入播报内容')
          return
        }

        this.submitLoading = true
        const param = []
        let procedureName = ''

        if (this.editingId) {
          // 编辑
          procedureName = 'TV_定时语音播报_编辑'
          param.push(['ID', this.editingId])
        } else {
          // 新增
          procedureName = 'TV_定时语音播报_增加'
        }

        param.push(['播报内容', this.form.content])
        param.push(['播报周期', this.form.cycle])
        param.push(['开始时间', this.form.startTime || ''])
        param.push(['结束时间', this.form.endTime || ''])
        param.push(['开始日期', this.form.dateRange && this.form.dateRange[0] ? this.form.dateRange[0] : ''])
        param.push(['结束日期', this.form.dateRange && this.form.dateRange[1] ? this.form.dateRange[1] : ''])
        param.push(['是否启用', this.form.enable ? 1 : 0])

        const Data = this.CreateData('12', procedureName, param)
        this.ExecDatabase(Data).then(response => {
          this.submitLoading = false
          if (response.data[0].result === '1') {
            this.$message.success(this.editingId ? '编辑成功' : '新增成功')
            this.dialogVisible = false
            this.loadData()
          } else {
            this.$message.error(response.data[0].msg || '操作失败')
          }
        }).catch(() => {
          this.submitLoading = false
          this.$message.error('网络错误，请重试')
        })
      })
    },

    // 切换启用状态
    toggleEnable(row) {
      const param = [['ID', row.ID]]
      const Data = this.CreateData('12', 'TV_定时语音播报_切换启用', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data[0].result === '1') {
          this.$message.success('状态切换成功')
        } else {
          this.$message.error('操作失败')
          row.enableStatus = !row.enableStatus
        }
      }).catch(() => {
        this.$message.error('网络错误')
        row.enableStatus = !row.enableStatus
      })
    },

    // 删除记录
    deleteRecord(row) {
      this.$confirm('确定要删除这条播报记录吗？', '删除确认', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }).then(() => {
        const param = [['ID', row.ID]]
        const Data = this.CreateData('12', 'TV_定时语音播报_删除', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result === '1') {
            this.$message.success('删除成功')
            this.loadData()
          } else {
            this.$message.error('删除失败')
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.voice-broadcast-container {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%);
  min-height: calc(100vh - 84px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px 25px;
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(64, 158, 255, 0.3);
}

.header-left {
  display: flex;
  align-items: center;
}

.header-icon {
  font-size: 28px;
  color: #fff;
  margin-right: 12px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
}

.header-title {
  font-size: 22px;
  font-weight: bold;
  color: #fff;
  letter-spacing: 2px;
}

.page-header .el-button {
  background: rgba(255, 255, 255, 0.95);
  border: none;
  color: #409eff;
  font-weight: bold;
  padding: 12px 24px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.page-header .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.table-card {
  border-radius: 12px;
  overflow: hidden;
}

.table-card >>> .el-card__body {
  padding: 0;
}

.table-card >>> .el-table {
  border-radius: 12px;
}

.table-card >>> .el-table th {
  padding: 15px 0;
}

.table-card >>> .el-table td {
  padding: 12px 0;
}

.table-card >>> .el-table--striped .el-table__body tr.el-table__row--striped td {
  background: #fafbfc;
}

.table-card >>> .el-table__body tr:hover > td {
  background-color: #ecf5ff !important;
}

.content-text {
  color: #303133;
  font-size: 14px;
}

.time-range {
  color: #606266;
  font-size: 13px;
}

.time-range i {
  margin-right: 4px;
  color: #409eff;
}

.date-range {
  color: #606266;
  font-size: 13px;
}

.date-range i {
  margin-right: 4px;
  color: #67c23a;
}

.time-separator {
  margin: 0 10px;
  color: #909399;
}

/* 弹窗样式优化 */
.voice-broadcast-container >>> .el-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.voice-broadcast-container >>> .el-dialog__header {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  padding: 20px;
}

.voice-broadcast-container >>> .el-dialog__title {
  color: #fff;
  font-weight: bold;
  font-size: 18px;
}

.voice-broadcast-container >>> .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}

.voice-broadcast-container >>> .el-dialog__body {
  padding: 30px;
}

.voice-broadcast-container >>> .el-form-item__label {
  font-weight: 500;
}

.voice-broadcast-container >>> .el-radio-button__inner {
  padding: 10px 20px;
}

.dialog-footer {
  text-align: center;
}

.dialog-footer .el-button {
  padding: 12px 30px;
  border-radius: 8px;
}

/* 开关样式 */
.voice-broadcast-container >>> .el-switch__label {
  font-size: 13px;
}
</style>
