<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { Upload } from '@/components/Upload'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElLink, ElMessage, ElTag, ElPopconfirm } from 'element-plus'
import { Table } from '@/components/Table'
import {
  getDepartmentApi,
  getDepartmentTableApi,
  saveDepartmentApi,
  exportExcelApi,
  importExcelApiUrl,
  runCDataApi,
  runDataApi,
  deleteApi
} from '@/api/jobmanage/jobconfig'
import type { DepartmentItem, TableData } from '@/api/jobmanage/jobconfig/types'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref, reactive } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useRouter } from 'vue-router'

const { push } = useRouter()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getDepartmentTableApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.list.length
    }
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, refresh } = tableMethods

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

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('RepJob.index'),
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'jPid',
    label: t('RepJob.jPid'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'jName',
    label: t('RepJob.jName'),
    table: {
      slots: {
        default: (data: any) => {
          return <>{data.row.jName}</>
        }
      }
    },
    form: {
      component: 'TreeSelect',
      componentProps: {
        nodeKey: 'id',
        props: {
          label: 'J_NAME'
        }
      },
      optionApi: async () => {
        const res = await getDepartmentApi()
        return res.data.list
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          return <>{data.departmentName}</>
        }
      }
    }
  },
  {
    field: 'jDescription',
    label: t('RepJob.jDescription'),
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return <>{data.row.jDescription}</>
        }
      }
    },
    form: {
      component: 'Select',
      componentProps: {
        options: [
          {
            value: 0,
            label: t('userDemo.disable')
          },
          {
            value: 1,
            label: t('userDemo.enable')
          }
        ]
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElTag type={data.status === 0 ? 'danger' : 'success'}>
                {data.status === 1 ? t('userDemo.enable') : t('userDemo.disable')}
              </ElTag>
            </>
          )
        }
      }
    }
  },
  {
    field: 'JBeforeJob',
    label: t('RepJob.jBeforeJob'),
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return <>{data.row.JBeforeJob}</>
        }
      }
    }
  },
  {
    field: 'jType',
    label: t('RepJob.jType'),
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return <>{data.row.jType}</>
        }
      }
    }
  },
  {
    field: 'createTime',
    label: t('RepJob.createTime'),
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return <>{data.row.createTime}</>
        }
      }
    }
  },
  {
    field: 'updateTime',
    label: t('RepJob.updateTime'),
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return <>{data.row.updateTime}</>
        }
      }
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElLink type="primary" underline={false} onClick={() => runData(data.row)}>
                {t('RepJob.run')}
              </ElLink>
              <ElLink type="primary" underline={false} onClick={() => runCData(data.row)}>
                {'带下级执行'}
              </ElLink>
              <ElLink type="primary" underline={false} onClick={() => monitorData(data.row)}>
                {t('RepJob.monitor')}
              </ElLink>
              <ElPopconfirm
                title={t('common.delTableMsg')}
                width={200}
                v-slots={{
                  reference: () => {
                    return (
                      <>
                        <ElLink type="primary" underline={false}>
                          {t('exampleDemo.del')}
                        </ElLink>
                      </>
                    )
                  }
                }}
                onConfirm={() => delData(data.row)}
              ></ElPopconfirm>
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

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

const currentRow = ref<DepartmentItem | null>(null)
const actionType = ref('')

const delData = async (row: TableData) => {
  const res = await deleteApi(row.jPid, row.jName)
  if (res) {
    const { code } = res.data
    if (code === 1) {
      ElMessage.success('操作成功!')
      getList()
    } else {
      ElMessage.error('操作失败!')
    }
  }
}

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

const saveLoading = ref(false)

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

/** 运行 */
const runData = async (row: TableData) => {
  const res = await runDataApi(row.jPid, row.jName)
  if (res) {
    const { code } = res.data
    if (code === 1) {
      ElMessage.success('操作成功!')
      getList()
    } else {
      ElMessage.error('操作失败!')
    }
  }
}

/** 带下级运行 */
const runCData = async (row: TableData) => {
  const res = await runCDataApi(row.jPid, row.jName)
  if (res) {
    const { code } = res.data
    if (code === 1) {
      ElMessage.success('操作成功!')
      getList()
    } else {
      ElMessage.error('操作失败!')
    }
  }
}

/** 监控 */
const monitorData = (row?: any) => {
  console.log(row)
  push(`/job-manage/JobMonitor`)
}

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

const disabled = ref(true)

const onSelectionChange = (selection: any[]) => {
  disabled.value = selection.length === 0
}
</script>

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

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
      @refresh="refresh"
      @selection-change="onSelectionChange"
    >
      <template #buttons>
        <Upload :url="importExcelApiUrl" :callback="getList">
          <ElButton type="primary">导入</ElButton>
        </Upload>
        <ElButton type="primary" @click="exportExcel()">导出</ElButton>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />

    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />

    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
