<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import {
  getRepTaskListApi,
  saveRepTaskApi,
  delRepTaskListApi,
  getSubTaskListApi,
  queryRepTaskApi,
  ReRunTaskApi,
  RefreshTask,
  RepTaskErrorMessageDownload,
  RepTaskFileDownload
} from '@/api/job/RepTask'
import { TableData } from '@/api/job/RepTask/types'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ElButton, ElLink, ElLoading, ElTag,ElMessage,ElProgress } 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 { Dialog } from '@/components/Dialog'
import { getLoginNameByUserInfo } from '@/utils/auth'
import { TASK_STATE_DICT_LIST,TASK_PROGRESS_LIST } from './components/constants'
import { randomCode } from '@/utils'
import { propTypes } from '@/utils/propTypes'
import { useRoute,useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();
defineOptions({
  name: 'JobMonitor'
})
defineProps({
  monitorInfo: propTypes.object.def({})
})
const { t } = useI18n()

const pageQuery = ref(route || null); 
const systemCode = pageQuery.value?.query?.systemCode;
const jId = pageQuery.value?.query?.jId;

const ids = ref<string[]>([])
  const createUser = getLoginNameByUserInfo();
  const { tableRegister, tableState, tableMethods } = useTable({
    fetchDataApi: async () => {
      const { currentPage, pageSize } = tableState
      console.log(searchParams,"查询参数");
      const res = await getRepTaskListApi({
        pageNum: unref(currentPage),
        createUser: unref(createUser),
        pageSize: unref(pageSize),
        // pId:systemCode,
        // jId:jId,
        ...unref(searchParams)
    })
    const list = res.body.list.map((item: TableData) => {
      item.randomCode = randomCode(32)
      item.hasChildren = true
        return item
      });
    return {
      list: list,
      total: res.body.total
    }
  },
  fetchDelApi: async () => {
    const res = await delRepTaskListApi(unref(ids))
    return !!res
  }
})
const searchSchema = reactive<FormSchema[]>([
  {
    field: 'pId',
    label: '系统编号',
    component: 'Input',
    value:systemCode,
    hidden:systemCode?true:false
  },
  {
    field: 'jId',
    label: '作业编号',
    component: 'Input',
    value:jId,
  },
  // {
  //   field: 'repCode',
  //   label: '任务编号',
  //   component: 'Input',
  // },
  {
    field: 'tBtid',
    label: '批次id',
    component: 'Input',
  },
  {
    field: 'name',
    label: '任务名称',
    component: 'Input',
  },
  {
    field: 'state',
    label: '状态',
    componentProps: {
      options: TASK_STATE_DICT_LIST,
    },
    component: 'Select',
  },
  {
    field: 'dataDate',
    label: '数据日期',
    componentProps: {
      valueFormat:'YYYYMMDD'
    },
    component: 'DatePicker',
  },
  {
    field: 'dateRangeList',
    label: '任务执行时间区间',
    componentProps: {
      type:"daterange",
      startPlaceholder:"任务开始时间",
      endPlaceholder:"任务结束时间",
      valueFormat:'YYYYMMDD'
    },
    component: 'DatePicker',
  },
  
])
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, refresh } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'selection',
    type: 'selection',
  },
  {
    field: 'id',
    label: '任务ID',
    hidden:true
  },
  {
    field: 'name',
    label: '任务名称',
    align:'left',
    headerAlign:'left',
    width:350
  },
  {
    field: 'tBtid',
    label: '批次id',
    align:'center',
    width:300
  },
  {
    field: 'serverNode',
    label: '所属服务器',
    align:'center',
    width:150
  },
  {
    field: 'state',
    label: '状态',
    align:'center',
    width:150,
    formatter:(row:Recordable,_:TableColumn) =>{
      const state=TASK_STATE_DICT_LIST.find((item)=>item.value===row.state)
      if(state){
          return <ElTag type={state.type} round>{state.label}</ElTag>
      }
      return <ElTag type="info" round>排队中</ElTag>
    }
  },
  {
    field: 'progress',
    label: '执行进度',
    align:'center',
    width:200,
    formatter:(row:Recordable,_:TableColumn) =>{
      const state=TASK_PROGRESS_LIST.find((item)=>item.value==row.state);
      const progressAllInfo = row.progress;//定义当前进度的信息
      let number = progressAllInfo?.match(/\d+%/g)[0];
      let progressNumber = number?number:(state?.value=='finish'?'100%':'0%');
      if(state && state.value!='init'){
          return <ElProgress percentage={parseInt(progressNumber)} status={state.status}>
                    <span>{progressAllInfo?progressAllInfo:progressNumber}</span>
                  </ElProgress>
      }else{
        return <ElProgress percentage={100} status={"warning"} indeterminate={true} duration={1}>
                  <span>排队中...</span>
                </ElProgress>
      }
    }
  },
  {
    field: 'startTime',
    label: '开始时间',
    align:'center',
    width:200,
  },
  {
    field: 'endTime',
    label: '结束时间',
    align:'center',
    width:200,
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 250,
    align:'center',
    fixed:"right",
    slots: {
      default: (data: any) => {
        if(data.row?.state=='error' || data.row?.state=='finish'){
          return (
            <>
              <ElLink type="primary" underline={false} onClick={() => downTaskData(data.row,data.row.state)} v-show={data.row.state=='error' || (data.row.state!='error' && (data.row.type=='buildrep' || data.row.type=='excel'))}>
                {data.row.state=='error'?'下载错误日志':'下载任务文件'}
              </ElLink>
              <ElLink type="primary" underline={false} onClick={() => ReExecuteTask(data.row)}>
                {'重新执行'}
              </ElLink>
              <ElLink type="primary" underline={false} onClick={() => action(data.row, 'detail')}>
                {t('tableDemo.detail')}
              </ElLink>
            </>
          )
        }else{
          return (
            <>
              <ElLink type="primary" underline={false} onClick={() => action(data.row, 'detail')}>
                {t('tableDemo.detail')}
              </ElLink>
            </>
          )
        }
      }
    },
    // hidden:true
  }
])

