<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="循环类型" prop="cycleType">
        <el-select v-model="queryParams.cycleType" placeholder="请选择循环类型" clearable>
          <el-option
            v-for="dict in broadcast_task_cycle_type"
            :key="dict.value"
            :label="dict.label"
            :value="String(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:broadcastTask:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['base:broadcastTask:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="CopyDocument"
          :disabled="single"
          @click="handleCopy"
          v-hasPermi="['base:broadcastTask:add']"
        >复制</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['base:broadcastTask:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['base:broadcastTask:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="broadcastTaskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务名称" align="center" prop="taskName" min-width="160" show-overflow-tooltip />
      <el-table-column label="关联内容" align="center" prop="contentId" min-width="160" show-overflow-tooltip>
        <template #default="scope">
          <span>{{ formatContentName(scope.row.contentId, scope.row.contentName) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="120" />
      <el-table-column label="结束时间" align="center" prop="endTime" width="120" />
      <el-table-column label="播报频率" align="center" prop="frequencyMinutes" width="120">
        <template #default="scope">
          <span>{{ scope.row.frequencyMinutes ? scope.row.frequencyMinutes + ' 分钟' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="循环类型" align="center" prop="cycleType" width="120">
        <template #default="scope">
          <dict-tag :options="broadcast_task_cycle_type" :value="String(scope.row.cycleType)" />
        </template>
      </el-table-column>
      <el-table-column label="循环取值" align="center" prop="cycleValue" min-width="160" show-overflow-tooltip>
        <template #default="scope">
          <span>{{ formatCycleValue(scope.row.cycleType, scope.row.cycleValue) }}</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" width="300" fixed="right" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            v-if="String(scope.row.status) !== '1'"
            link
            type="primary"
            icon="CircleCheck"
            @click="handleStatusChange(scope.row, '1')"
            v-hasPermi="['base:broadcastTask:edit']"
          >启用</el-button>
          <el-button
            v-if="String(scope.row.status) === '1'"
            link
            type="warning"
            icon="CircleClose"
            @click="handleStatusChange(scope.row, '0')"
            v-hasPermi="['base:broadcastTask:edit']"
          >停用</el-button>
          <el-button link type="primary" icon="CopyDocument" @click="handleCopy(scope.row)" v-hasPermi="['base:broadcastTask:add']">复制</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['base:broadcastTask:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['base:broadcastTask: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="720px" append-to-body>
      <el-form ref="broadcastTaskRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="form.taskName" maxlength="100" show-word-limit placeholder="请输入任务名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="关联播报内容" prop="contentId">
              <el-select
                v-model="form.contentId"
                placeholder="请选择播报内容"
                filterable
                clearable
                empty-text="暂无启用的播报内容，请先维护播报内容"
                style="width: 100%"
              >
                <el-option
                  v-for="item in broadcastContentOptions"
                  :key="item.id"
                  :label="formatContentOptionLabel(item)"
                  :value="item.id"
                  :disabled="String(item.status) !== '1'"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-time-picker
                v-model="form.startTime"
                value-format="HH:mm:ss"
                format="HH:mm:ss"
                placeholder="请选择开始时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-time-picker
                v-model="form.endTime"
                value-format="HH:mm:ss"
                format="HH:mm:ss"
                placeholder="请选择结束时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="播报频率" prop="frequencyMinutes">
              <div class="frequency-input-wrap">
                <el-input-number
                  class="frequency-number"
                  v-model="form.frequencyMinutes"
                  :min="1"
                  :max="1440"
                  :step="1"
                  controls-position="right"
                  placeholder="请输入播报频率"
                />
                <span class="frequency-unit">分钟</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="循环类型" prop="cycleType">
              <el-select v-model="form.cycleType" placeholder="请选择循环类型" style="width: 100%">
                <el-option
                  v-for="dict in broadcast_task_cycle_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="String(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="String(form.cycleType) === '1'" label="播报星期" prop="cycleValue">
              <el-checkbox-group v-model="cycleWeekValues" @change="handleCycleValueChange">
                <el-checkbox
                  v-for="item in weekOptions"
                  :key="item.value"
                  :label="item.value"
                >{{ item.label }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item v-if="String(form.cycleType) === '2'" label="指定日期" prop="cycleValue">
              <el-date-picker
                v-model="cycleDateValues"
                type="dates"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                placeholder="请选择指定日期"
                style="width: 100%"
                @change="handleCycleValueChange"
              />
            </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="BroadcastTask">
import { listBroadcastTask, getBroadcastTask, delBroadcastTask, addBroadcastTask, updateBroadcastTask } from "@/api/base/broadcastTask"
import { listBroadcastContent } from "@/api/base/broadcastContent"

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

const broadcastTaskList = ref([])
const broadcastContentOptions = 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 suppressCycleWatch = ref(false)

/** 星期选项 */
const weekOptions = [
  { label: "星期一", value: "1" },
  { label: "星期二", value: "2" },
  { label: "星期三", value: "3" },
  { label: "星期四", value: "4" },
  { label: "星期五", value: "5" },
  { label: "星期六", value: "6" },
  { label: "星期日", value: "7" }
]

/** 星期选择值 */
const cycleWeekValues = ref([])
/** 日期选择值 */
const cycleDateValues = ref([])

/** 启用的播报内容下拉选项 */
const enabledBroadcastContentOptions = computed(() => {
  return broadcastContentOptions.value.filter(item => String(item.status) === "1")
})

/** 格式化播报内容下拉选项标签 */
function formatContentOptionLabel(item) {
  if (!item) return "-"
  return String(item.status) === "1" ? item.contentName : item.contentName + "（已停用）"
}

/** 格式化循环取值展示 */
function formatCycleValue(cycleType, cycleValue) {
  if (!cycleValue) return "-"
  // 1 = 按星期
  if (String(cycleType) === "1") {
    const values = String(cycleValue).split(",")
    return weekOptions
      .filter(item => values.includes(item.value))
      .map(item => item.label)
      .join("、") || "-"
  }
  // 2 = 按日期
  if (String(cycleType) === "2") {
    return String(cycleValue).split(",").join("、")
  }
  return cycleValue
}

/** 回显循环取值到控件 */
function setCycleValueForEdit(cycleType, cycleValue) {
  cycleWeekValues.value = []
  cycleDateValues.value = []
  if (!cycleValue) return
  // 1 = 按星期
  if (String(cycleType) === "1") {
    cycleWeekValues.value = String(cycleValue).split(",").filter(Boolean)
  }
  // 2 = 按日期
  if (String(cycleType) === "2") {
    cycleDateValues.value = String(cycleValue).split(",").filter(Boolean)
  }
}

/** 回填表单数据，避免 cycleType 回显时被 watch 清空 cycleValue */
function fillFormData(data, options = {}) {
  const isCopy = options.isCopy === true
  suppressCycleWatch.value = true
  form.value = {
    ...data,
    id: isCopy ? null : data.id,
    taskName: isCopy ? (data.taskName ? data.taskName + " - 副本" : "播报任务副本") : data.taskName,
    cycleType: data.cycleType != null ? String(data.cycleType) : "1",
    status: data.status != null ? String(data.status) : "1"
  }
  setCycleValueForEdit(form.value.cycleType, form.value.cycleValue)
  nextTick(() => {
    suppressCycleWatch.value = false
  })
}

/** 提交前组装循环取值 */
function buildCycleValueBeforeSubmit() {
  // 1 = 按星期
  if (String(form.value.cycleType) === "1") {
    form.value.cycleValue = cycleWeekValues.value.join(",")
    return
  }
  // 2 = 按日期
  if (String(form.value.cycleType) === "2") {
    form.value.cycleValue = cycleDateValues.value.join(",")
    return
  }
  form.value.cycleValue = null
}

/** 循环取值校验 */
function validateCycleValue(rule, value, callback) {
  if (String(form.value.cycleType) === "1" && cycleWeekValues.value.length === 0) {
    callback(new Error("请至少选择一个播报星期"))
    return
  }
  if (String(form.value.cycleType) === "2" && cycleDateValues.value.length === 0) {
    callback(new Error("请至少选择一个指定日期"))
    return
  }
  callback()
}

/** 时间范围校验 */
function validateTimeRange(rule, value, callback) {
  if (form.value.startTime && form.value.endTime && form.value.endTime <= form.value.startTime) {
    callback(new Error("结束时间必须大于开始时间"))
  } else {
    callback()
  }
}

/** 循环取值变化时触发表单校验 */
function handleCycleValueChange() {
  nextTick(() => {
    proxy.$refs["broadcastTaskRef"]?.validateField("cycleValue")
  })
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    taskName: undefined,
    cycleType: undefined,
    status: undefined,
  },
  rules: {
    taskName: [
      { required: true, message: "任务名称不能为空", trigger: "blur" }
    ],
    contentId: [
      { required: true, message: "请选择播报内容", trigger: "change" }
    ],
    startTime: [
      { required: true, message: "请选择开始时间", trigger: "change" }
    ],
    endTime: [
      { required: true, message: "请选择结束时间", trigger: "change" },
      { validator: validateTimeRange, trigger: "change" }
    ],
    frequencyMinutes: [
      { required: true, message: "请输入播报频率", trigger: "blur" }
    ],
    cycleType: [
      { required: true, message: "请选择循环类型", trigger: "change" }
    ],
    cycleValue: [
      { validator: validateCycleValue, trigger: "change" }
    ],
    status: [
      { required: true, message: "请选择启用状态", trigger: "change" }
    ],
  }
})

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

/** 监听循环类型变化，清空旧值 */
watch(() => form.value.cycleType, (newVal, oldVal) => {
  if (suppressCycleWatch.value) return
  if (String(newVal) !== String(oldVal)) {
    form.value.cycleValue = null
    cycleWeekValues.value = []
    cycleDateValues.value = []
  }
})

/** 查询播报任务列表 */
function getList() {
  loading.value = true
  listBroadcastTask(queryParams.value).then(response => {
    broadcastTaskList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

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

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    taskName: null,
    contentId: null,
    startTime: null,
    endTime: null,
    frequencyMinutes: 30,
    cycleType: "1",
    cycleValue: null,
    status: "1",
    remark: null,
    createTime: null,
    updateTime: null
  }
  cycleWeekValues.value = []
  cycleDateValues.value = []
  proxy.resetForm("broadcastTaskRef")
}

/** 搜索按钮操作 */
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()
  getBroadcastContentOptions()
  open.value = true
  title.value = "添加播报任务"
}

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

/** 复制按钮操作 */
function handleCopy(row) {
  reset()
  getBroadcastContentOptions()
  const _id = row.id || ids.value[0]
  if (!_id) {
    proxy.$modal.msgWarning("请选择一条需要复制的播报任务")
    return
  }
  getBroadcastTask(_id).then(response => {
    const data = response.data || {}
    fillFormData(data, { isCopy: true })
    open.value = true
    title.value = "复制播报任务"
  })
}

/** 启用/停用播报任务 */
function handleStatusChange(row, status) {
  const actionText = status === "1" ? "启用" : "停用"
  const extraTip = status === "1" ? "请确认关联播报内容处于启用状态，否则任务可能无法正常播报。" : ""
  proxy.$modal.confirm('确认' + actionText + '播报任务"' + row.taskName + '"吗？' + extraTip).then(() => {
    return updateBroadcastTask({
      ...row,
      status
    })
  }).then(() => {
    proxy.$modal.msgSuccess(actionText + "成功")
    getList()
  }).catch(() => {})
}

/** 获取播报内容下拉选项 */
function getBroadcastContentOptions() {
  listBroadcastContent({
    pageNum: 1,
    pageSize: 999
  }).then(response => {
    broadcastContentOptions.value = response.rows || []
  }).catch(() => {
    broadcastContentOptions.value = []
  })
}

/** 格式化内容名称 */
function formatContentName(contentId, contentName) {
  if (contentName) return contentName
  if (!contentId) return "-"
  const target = broadcastContentOptions.value.find(item => String(item.id) === String(contentId))
  if (target && target.contentName) {
    return String(target.status) === "0" ? target.contentName + "（已停用）" : target.contentName
  }
  return "内容ID：" + contentId
}

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

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('确认删除选中的播报任务吗？删除后不可恢复。').then(function() {
    return delBroadcastTask(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

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

getBroadcastContentOptions()
getList()
</script>

<style scoped>
.app-container {
  padding: 20px;
}
:deep(.el-table .cell) {
  line-height: 22px;
}
.frequency-input-wrap {
  display: flex;
  align-items: center;
  width: 100%;
}
.frequency-number {
  flex: 1;
}
.frequency-unit {
  flex: 0 0 auto;
  margin-left: 8px;
  color: #606266;
}
</style>
