<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      row-key="id"
      :request-api="listSortieParameterApi"
      :init-param="initParam"
      :data-callback="dataCallback"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="Download" @click="openDialog(4, '在线下载')"> 在线下载 </el-button>
        <el-button type="primary" :icon="Download" @click="openDownDialog()"> 离线下载 </el-button>
        <!-- <UploadFile icon="Download"></UploadFile> -->
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" v-auth="['manage:dataDown:query']" @click="openDialog(3, '数据下载结果查看', scope.row)">
          查看
        </el-button>
        <el-button type="primary" link :icon="Delete" v-auth="['manage:deepIsolationModel:remove']" @click="deleteDataDown(scope.row)">
          删除
        </el-button>
      </template>
    </ProTable>
    <FormDialogOld ref="formDialogRef" />
    <FormDialog ref="downDialogRef" />
  </div>
</template>

<script setup lang="tsx" name="DataDownResult">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import ProTable from '@/components/ProTable/index.vue'
import { useHandleData } from '@/hooks/useHandleData'
import FormDialogOld from '@/components/DialogOld/form.vue'
import FormDialog from '@/components/FormDialog/index.vue'
import { ProTableInstance, ColumnProps } from '@/components/ProTable/interface'
import { Download, View, Delete } from '@element-plus/icons-vue'
import { listSortieParameterApi, getSortieParameterApi, delSortieParameterApi } from '@/api/modules/manage/sortieParameter'
import { listAircraftAllApi } from '@/api/modules/manage/aircraft'
import { getDictsApi } from '@/api/modules/system/dictData'
import { listSortieAllApi } from '@/api/modules/manage/sortie'
import { dataDownApi, dataUploadApi } from '@/api/modules/manage/dataDown'
// import { ElMessage } from 'element-plus'
const router = useRouter()
// 跳转详情页
const toDetail = (row: { sortieNo: any }) => {
  router.push({ path: `/manage/detail/index`, query: { sortieNo: row.sortieNo } })
}
// ProTable 实例
const proTable = ref<ProTableInstance>()

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 0 })

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，可以在这里进行处理成这些字段
const dataCallback = (data: any) => {
  const page = proTable.value!.pageable
  return {
    list: data.data,
    total: data.total,
    pageNum: page.pageNum,
    pageSize: page.pageSize
  }
}

// 删除下载结果信息
const deleteDataDown = async (params: any) => {
  await useHandleData(delSortieParameterApi, params.id, `删除【${params.id}】下载结果`)
  proTable.value?.getTableList()
}

const formDialogRef = ref<InstanceType<typeof FormDialogOld> | null>(null)
const sortieOptions = ref<any[]>([])
const sortie = async () => {
  const res = await listSortieAllApi({})
  sortieOptions.value = res.data
}
sortie()
// const aircraftOptions = ref<any[]>([])
// const aircraft = async () => {
//   const res = await listAircraftAllApi({})
//   aircraftOptions.value = res.data
// }
// aircraft()
// 打开弹框的功能
const openDialog = async (type: number, title: string, row?: any) => {
  let res = { data: {} }
  if (row?.id) {
    res = await getSortieParameterApi(row?.id || null)
  }
  // 在线数据下载
  if (type == 4) {
    setOnlineDownFieldList()
  } else if (type == 5) {
    setOfflineDownFieldList()
  } else {
    // 重置表单
    setFieldList()
  }
  const params = {
    title,
    width: 480,
    top: '30vh',
    labelWidth: 80,
    isEdit: type !== 3,
    fieldList: fieldList,
    model: type == 1 ? {} : res.data,
    getTableList: proTable.value?.getTableList
  }
  if ([4, 5].includes(type)) {
    params['api'] = dataDownApi
  }
  formDialogRef.value?.openDialog(params)
}
const downDialogRef = ref<InstanceType<typeof FormDialog> | null>(null)
// 打开弹框的功能
const openDownDialog = async () => {
  // 离线数据下载
  let model = {
    fileList: [],
    sortieNo: '',
    sourceType: '2'
  }
  setItemsOptions()
  const params = {
    title: '离线数据',
    width: 480,
    top: '30vh',
    labelWidth: 80,
    isEdit: true,
    itemsOptions: itemsOptions,
    model,
    api: dataUploadApi,
    getTableList: proTable.value?.getTableList
  }
  downDialogRef.value?.openDialog(params)
}

