<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <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="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable>
          <el-option label="启用" value="0" />
          <el-option label="停用" value="1" />
        </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="['video:inspection:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['video:inspection:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['video:inspection:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['video:inspection:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inspectionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务ID" align="center" prop="taskId" />
      <el-table-column label="任务名称" align="center" prop="taskName" />
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="Cron表达式" align="center" prop="cronExpression" />
      <el-table-column label="巡检时长(秒)" align="center" prop="duration" />
      <el-table-column label="任务状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="启用检测" align="center" prop="enableDetection">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.enableDetection"/>
        </template>
      </el-table-column>
      <el-table-column label="检测阈值" align="center" prop="threshold" />
      <el-table-column label="执行次数" align="center" prop="executeCount" />
      <el-table-column label="报警次数" align="center" prop="alarmCount" />
      <el-table-column label="最后执行时间" align="center" prop="lastExecuteTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastExecuteTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['video:inspection:edit']">修改</el-button>
          <el-button link type="primary" icon="VideoPlay" @click="handleStart(scope.row)" v-hasPermi="['video:inspection:start']" v-if="scope.row.status === '1'">启动</el-button>
          <el-button link type="warning" icon="VideoPause" @click="handleStop(scope.row)" v-hasPermi="['video:inspection:stop']" v-if="scope.row.status === '0'">停止</el-button>
          <el-button link type="success" icon="CaretRight" @click="handleExecute(scope.row)" v-hasPermi="['video:inspection:execute']">执行</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['video:inspection: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="500px" append-to-body>
      <el-form ref="inspectionRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="设备" prop="deviceId">
          <el-select v-model="form.deviceId" placeholder="请选择设备" style="width: 100%">
            <el-option
              v-for="device in deviceList"
              :key="device.deviceId"
              :label="device.ip"
              :value="device.deviceId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Cron表达式" prop="cronExpression">
          <el-input v-model="form.cronExpression" placeholder="请输入Cron表达式" />
          <div class="el-form-item__tip">
            例如：0 0 8 * * ? 表示每天8点执行<br/>
            0 0/30 * * * ? 表示每30分钟执行一次
          </div>
        </el-form-item>
        <el-form-item label="巡检时长" prop="duration">
          <el-input-number v-model="form.duration" :min="10" :max="3600" placeholder="巡检时长(秒)" />
        </el-form-item>
        <el-form-item label="任务状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="启用检测" prop="enableDetection">
          <el-radio-group v-model="form.enableDetection">
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="检测阈值" prop="threshold">
          <el-input-number v-model="form.threshold" :min="0.1" :max="1.0" :step="0.1" placeholder="检测阈值" />
        </el-form-item>
      </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="Inspection">
import { listInspection, getInspection, delInspection, addInspection, updateInspection, startTask, stopTask, executeTask } from "@/api/video/inspection";
import { listDevice } from "@/api/video/device";

const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict('sys_normal_disable');

const inspectionList = ref([]);
const deviceList = 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: 20,
    taskName: null,
    deviceName: null,
    status: null
  },
  rules: {
    taskName: [
      { required: true, message: "任务名称不能为空", trigger: "blur" }
    ],
    deviceId: [
      { required: true, message: "设备不能为空", trigger: "change" }
    ],
    cronExpression: [
      { required: true, message: "Cron表达式不能为空", trigger: "blur" }
    ],
    duration: [
      { required: true, message: "巡检时长不能为空", trigger: "blur" }
    ],
    threshold: [
      { required: true, message: "检测阈值不能为空", trigger: "blur" }
    ]
  }
});

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

/** 查询巡检任务列表 */
function getList() {
  loading.value = true;
  listInspection(queryParams.value).then(response => {
    inspectionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询设备列表 */
function getDeviceList() {
  listDevice({}).then(response => {
    deviceList.value = response.rows;
  });
}

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

// 表单重置
function reset() {
  form.value = {
    taskId: null,
    taskName: null,
    deviceId: null,
    cronExpression: null,
    duration: 300,
    status: "0",
    enableDetection: "0",
    threshold: 0.7
  };
  proxy.resetForm("inspectionRef");
}

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

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

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

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加巡检任务";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const taskId = row.taskId || ids.value;
  getInspection(taskId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改巡检任务";
  });
}

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

/** 删除按钮操作 */
function handleDelete(row) {
  const taskIds = row.taskId || ids.value;
  proxy.$modal.confirm('是否确认删除巡检任务编号为"' + taskIds + '"的数据项？').then(function() {
    return delInspection(taskIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 启动任务 */
function handleStart(row) {
  proxy.$modal.confirm('是否确认启动任务"' + row.taskName + '"？').then(function() {
    return startTask(row.taskId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("启动成功");
  }).catch(() => {});
}

/** 停止任务 */
function handleStop(row) {
  proxy.$modal.confirm('是否确认停止任务"' + row.taskName + '"？').then(function() {
    return stopTask(row.taskId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("停止成功");
  }).catch(() => {});
}

/** 执行任务 */
function handleExecute(row) {
  proxy.$modal.confirm('是否确认立即执行任务"' + row.taskName + '"？').then(function() {
    return executeTask(row.taskId);
  }).then(() => {
    proxy.$modal.msgSuccess("任务已提交执行");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('video/inspection/export', {
    ...queryParams.value
  }, `inspection_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
  getDeviceList();
});
</script>