<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import {
  getRepJobListApi,
  saveRepJobApi,
  delRepJobListApi,
  delRepJobApi,
  queryRepJobApi,
  exportExcelApi,
  importExcelApiUrl,
  runData,
  runRelyOnData,
  ScheduleJobAdd,
  RepScheduleJobStop
} from '@/api/job/RepJob'
import { Upload } from '@/components/Upload'
import { TableData } from '@/api/job/RepJob/types'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ElButton, ElLink, ElLoading,ElPopover, ElPopconfirm, ElMessage,ElTag,ElMessageBox } from 'element-plus'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import Run from './components/Run.vue'
import Clock from './components/Clock.vue'
import { Dialog } from '@/components/Dialog'
import { JOB_TYPE_LIST,JOB_BUSSINESS_TYPE_LIST } from './constants'
import { findListLabel } from '@/utils'
import dayjs from 'dayjs'
import { useRoute,useRouter } from 'vue-router'
const { push } = useRouter();
const route = useRoute();
defineOptions({
  name: 'RepJob'
})
const pageQuery = ref(route || null); 
const systemCode = pageQuery.value?.query?.systemCode;
const { t } = useI18n()

const ids = ref<string[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getRepJobListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      jPid:systemCode,
      ...unref(searchParams)
    })
    return {
      list: res.body.list,
      total: res.body.total
    }
  },
  fetchDelApi: async () => {
    const res = await delRepJobListApi(unref(ids))
    return !!res
  }
})

const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList, refresh } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'selection',
    type: 'selection',
    width: 50,
  },
  {
    field: 'jPid',
    label: '系统编号',
    fixed:"left",
    width: 120,
  },
  {
    field: 'jId',
    label: '作业编号',
    width: 120,
  },
  {
    field: 'jName',
    label: '作业名称',
    width: 200,
    align:'left',
    headerAlign:'left'
  },
  {
    field: 'jBusinessType',
    label: '业务分类',
    width: 130,
    slots:{
      default:(data:any) => {
        return (
          <>
            <ElPopover
              placement="top-start"
              width="120"
              trigger="hover"
              effect="dark"
              content="用于并发任务使用"
              v-slots={{
                reference: () => {
                  const temp = JOB_BUSSINESS_TYPE_LIST.filter(item=>{
                    return item.value == data.row.jBusinessType;
                  })
                  return (
                    <>
                      <div v-slots="reference">{temp[0]?.label}</div> 
                    </>
                  )
                }
              }}
            >
          </ElPopover>
          </>
        )
      }
    }
  },
  {
    field: 'jBeforeJob',
    label: '前置作业名称',
    width: 150,
    align: 'left',
  },
  {
    field: 'jType',
    label: '作业类型',
    width: 150,
    formatter: (row: Recordable, __: TableColumn) => {
      const label = findListLabel(JOB_TYPE_LIST, row.jType)
      if (label) {
        return label
      }
    }
  },
  {
    field: 'createTime',
    label: '创建时间',
    width: 180,
  },
  {
    field: 'updateTime',
    label: '更新时间',
    width: 180,
  },
  {
    field: 'sStatus',
    label: '定时状态',
    slots: {
      default: (data: any) => {
        // 0:启用,1:停止
        if(data.row.sStatus === '0' || data.row.sStatus === '1'){
          return <ElTag type={data.row.sStatus?'success':'warning'}>{data.row.sStatus?t('userDemo.enable'):t('userDemo.stopUsing')}</ElTag>
        }else{
          return <><span></span></>
        }
      }
    }
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 280,
    fixed:"right",
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElLink type="primary" underline={false} onClick={() => editAction(data.row)}>
              {t('tableDemo.edit')}
            </ElLink>
            <ElLink type="primary" underline={false} onClick={() => clockAction(data.row)}>
              {data.row.sStatus?'停止':'定时'}
            </ElLink>
            <ElLink type="primary" underline={false} onClick={() => runJob(data.row)}>
              {t('RepJob.run')}
            </ElLink>
            <ElLink type="primary" underline={false} onClick={() => action('JobMonitor',data.row)}>
              {t('RepJob.monitor')}
            </ElLink>
            <ElPopconfirm
              title={t('common.delTableMsg')}
              width={200}
              v-slots={{
                reference: () => {
                  return (
                    <>
                      <ElLink type="primary" underline={false}>
                        {t('tableDemo.del')}
                      </ElLink>
                    </>
                  )
                }
              }}
              onConfirm={() => delData(data.row)}
            ></ElPopconfirm>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'jPid',
    label: '系统编号',
    component: 'Input',
    value:systemCode,
    hidden:systemCode?true:false
  },
  {
    field: 'jId',
    label: '作业编号',
    component: 'Input'
  },
  {
    field: 'jName',
    label: '作业名称',
    component: 'Input'
  },
  {
    field: 'jBusinessType',
    label: '业务分类',
    component: 'Select',
    componentProps: {
      options: JOB_BUSSINESS_TYPE_LIST
    }
  },
  {
    field: 'jBeforeJob',
    label: '前置作业名称',
    component: 'Input'
  },
  {
    field: 'jType',
    label: '作业类型',
    component: 'Select',
    componentProps: {
      options: JOB_TYPE_LIST
    }
  },
])

const searchParams = ref({})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

