<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :pagination="false"
      :columns="columns"
      row-key="id"
      :request-api="listAircraftApi"
      :init-param="initParam"
      :data-callback="dataCallback"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" v-auth="['als:aircraft:add']" icon="CirclePlus" @click="openDialog(1, '机型机号新增')"> 新增 </el-button>
        <el-button type="primary" v-auth="['als:aircraft:import']" icon="Upload" plain @click="batchAdd"> 导入 </el-button>
        <el-button type="primary" v-auth="['als:aircraft:export']" icon="Download" plain @click="downloadFile"> 导出 </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link icon="EditPen" v-auth="['als:aircraft:edit']" @click="openDialog(2, '机型机号编辑', scope.row)">
          编辑
        </el-button>
        <el-button type="primary" link v-auth="['als:aircraft:add']" icon="CirclePlus" @click="openDialog(4, '机型机号新增', scope.row)">
          新增
        </el-button>
        <el-button type="primary" link icon="Delete" v-auth="['als:aircraft:remove']" @click="deleteAircraft(scope.row)"> 删除 </el-button>
      </template>
    </ProTable>
    <FormDialog ref="formDialogRef" :items-options="itemsOptions" :model="model" />
    <ImportExcel ref="dialogRef" />
    <TaskDialog ref="taskDialogRef" />
  </div>
</template>

<script setup lang="tsx" name="Aircraft">
import { ElMessageBox } from 'element-plus'
import { useHandleData } from '@/hooks/useHandleData'
import ImportExcel from '@/components/ImportExcel/index.vue'
import TaskDialog from '@/components/TaskDialog/index.vue'
import FormDialog from '@/components/FormDialog/index.vue'
import { ProTableInstance, ColumnProps } from '@/components/ProTable/interface'
import { handleTree } from '@/utils/common'
import {
  listAircraftApi,
  delAircraftApi,
  addAircraftApi,
  updateAircraftApi,
  importTemplateApi,
  importAircraftDataApi,
  exportAircraftApi,
  getAircraftApi
} from '@/api/modules/als/aircraft'
// ProTable 实例
const proTable = ref<ProTableInstance>()
// 表单model
const model = ref({})
// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({})
const aircraftOptions = ref<any[]>([])
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，可以在这里进行处理成这些字段
const dataCallback = (res: any) => {
  const data = handleTree(res, 'id')
  aircraftOptions.value = Object.assign([], data)
  aircraftOptions.value.push({ id: 0, name: '顶层', children: null })
  setItemsOptions()
  return data
}

// 删除机型机号信息
const deleteAircraft = async (params: any) => {
  await useHandleData(delAircraftApi, params.id, '删除【' + params.name + '】机型机号')
  proTable.value?.getTableList()
}

const taskDialogRef = ref<InstanceType<typeof TaskDialog> | null>(null)
// 导出机型机号列表
const downloadFile = async () => {
  ElMessageBox.confirm('确认导出机型机号数据?', '温馨提示', { type: 'warning' }).then(async () => {
    exportAircraftApi(proTable.value?.searchParam)
    taskDialogRef.value?.openExportDialog()
  })
}

// 批量添加机型机号
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null)
const batchAdd = () => {
  const params = {
    title: '机型机号',
    tempApi: importTemplateApi,
    importApi: importAircraftDataApi,
    getTableList: proTable.value?.getTableList
  }
  dialogRef.value?.acceptParams(params)
}

const formDialogRef = ref<InstanceType<typeof FormDialog> | null>(null)
// 打开弹框的功能
const openDialog = async (type: number, title: string, row?: any) => {
  let res = { data: {} }
  if (row?.id) {
    res = await getAircraftApi(row?.id || null)
  }
  // 重置表单项
  setItemsOptions()
  if (row?.parentId == 0 && type == 2) {
    itemsOptions.splice(0, 1)
  }
  // 增加子节点
  if (type == 4) {
    res.data = {
      parentId: row?.id
    }
  }
  model.value = type == 1 ? {} : res.data
  const params = {
    title,
    width: 580,
    isEdit: type !== 3,
    api: [1, 4].includes(type) ? addAircraftApi : updateAircraftApi,
    getTableList: proTable.value?.getTableList
  }
  formDialogRef.value?.openDialog(params)
}

// 表格配置项
const columns = reactive<ColumnProps<any>[]>([
  {
    prop: 'name',
    label: '机型/机号',
    align: 'left',
    search: {
      el: 'input'
    }
  },
  {
    prop: 'orderNum',
    label: '显示顺序'
  },
  {
    prop: 'createByName',
    label: '创建人'
  },
  {
    prop: 'createTime',
    label: '创建时间'
  },
  {
    prop: 'updateByName',
    label: '更新人'
  },
  {
    prop: 'updateTime',
    label: '更新时间'
  },
  { prop: 'operation', label: '操作' }
])
// 表单配置项
let itemsOptions = reactive<ProForm.ItemsOptions[]>([])
const setItemsOptions = () => {
  itemsOptions = [
    {
      label: '机型Id',
      prop: 'parentId',
      rules: [{ required: true, message: '机型Id不能为空', trigger: 'blur' }],
      compOptions: {
        elTagName: 'tree-select',
        enum: aircraftOptions.value,
        valueKey: 'id',
        checkStrictly: true,
        props: {
          value: 'id',
          label: 'name'
        },
        placeholder: '请选择机型Id'
      }
    },
    {
      label: '机型/机号',
      prop: 'name',
      rules: [{ required: true, message: '机型/机号不能为空', trigger: 'blur' }],
      compOptions: {
        placeholder: '请输入机型/机号'
      }
    },
    {
      label: '显示顺序',
      prop: 'orderNum',
      rules: [{ required: true, message: '显示顺序不能为空', trigger: 'blur' }],
      compOptions: {
        elTagName: 'input-number'
      }
    }
  ]
}
</script>