// 表格配置项
const columns = reactive<ColumnProps<any>[]>([
  { type: 'selection', fixed: 'left', width: 70 },
  {
    prop: 'batchNo',
    label: '批次号',
    search: {
      el: 'input'
    }
  },
  {
    prop: 'sortieNo',
    label: '架次号',
    search: {
      el: 'input'
    },
    render: scope => {
      return (
        <el-button type="primary" link onClick={() => toDetail(scope.row)}>
          {scope.row.sortieNo}
        </el-button>
      )
    }
  },
  {
    prop: 'source',
    label: '数据源',
    tag: true,
    enum: () => getDictsApi('data_source'),
    search: {
      el: 'select'
    },
    fieldNames: { label: 'dictLabel', value: 'dictValue' }
  },
  {
    prop: 'dataPath',
    label: '数据路径',
    search: {
      el: 'input'
    }
  },
  {
    prop: 'createTime',
    label: '创建时间'
  },
  { prop: 'operation', label: '操作', width: 230 }
])
// 表单配置项
let fieldList: Form.FieldItem[] = []
const setFieldList = () => {
  fieldList = [
    {
      label: '批次号',
      field: 'batchNo'
    },
    {
      label: '架次号',
      field: 'sortieNo'
    },
    {
      label: '数据源',
      field: 'source'
    },
    {
      label: '下载方式',
      field: 'type'
    },
    {
      label: '数据路径',
      field: 'dataPath'
    }
  ]
}
const enumData = [
  {
    label: '机载PHM',
    value: '1'
  },
  {
    label: '数链仿真系统',
    value: '0'
  }
]
// 在线下载表单项
const setOnlineDownFieldList = () => {
  fieldList = [
    {
      label: '数据源',
      field: 'sourceType',
      type: 'radio',
      enum: enumData,
      options: {
        labelKey: 'label',
        valueKey: 'value'
      }
    },
    {
      label: '架次',
      field: 'sortieNo',
      span: 20,
      enum: sortieOptions.value,
      type: 'select',
      clearable: true,
      options: {
        labelKey: 'sortieNumber',
        valueKey: 'sortieNumber',
        filterable: true,
        allowCreate: true
      },
      placeholder: '请选择架次'
    },
    {
      label: '机号',
      field: 'aircraftNumber',
      span: 20,
      enum: listAircraftAllApi,
      type: 'select',
      clearable: true,
      options: {
        labelKey: 'number',
        valueKey: 'number'
      },
      placeholder: '请选择架次'
    }
  ]
}
// 在线下载表单项
const setOfflineDownFieldList = () => {
  fieldList = [
    {
      label: '数据源',
      field: 'sourceType',
      type: 'radio',
      enum: enumData,
      options: {
        labelKey: 'label',
        valueKey: 'value'
      }
    },
    {
      label: '架次',
      field: 'sortie',
      enum: sortieOptions.value,
      type: 'select',
      clearable: true,
      options: {
        labelKey: 'sortieNumber',
        valueKey: 'sortieNumber',
        filterable: true,
        allowCreate: true
      },
      placeholder: '请选择架次'
    }
  ]
}

// 表单配置项
let itemsOptions: ProForm.ItemsOptions[] = []
const setItemsOptions = () => {
  itemsOptions = [
    {
      label: '文件上传',
      prop: 'fileList',
      rules: [{ required: true, message: '文件不能为空', trigger: 'blur' }],
      compOptions: {
        elTagName: 'file-upload'
      }
    },
    {
      label: '架次',
      prop: 'sortieNo',
      rules: [{ required: true, message: '架次不能为空', trigger: 'blur' }],
      compOptions: {
        elTagName: 'select',
        placeholder: '请选择架次',
        enum: sortieOptions.value,
        labelKey: 'sortieNumber',
        valueKey: 'sortieNumber',
        filterable: true,
        allowCreate: true
      }
    },
    {
      label: '备注',
      prop: 'remark',
      compOptions: {
        type: 'textarea',
        placeholder: '请输入内容'
      }
    }
  ]
}
</script>
