<template>
  <div>
    <ElForm v-show="showSearchForm" inline @submit.prevent="paging">
      <ElFormItem label="调度时间">
        <ElDatePicker
          v-model="searchForm.scheduleTime"
          :shortcuts="shortcuts"
          end-placeholder="结束"
          range-separator="至"
          start-placeholder="开始"
          type="datetimerange"
          unlink-panels
        />
      </ElFormItem>
      <ElFormItem label="调度方式">
        <ElSelect v-model="searchForm.scheduleType" clearable placeholder="请选择调度方式" style="width: 150px" @clear="paging">
          <ElOption v-for="item in scheduleTypeList" :key="item.value" :label="item.label" :value="item.value"/>
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="任务状态">
        <ElSelect v-model="searchForm.taskStatus" placeholder="请选择任务状态" style="width: 150px;">
          <ElOption v-for="item in status" :key="item.value" :label="item.label" :value="item.value"/>
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="手动触发">
        <ElCheckbox
          v-model="searchForm.manually"
          placeholder="手动触发"/>
      </ElFormItem>
      <ElFormItem>
        <ElButton :icon="elIcons.Search" :loading="searching" native-type="submit" type="primary">搜索</ElButton>
        <ElButton :icon="elIcons.Refresh" :loading="searching" @click="reset">重置</ElButton>
      </ElFormItem>
    </ElForm>
    <!-- <div class="tool-bar">
      <ElButton :icon="elIcons.Filter" type="default" @click="showSearchForm = !showSearchForm"/>
    </div> -->
    <ElTable v-loading="searching" :data="tableData"
      cell-class-name="table-cell"
      class="table-list"
      empty-text="暂无数据"
      header-row-class-name="table-header"
      row-key="id">
      <ElTableColumn label="任务名称" prop="taskName"/>

      <ElTableColumn label="任务执行函数" prop="fn" show-overflow-tooltip width="150"/>

      <ElTableColumn label="调度方式" prop="scheduleType">

        <template #default="{row}">
          {{ scheduleType(row.scheduleType) }}
        </template>
      </ElTableColumn>

      <ElTableColumn label="调度配置" prop="scheduleConf"/>

      <ElTableColumn label="调度时间" prop="scheduleTime">
        <template #default="{row}">
          <ElTooltip :content="row.scheduleTime" effect="dark" placement="top">
            <span>{{ Times.pretty(row.scheduleTime) }}</span>
          </ElTooltip>
        </template>
      </ElTableColumn>

      <ElTableColumn label="执行时间" prop="startTime">
        <template #default="{row}">
          <ElTooltip :content="row.startTime + ' 至 ' + row.endTime" effect="dark" placement="top">
            <span>{{ Times.prettyDuration(row.startTime, row.endTime) }}</span>
          </ElTooltip>
        </template>
      </ElTableColumn>

      <ElTableColumn label="任务状态" prop="taskStatus">
        <template #default="{row}">
          <ElTag v-if="row.taskStatus === 'Waiting'" type="info">等待调度</ElTag>
          <ElTag v-if="row.taskStatus === 'Pending'" type="warning">排队中</ElTag>
          <ElTag v-if="row.taskStatus === 'Running'" type="primary">运行中</ElTag>
          <ElTag v-if="row.taskStatus === 'Completed'" type="success">已完成</ElTag>
          <ElTag v-if="row.taskStatus === 'Error'" type="danger">错误</ElTag>
        </template>
      </ElTableColumn>

      <ElTableColumn label="内置任务" prop="builtin">
        <template #default="{row}">
          {{ row.builtin ? '是' : '否' }}
        </template>
      </ElTableColumn>

      <ElTableColumn label="手动触发" prop="manually">
        <template #default="{row}">
          {{ row.manually ? '是' : '否' }}
        </template>
      </ElTableColumn>

      <ElTableColumn label="备注" prop="memo"/>

      <ElTableColumn label="操作" width="180">
        <template #default="scope">
          <div class="action-btn">
            <el-popconfirm
              cancel-button-text="否"
              cancel-button-type="primary"
              confirm-button-text="是"
              confirm-button-type="danger"
              placement="top"
              title="是否删除当前数据?"
              width="180"
              @confirm="delHandler(scope)">
              <template #reference>
                <ElButton :loading="deling" text type="danger">删除</ElButton>
              </template>
            </el-popconfirm>
            <ElButton text type="primary" @click="showLog(scope.row.id!)">查看日志</ElButton>
          </div>
        </template>
      </ElTableColumn>
    </ElTable>
    <ElPagination
      :page-size="pagination.size"
      :total="pagination.total"
      class="pagination"
      layout="prev, pager, next"
      @change="pageChangeHandler"/>
    <ExecuteLogPanel ref="executeLogPanel"/>
  </div>
