<template>
  <Page>
    <ElForm v-show="showSearchForm" inline @submit.prevent="paging">
      <ElFormItem label="任务名称">
        <ElInput
          v-model="searchForm.taskName"
          placeholder="任务名称"/>
      </ElFormItem>
      <ElFormItem label="任务执行函数">
        <ElInput
          v-model="searchForm.fn"
          placeholder="任务执行函数"/>
      </ElFormItem>
      <ElFormItem label="调度方式">
        <ElSelect
          v-model="searchForm.scheduleType"
          clearable placeholder="请选择调度方式" style="width: 150px" @change="paging" @clear="paging">
          <ElOption v-for="item in scheduleTypeList" :key="item.value" :label="item.label" :value="item.value"/>
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="内部任务">
        <ElCheckbox
          @change="paging"
          v-model="searchForm.builtin"
          placeholder="内部任务"/>
      </ElFormItem>
      <ElFormItem v-if="!searchForm.builtin" label="状态">
        <ElSelect v-model="searchForm.disabled" clearable placeholder="请选择状态" style="width: 150px" @clear="paging">
          <ElOption :value="true" label="禁用"/>
          <ElOption :value="false" label="启用"/>
        </ElSelect>
      </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.Plus" type="primary" @click="addHandler">新建</ElButton>
      <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="logLevelTxt"/>

      <ElTableColumn label="调度方式" prop="scheduleTypeTxt"/>

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

      <ElTableColumn label="临界时间" prop="criticalTiming" width="170">
        <template #default="{row}">
          <span>
            {{ row.criticalTiming != null && row.criticalTiming > 0 ? Times.format(Times.parse(row.criticalTiming * 1000)) : '' }}
          </span>
        </template>
      </ElTableColumn>

      <ElTableColumn label="是否禁用" width="180">
        <template #default="scope">
          <span>
            {{ scope.row.disabled ? '是' : '否' }}
          </span>
        </template>
      </ElTableColumn>

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

      <ElTableColumn label="操作" width="180">
        <template #default="scope">
          <div class="action-btn">
            <el-popconfirm
              v-if="!scope.row.builtin"
              cancel-button-type="primary"
              cancel-button-text="否"
              confirm-button-type="danger"
              confirm-button-text="是"
              placement="top"
              title="是否删除当前数据?"
              width="180"
              @confirm="delHandler(scope)">
              <template #reference>
                <ElButton :loading="deling" text type="danger">删除</ElButton>
              </template>
            </el-popconfirm>
            <ElButton v-if="!scope.row.builtin" text type="primary" @click="modifyHandler(scope)">修改</ElButton>
            <ElButton v-if="!scope.row.builtin" text type="primary" @click="disable(scope)">{{ scope.row.disabled ? '启用' : '禁用' }}</ElButton>
            <ElButton v-if="!scope.row.disabled" text type="primary" @click="trigger(scope)">执行一次</ElButton>
            <ElButton text type="primary" @click="showRecode(scope.row.id)">调度记录</ElButton>
          </div>
        </template>
      </ElTableColumn>
    </ElTable>
    <ElPagination
      class="pagination"
      layout="prev, pager, next"
      :page-size="pagination.size"
      :total="pagination.total"
      @change="pageChangeHandler"/>
    <TaskForm ref="taskForm" @edit-succ="paging"/>
    <ScheduleRecodePanel ref="scheduleRecodePanel"/>
  </Page>
</template>
<script lang="ts" setup>
import TaskApi from '@/pages/sys/task/task-api.ts'
import Page from '@/components/page/Page.vue'
import { elIcons } from '@/common/element/element.ts'
import TaskForm from '@/pages/sys/task/TaskForm.vue'
import ScheduleRecodePanel from '@/pages/sys/task/schedule-recode/ScheduleRecodePanel.vue'
import Times from '@/common/utils/times.ts'

const tableData = ref<TaskTypes.SearchTaskResult[]>([])
const searchForm = ref<TaskTypes.SearchTaskParam>({
  current: 1,
  size: 20,
  builtin: false,
})
const searching = ref(false)
const deling = ref(false)
const showSearchForm = ref(true)
const taskFormIns = useTemplateRef<InstanceType<typeof TaskForm>>('taskForm')
const scheduleRecodePanelIns = useTemplateRef<InstanceType<typeof ScheduleRecodePanel>>('scheduleRecodePanel')
const pagination = reactive<G.Pagination>({
  total: 0,
  pages: 0,
  current: 1,
  size: 1,
})
const scheduleTypeList = [
  {value: 'Manually', label: '手动'},
  {value: 'Fixed', label: '固定周期'},
  {value: 'Cron', label: '自定义'},
]

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

function showDialog(data?: TaskTypes.SearchTaskResult) {
  taskFormIns.value?.open(data)
}

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

function modifyHandler({row}: { row: TaskTypes.SearchTaskResult }) {
  showDialog(row)
}

function trigger({row}: { row: TaskTypes.SearchTaskResult }) {
  TaskApi.trigger(row.id!)
    .then(() => {
      ElMessage.success('已提交触发请求')
    })
}

function disable({row}: { row: TaskTypes.SearchTaskResult }) {
  TaskApi.disable(row.id!, !row.disabled!)
    .then(() => {
      ElMessage.success(row.disabled ? '启用成功' : '禁用成功')
      paging()
    })
}

function addHandler() {
  showDialog()
}

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

function paging() {
  searching.value = true
  TaskApi.paging(searchForm.value)
    .then(res => {
      tableData.value = res.data?.records ?? []
    })
    .finally(() => {
      searching.value = false
    })
}

function showRecode(id: string) {
  scheduleRecodePanelIns.value?.open(id)
}

onMounted(() => {
  paging()
})
</script>
<style lang="stylus" scoped>
.table-list {
  flex 1;
  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>
