<template>
  <PageWrapper>
    <el-card :bordered="false" class="pt-3 mb-3 proCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset"></BasicForm>
    </el-card>
    <el-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="tableRef"
        :actionColumn="actionColumn"
         @selection-change="onSelectionChange"
      >
        <template #tableTitle>
          <el-button type="primary" @click="handleAdd" v-perm="['sys:job:add']">
            <template #icon>
              <el-icon class="el-input__icon">
                <PlusOutlined />
              </el-icon>
            </template>
            添加任务
          </el-button>
          <el-button type="danger" @click="handleDelete()" :disabled="!selectionData.length" v-perm="['sys:job:batchDelete']">
              <template #icon>
                <el-icon class="el-input__icon">
                  <Delete />
                </el-icon>
              </template>
              删除
            </el-button>
        </template>
        <template #status="{ scope }">
          <el-switch v-model="scope.row.realStatus" @change="handelSetStatus(scope.row)" />
        </template>
      </BasicTable>
    </el-card>

    <editDialog
        v-if="editVisible"
        :jobId="jobId"
        v-model:visible="editVisible"
        @success="reloadTable('noRefresh')"
    >
    </editDialog>
    <jobLog
      v-if="editLogVisible"
        :jobId="jobId"
        v-model:visible="editLogVisible">
    </jobLog>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { reactive, ref, h,nextTick,defineAsyncComponent } from 'vue';
  import { ColProps } from 'element-plus';
  import { schemas } from './querySchemas';
  import { useForm } from '@/components/Form/index';
  import { TableAction } from '@/components/Table';
  import { getJobList,jobDelete,jobBatchDelete,getJobRunOnce,setJobStatus,getJobPause,getJobResume } from '@/api/monitor/job';
  import { columns } from './columns';
  import { PlusOutlined } from '@vicons/antd';
  import {message,confirm} from "@/utils/auth";
  import { useRouter } from 'vue-router';
  const router = useRouter();
  const editDialog = defineAsyncComponent(() =>
    import('./edit.vue')
)
const jobLog = defineAsyncComponent(() =>
    import('./log/index.vue')
)
const jobId =ref(0)
const editVisible=ref(false)
const editLogVisible=ref(false)
const selectionData = ref([])
  const tableRef = ref();
  const formParams = reactive({
    jobName:'',
    status:''
  });
  const actionColumn = reactive({
    width: 300,
    label: '操作',
    prop: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction, {
        style: 'button',
        actions: [
        {
            label: '启动',
            type: 'success',
            onClick: handelChangeStatus.bind(null, record),
            auth:['sys:job:resume'],
            ifShow: () => {
              return record.row.status==0 ||record.row.status==2;
            },
          },
          {
            label: '暂停',
            type: 'warning',
            onClick: handelChangeStatus.bind(null, record),
            auth:['sys:job:pause'],
            ifShow: () => {
              return record.row.status==1;
            },
          },
          {
            label: '编辑',
            icon:'Edit',
            type: 'warning',
            onClick: handleEdit.bind(null, record),
            disabled:record.row.status==1,
            auth: ['sys:job:update'],
          },
          {
            label: '删除',
            icon:'Delete',
            type: 'danger',
            onClick: handleDelete.bind(null, record),
            // 根据权限控制是否显示: 有权限，会显示，支持多个
            auth: ['sys:job:delete'],
          },
        ],
        dropDownActions: [
          {
            label: '执行一次',
            key: 'runOnce',
            auth: ['sys:job:runOnce'],
            ifShow: () => {
              return record.row.status==2;
            },
          },
          {
            label: '调度日志',
            key: 'jobLog',
            auth:['sys:job:jobLog']
          },
        ],
        select: (key) => {
          if(key=='runOnce') {
            handelRunOnce(record)
          } else if(key=='jobLog'){
            handleJobLog(record)
          }
        },
      });
    },
  });

  const loadDataTable = async (res: any) => {
    const result = await getJobList({ ...formParams, ...res });
    result.records.map(item=>{
      if(item.status==0) {
        item.realStatus = false
      } else {
        item.realStatus = true
      }
    })
    return result;
  };

  function reloadTable(noRefresh='') {
    tableRef.value.reload(noRefresh?{}:{pageNo:1});
  }
  const [register, {}] = useForm({
    labelWidth: 100,
    layout: 'horizontal',
    colProps: { span: 6 } as ColProps,
    submitOnReset:true,
    schemas
  });
  function handleSubmit(values: Recordable) {
    handleReset()
    for (const key in values) {
      formParams[key] = values[key]
    }
    reloadTable();
  }

  function handleReset() {
    for (const key in formParams) {
        formParams[key] ='';
    }
  }
  const handleAdd = async () => {
    jobId.value=0
  await nextTick();
  editVisible.value=true
};
const handelSetStatus = async(row)=>{
  await setJobStatus({id:row.id,status:row.realStatus?1:0})
  message("设置成功");
  reloadTable('noRefresh')
}
const handleEdit = async (record: Recordable) => {
  jobId.value=record.row.id
  await nextTick();
  editVisible.value=true
};
const handelChangeStatus = async (record)=>{
  await confirm(`确定要${record.row.status==1?'暂停':'启动'}`);
  record.row.status==1 ? await getJobPause(record.row.id):await getJobResume(record.row.id)
  reloadTable('noRefresh');
}
const handelRunOnce = async (record)=>{
  await confirm('确定要执行一次？');
  await getJobRunOnce(record.row.id)
  message("执行成功");
}
async function handleDelete(record: Recordable) {
    let ids = []
    if(!record){
      ids = selectionData.value.map(({id}) => id);
    }
    await confirm('确定要删除？');
    record? await jobDelete(record.row.id):await jobBatchDelete(ids);
    message("删除成功");
    reloadTable()
  }
  const handleJobLog=(record)=>{
    // router.push({path:'/monitorJob/log'})
    editLogVisible.value = true
    jobId.value=record.row.id
  }
function onSelectionChange(value){
    selectionData.value = value
  }
</script>

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