const searchParams = ref({})
const setSearchParams = (data: any) => {
  if(data.dateRangeList){
    data.startDate = data.dateRangeList[0];
    data.endDate = data.dateRangeList[1];
  }
  searchParams.value = data;
  getList();
}
setSearchParams({pId:systemCode,jId:jId})
const dialogVisible = ref(false)
const dialogTitle = ref('')

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

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

/**单行查询**/
const action = async (row: any, type: string) => {
  let detailLoading = ElLoading.service({
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const res = await queryRepTaskApi(row.id)
    .catch(() => {})
    .finally(() => {
      detailLoading.close()
    })
  detailLoading.close()
  if (res) {
    const data = res.body.result
    dialogTitle.value = t(type === 'edit' ? 'tableDemo.edit' : 'tableDemo.detail')
    actionType.value = type
    currentRow.value = data
    dialogVisible.value = true
  }
}
/** 重新执行 **/
const ReExecuteTask = (row: any) => {
  //重新执行
  ReRunTaskApi(row).then(res=>{
  }).catch(res=>{
  })
  setTimeout(()=>{
    getList();
  },100)
}
/** 下载任务信息 **/
const downTaskData = (row,status)=>{
  switch(status){
    case 'error':
      RepTaskErrorMessageDownload({id:row.id})
      break;
    case 'finish':
      RepTaskFileDownload({id:row.id})
      break;
    default:
      RepTaskErrorMessageDownload({id:row.id})
      break;
  }
}

const saveLoading = ref(false)

/** 保存 **/
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const res = await saveRepTaskApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}

/** 数据加载 */
const load = async (
  row: TableData,
  __: any,
  resolve: (date: TableData[]) => void
) => {
  const formData = {
    id:row.id
  };
  const res = await getSubTaskListApi(formData)
  if (res) {
    const data = res?.body?.list;
    if(data.length == 0){
      ElMessage.success("该任务下没有执行的子任务");
    }
    resolve(data)
  }
}


const disabled = ref(true)

const onSelectionChange = (selection: TableData[]) => {
  disabled.value = selection.length === 0
}
/* 刷新任务 */
const refreshTaskList = ()=>{
  let detailLoading = ElLoading.service({
    background: 'rgba(0, 0, 0, 0.7)'
  })
  RefreshTask({}).then(res=>{
    detailLoading.close();
    getList();
    ElMessage.success('刷新成功');
  }).catch(()=>{
    detailLoading.close();
    ElMessage.error('刷新失败');
  })
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />

    <Table
      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"
      row-key="randomCode"
      lazy
      :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren'}"
    >
      <template #buttons>
        <ElButton type="primary" @click="refreshTaskList"><Icon
          icon="ant-design:sync-outlined" class="cursor-pointer"
          hover-color="var(--el-color-primary)"
        />刷新任务
        </ElButton>
        <ElButton type="primary" @click="router.go(-1)" v-if="jId"><Icon
          icon="ant-design:rollback-outlined" class="cursor-pointer"
          hover-color="var(--el-color-primary)"
        />返回作业管理
        </ElButton>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow" />
    <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>
</template>