/**单行查询**/
const action = async (path:string,row: any) => {
  //跳转作业监控界面
    push({name:path,query:{systemCode:row.jPid,jId:row.jId}});
}
//新增规则
const AddAction = () => {
  dialogTitle.value = t('tableDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = 'add'
}
//编辑规则
const editAction = (row:TableData)=>{
  dialogTitle.value = t('tableDemo.edit');
  currentRow.value = row;
  dialogVisible.value = true
  actionType.value = 'edit'
}
//定时执行任务
const clockAction = (row:TableData) => {
  if(row?.sStatus){
    //停止任务（有一个停止任务的弹框）
    ElMessageBox.confirm('请确认是否停止本次作业？', '提示', {  
      confirmButtonText: '确定',  
      cancelButtonText: '取消',  
      type: 'warning'  
    }).then(async () => {  
      // 用户点击确定（调停止作业的接口）  
      await RepScheduleJobStop({jId:row.jId}).then(res=>{
        if(res.head.code == '0'){
          ElMessage.success('定时器关闭成功');
        }
      }).catch(err=>{
        ElMessage.error('定时器关闭失败');
      })
      getList();
    })
    return;
  }
  dialogTitle.value = '设置定时器';
  currentRow.value = row;
  clockJobVisible.value = true;
}

const saveLoading = ref(false)

/** 保存 **/
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    // 新增
    if (['', 'add'].includes(actionType.value)) {
      formData.createTime = dayjs(new Date()).format('YYYYMMDD HH:mm:ss')
    }
    // 更新时间
    formData.updateTime = dayjs(new Date()).format('YYYYMMDD HH:mm:ss')
    saveLoading.value = true
    const res = await saveRepJobApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}

const delLoading = ref(false)

/** 批量删除  **/
const delDataBatch = async () => {
  const elTableExpose = await getElTableExpose()
  ids.value =
    elTableExpose?.getSelectionRows().map((v: TableData) => {
      return { jPid: v.jPid, jName: v.jName,jId: v.jId }
    }) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

/** 单行删除 */
const delData = async (row: TableData) => {
  const res = await delRepJobApi(row.jPid, row.jName, row.jId)
  if (res) {
    const { code, errMsg } = res.head
    if (code === '0') {
      ElMessage.success('删除成功!')
      getList()
    } else {
      ElMessage.error(errMsg || '删除失败!')
    }
  }
}

const disabled = ref(true)

const onSelectionChange = (selection: TableData[]) => {
  disabled.value = selection.length === 0
}

/** 导出Excel */
const exportExcel = async () => {
  const data = { jPid:systemCode,...unref(searchParams) }
  await exportExcelApi(data)
}

const runJobVisible = ref(false)
const clockJobVisible = ref(false)
/** 运行 */
const runJob = (data: TableData) => {
  dialogTitle.value = `运行【${data.jName}】`;
  currentRow.value = data;
  runJobVisible.value = true;
}

const runRef = ref<ComponentRef<typeof Run>>()
//执行
const runDataJob = async () => {
  const run = unref(runRef)
  const formData = await run?.submit()
  if (formData) {
    const data = {
      ...currentRow.value,
      ...formData
    }
    let detailLoading = ElLoading.service({
      background: 'rgba(0, 0, 0, 0.7)'
    })
    const res = formData.jModuleState?await runRelyOnData(data).catch(()=>{detailLoading.close();}):await runData(data).catch(()=>{detailLoading.close();});
    detailLoading.close();
    if (res) {
      const { code, errMsg } = res.head
      if (code === '0') {
        runJobVisible.value = false
        ElMessage.success('运行成功!')
      } else {
        ElMessage.error(errMsg || '运行失败!')
      }
    }
  }
}

const clockRef = ref<ComponentRef<typeof Clock>>()
//定时
const clockDataJob = async()=>{
  const clock = unref(clockRef);
  const formData = await clock?.submit();
  if (formData) {
    let detailLoading = ElLoading.service({
      background: 'rgba(0, 0, 0, 0.7)'
    })
    const data = {
      ...currentRow.value,
      ...formData
    }
    const res = await ScheduleJobAdd(data);
    detailLoading.close();
    if (res) {
      const { code, errMsg } = res.head
      if (code === '0') {
        clockJobVisible.value = false
        ElMessage.success('运行成功!');
        //查列表
        getList();
      } else {
        ElMessage.error(errMsg || '运行失败!');
      }
    }
  }
}

</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <Table
      align="center"
      headerAlign="center"
      :columns="tableColumns"
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @selection-change="onSelectionChange"
      @register="tableRegister"
      @refresh="refresh"
    >
      <template #buttons>
        <ElButton type="primary" @click="AddAction">{{ t('tableDemo.add') }}</ElButton>
        <ElButton :loading="delLoading" type="primary" :disabled="disabled" @click="delDataBatch()">
          {{ t('tableDemo.del') }}
        </ElButton>
        <ElButton type="primary" @click="exportExcel()">{{ t('tableDemo.export') }}</ElButton>
        <Upload :url="importExcelApiUrl" :callback="getList">
          <ElButton type="primary">{{ t('tableDemo.import') }}</ElButton>
        </Upload>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :current-row="currentRow"
      :action-type="actionType"
      :system-code="systemCode"
    />
    <Detail v-if="actionType === 'detail'" :current-row="currentRow" />
    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save">
        {{ t('dialogDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>

  <!-- 运行 -->
  <Dialog v-model="runJobVisible" :title="dialogTitle" max-height="300px">
    <Run ref="runRef" :current-row="currentRow" />
    <template #footer>
      <ElButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="runDataJob"
      >
        运行
      </ElButton>
      <ElButton @click="runJobVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>

  <!-- 定时 -->
  <Dialog v-model="clockJobVisible" :title="dialogTitle" max-height="300px">
    <Clock ref="clockRef" :current-row="currentRow" />
    <template #footer>
      <ElButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="clockDataJob"
      >
        执行
      </ElButton>
      <ElButton @click="clockJobVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>

</template>