</template>
<script lang="ts" setup>
import TaskScheduleRecodeApi from '@/pages/sys/task/schedule-recode/schedule-recode-api.ts'
import { elIcons } from '@/common/element/element.ts'
import Times from '@/common/utils/times.ts'
import ExecuteLogPanel from '@/pages/sys/task/execute-log/ExecuteLogPanel.vue'
import Colls from '@/common/utils/colls.ts'

const executeLogPanelIns = useTemplateRef<InstanceType<typeof ExecuteLogPanel>>('executeLogPanel')

const props = defineProps<{
  taskId: string
}>()
const scheduleTypeList = [
  {value: 'Manually', label: '手动'},
  {value: 'Fixed', label: '固定周期'},
  {value: 'Cron', label: '自定义'},
]
const shortcuts = [
  {
    text: '上周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [ start, end ]
    },
  },
  {
    text: '上个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [ start, end ]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [ start, end ]
    },
  },
]

function showLog(id: string) {
  executeLogPanelIns.value?.open(id)
}

function scheduleType(type: string) {
  return [
    {value: 'Manually', label: '手动'},
    {value: 'Fixed', label: '固定周期'},
    {value: 'Cron', label: '自定义'},
  ].find(it => it.value === type)?.label
}

const status = [
  {value: 'Waiting', label: '等待调度'},
  {value: 'Pending', label: '排队中'},
  {value: 'Running', label: '运行中'},
  {value: 'Completed', label: '已完成'},
  {value: 'Error', label: '错误'},
]

const tableData = ref<TaskScheduleRecodeTypes.SearchTaskScheduleRecodeResult[]>([])
const searchForm = ref<TaskScheduleRecodeTypes.SearchTaskScheduleRecodeParam>({
  current: 1,
  size: 20,
})
const searching = ref(false)
const deling = ref(false)
const showSearchForm = ref(true)
const pagination = reactive<G.Pagination>({
  total: 0,
  pages: 0,
  current: 1,
  size: 20,
})

function pageChangeHandler(currentPage: number, pageSize: number) {
  searchForm.value.current = currentPage
  searchForm.value.size = pageSize
  paging()
}

function delHandler({row}: { row: TaskScheduleRecodeTypes.SearchTaskScheduleRecodeResult }) {
  deling.value = true
  TaskScheduleRecodeApi.del([ row.id! ])
    .then(() => {
      ElMessage.success('删除成功')
      paging()
    })
    .finally(() => {
      deling.value = false
    })
}

function reset() {
  searchForm.value = {
    current: 1,
    size: 20,
  }
  paging()
}

function paging() {
  searching.value = true
  const {
    scheduleType,
    scheduleTime,
    taskStatus,
    manually,
  } = searchForm.value
  TaskScheduleRecodeApi.paging({
    taskId: props.taskId,
    scheduleType,
    taskStatus,
    manually,
    startTime: Colls.isEmpty(scheduleTime) ? undefined : Times.format(scheduleTime![0]),
    endTime: Colls.isEmpty(scheduleTime) ? undefined : Times.format(scheduleTime![1]),
  })
    .then(res => {
      tableData.value = res.data?.records ?? []
    })
    .finally(() => {
      searching.value = false
    })
}

onMounted(() => {
  paging()
})
</script>
<style lang="stylus" scoped>
.table-list {
  height 50vh;
  width 100%

  :deep(.table-header) {
    color #454C59

    th {
      background-color #EDF1F7
      font-weight 500
      position relative

      & > div {
        display flex
        gap 5px
        align-items center
      }

      &:not(:first-child) > div::before {
        position: absolute;
        top: 50%;
        left: 1px;
        width: 1px;
        background-color: #D3D7DE;
        transform: translateY(-50%);
        content: "";
        height 50%
      }
    }
  }

  :deep(.table-cell) {
    color #2F3540
  }

  .action-btn {
    width 100%
    display flex
    flex-wrap wrap

    & > button {
      margin 0
    }
  }
}

.tool-bar {
  display flex
  justify-content space-between
  margin 0 0 20px 0
}

.pagination {
  justify-content: end;
  margin: 8px;
}
</style>
