<template>
  <el-dialog
    v-model="dialogVisible"
    :close-on-click-modal="false"
    :title="parameter.title"
    :destroy-on-close="true"
    :width="parameter.width"
    :top="parameter.top"
    draggable
  >
    <ProTable
      ref="proTable"
      height="50vh"
      :tool-button="parameter.toolButton"
      :columns="parameter.columns"
      row-key="roleId"
      :request-api="parameter.getTableList"
      :init-param="initParam"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" :loading="butLoading" @click="handleSubmit">确认</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="FormDialog">
import { ref, reactive } from 'vue'
import ProTable from '@/components/ProTable/index.vue'
import { ElMessage } from 'element-plus'
import { ProTableInstance, ColumnProps } from '@/components/ProTable/interface'

export interface TableParameterProps {
  title?: string // 标题
  width?: number // 弹框宽度
  top?: string // 离顶部距离
  toolButton?: boolean
  api?: (params: any) => Promise<any> // 表单提交api
  columns?: ColumnProps[] // 动态表单字段
  getTableList?: (params: any) => Promise<any> // 获取表格数据的Api
  backTableList?: (params: any) => Promise<any> // 返回主表表格数据的Api
}
// dialog状态
const dialogVisible = ref(false)
const butLoading = ref(false)

// 接受父组件参数，配置默认值
// const parameter = ref<TableParameterProps>({
//   title: '',
//   width: 600,
//   top: '5vh',
//   toolButton: false,
//   columns: [] as ColumnProps[]
// })
let parameter = withDefaults(defineProps<TableParameterProps>(), {
  title: '',
  width: 600,
  top: '5vh',
  toolButton: false,
  columns: () => []
})
// ProTable 实例
const proTable = ref<ProTableInstance>()

const initParam = reactive({ deptId: '' })
// 定义 emit 事件
const emit = defineEmits<{
  submitForm: []
}>()
// 表单提交校验
const handleSubmit = () => {
  butLoading.value = true
  let tableNames: any[] | undefined = proTable.value?.selectedList.map(item => item.tableName)
  parameter.api!(tableNames).then(res => {
    if (res.code == 200) {
      ElMessage.success('操作成功')
      dialogVisible.value = false
      emit('submitForm')
    } else {
      console.log('message', res.message)
    }
  })
  butLoading.value = false
}

// 取消按钮，重置表单，关闭弹框
const handleCancel = () => {
  butLoading.value = false
  dialogVisible.value = false
}

// 接收父组件参数
const openDialog = (params: TableParameterProps) => {
  parameter = { ...parameter, ...params }
  butLoading.value = false
  dialogVisible.value = true
}

defineExpose({
  openDialog
})
</script>
<style scoped lang="scss"></style>
