<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading">
      <scheduledTasksSearch ref="searchRef" @search="reload"> </scheduledTasksSearch>
      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :pageSizes="tablePageSizes"
        :columns="columns"
        :datasource="datasource"
        :selection.sync="selection"
        :cache-key="cacheKeyUrl"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
            <el-button
                size="small"
                type="primary"
                icon="el-icon-plus"
                class="ele-btn-icon"
                v-if="$hasPermission('infra:job:create')"
                @click="openForm('create')"
            >
                新建
            </el-button>
            <el-button
                size="small"
                type="primary"
                icon="el-icon-plus"
                class="ele-btn-icon"
                v-if="$hasPermission('infra:job:delete')"
                @click="handleBatchDelete"
            >
                批量删除
            </el-button>
            <el-button
                size="small"
                type="primary"
                icon="el-icon-download"
                class="ele-btn-icon"
                v-if="$hasPermission('infra:job:export')"
                @click="handleExport"
            >
                导出
            </el-button>
        </template>
        <!-- 操作列 -->
        <template v-slot:action="{ row }">
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-edit"
            @click="openForm('update', row.id)"
            v-if="$hasPermission('infra:job:update')"
          >
            编辑
          </el-link>
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-video-play"
            @click="handleChangeStatus(row)"
            v-if="$hasPermission('infra:job:update')"
          >
            {{ row.status === 1 ? '暂停' : '开启' }}
          </el-link>
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-delete"
            :style="{ color: delColor }"
            @click="handleDelete(row.id)"
            v-if="$hasPermission('infra:job:delete')"
          >
            删除
          </el-link>
          <el-dropdown
            @command="(command) => handleCommand(command, row)"
            v-if="$hasPermission('infra:job:trigger') || $hasPermission('infra:job:query')"
          >
            <el-link type="primary" :underline="false">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </el-link>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  command="handleRun"
                  v-if="$hasPermission('infra:job:trigger')"
                >
                  执行一次
                </el-dropdown-item>
                <el-dropdown-item
                  command="openDetail"
                  v-if="$hasPermission('infra:job:query')"
                >
                  任务详细
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </ele-pro-table>
    </el-card>

    <!-- 表单弹窗：添加/修改 -->
    <JobForm ref="formRef" @success="reload" />
    <!-- 表单弹窗：查看 -->
    <JobDetail ref="detailRef" />
  </div>
</template>

<script>
import ScheduledTasksSearch from './components/scheduledTasks-search.vue'
import JobForm from './components/JobForm.vue'
import JobDetail from './components/JobDetail.vue'
import { getToken, setToken } from '@/utils/token-util';
import { download } from '@/utils/file';
import * as JobApi from '@/api/config/scheduledTasks'
import dictMixins from '@/mixins/dictMixins';
import axios from 'axios';
import {
    API_BASE_URL,
  } from '@/config/setting';

export default {
  name: 'InfraJob',
  mixins: [dictMixins],
  components: {
    ScheduledTasksSearch,
    JobForm,
    JobDetail
  },
  data() {
    return {
      cacheKeyUrl: 'infraJobTable',
      delColor: '#F56C6C',
      selection: [],
      // 表格列配置
      columns: [
        {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center',
            fixed: 'left'
        },
        {
          columnKey: 'index',
          label: '序号',
          type: 'index',
          width: 55,
          align: 'center',
          showOverflowTooltip: true,
          fixed: 'left'
        },
        {
          prop: 'name',
          label: '任务名称',
          headerAlign: 'center',
          align: 'center',
          showOverflowTooltip: true,
        //   minWidth: 150
        },
        {
          prop: 'status',
          label: '任务状态',
          align: 'center',
          showOverflowTooltip: true,
          width: 90,
          formatter: (row) => {
            return this.getDictValue('定时任务状态', row.status)
          }
        },
        {
          prop: 'handlerName',
          label: '任务类名',
          headerAlign: 'center',
          align: 'center',
          showOverflowTooltip: true,
        //   minWidth: 150
        },
        {
          prop: 'cronExpression',
          label: 'CRON 表达式',
          align: 'center',
          showOverflowTooltip: true,
        //   width: 150
        },
        {
          prop: 'createTime',
          label: '创建时间',
          align: 'center',
          showOverflowTooltip: true,
        //   width: 160
        },
        {
          columnKey: 'action',
          fixed: 'right',
          label: '操作',
          width: 230,
          align: 'center',
          resizable: false,
          slot: 'action',
          showOverflowTooltip: true
        }
      ],
      // 加载状态
      loading: false,
      tablePageSizes: [10, 20, 50, 100]
    }
  },
  created() {
    this.requestDict('定时任务状态');
  },
  methods: {
    /* 表格数据源 */
    datasource({ page, limit, where, order }) {
      return JobApi.getJobPage({
        pageNo: page,
        pageSize: limit,
        ...where
      })
    },
    /* 刷新表格 */
    reload(where) {
      this.$refs.table.reload({ page: 1, where })
    },

    /* 搜索 */
    handleQuery(where) {
      this.reload(where)
    },

    /** 添加/修改操作 */
    openForm(type, id) {
      this.$refs.formRef.open(type, id)
    },

    /** 修改状态操作 */
    handleChangeStatus(row) {
      const text = row.status == 1 ? '暂停' : '开启'
      this.$confirm(
        '确认要' + text + '定时任务名称为"' + row.name + '"的数据项?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async () => {
          const status = row.status === 1 ? 2 : 1
          await JobApi.updateJobStatus(row.id, status)
          this.$message.success(text + '成功')
          this.reload()
        })
        .catch(() => {})
    },

    /** 删除按钮操作 */
    handleDelete(id) {
      this.$confirm('是否确认删除数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await JobApi.deleteJob(id)
          this.$message.success('删除成功')
          this.reload()
        })
        .catch(() => {})
    },

    /** 批量删除按钮操作 */
    handleBatchDelete() {
        console.log(this.selection) 
        if(this.selection.length == 0) {
            this.$message.warning('请选择要删除的数据项')
            return
        }
      this.$confirm('是否确认删除选中的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
            const ids = this.selection.map(item => item.id)
          await JobApi.batchDeleteJob(ids)
          this.$message.success('删除成功')
          this.reload()
        })
        .catch(() => {})
    },

    /** '更多'操作按钮 */
    handleCommand(command, row) {
      switch (command) {
        case 'handleRun':
          this.handleRun(row)
          break
        case 'openDetail':
          this.openDetail(row.id)
          break
        default:
          break
      }
    },

    /** 执行一次 */
    handleRun(row) {
      this.$confirm('确认要开始执行一次' + row.name + '?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await JobApi.runJob(row.id)
          this.$message.success('执行成功')
          this.reload()
        })
        .catch(() => {})
    },

    /** 导出按钮操作 */
    async handleExport() {
      // try {
      //   const data = await JobApi.exportJob(this.$refs.table?.where || {})
      //   console.log('handleExport~~~', data)
      //   download(data, '定时任务.xls')
      // } catch (error) {
      //   console.error('导出失败:', error)
      // }

      let params = {
          ...this.$refs.searchRef.where,
        };
        this.loading = true;
        axios({
          url: `${API_BASE_URL}/eam/job/export-excel`,
          method: 'get',
          responseType: 'blob',
          headers: {
            Authorization: getToken()
          },
          data: params
        })
          .then((res) => {
            this.loading = false;
            download(res.data, '定时任务.xls');
            this.$message.success('操作成功');
          })
          .catch((err) => {
            this.loading = false;
          });
    },

    /** 查看操作 */
    openDetail(id) {
      this.$refs.detailRef.open(id)
    }
  }
}
</script>

<style lang="scss" scoped></style>
