<script lang="ts" setup name="AreaSelectTree">
import { defineExpose, reactive, ref } from 'vue'
import type { IlistQuerySelectTree } from './area-interface'
import { getAreaTree } from '@/api/system/area'

const emits = defineEmits(['selectDone'])
const dialogFormVisible = ref(false)
const tree = ref(null) as any
const defaultProps = {
  label: 'name',
  children: 'children',
  isLeaf: 'leaf',
}
const listQuery: IlistQuerySelectTree = reactive({
  pid: '',
})

// 初始化对话框
const initDialog = () => {
  dialogFormVisible.value = true
}
defineExpose({
  initDialog,
})

// 加载数据
const loadNode = (node: any, resolve: any) => {
  if (node.data && node.data.id) {
    listQuery.pid = node.data.id
  }
  getAreaTree(listQuery).then((response) => {
    const data = response.data
    resolve(data)
  })
}

// 确认选择后的操作，传给父组件并关闭弹窗
const confirmSelect = () => {
  const node = tree.value.getCurrentNode()
  dialogFormVisible.value = false
  emits('selectDone', node)
}
const cancel = () => {
  dialogFormVisible.value = false
}
</script>

<template>
  <el-dialog v-model="dialogFormVisible" custom-class="area-select-dialog" title="选择区域" append-to-body>
    <el-scrollbar style="height: 400px;">
      <el-tree
        ref="tree"
        :expand-on-click-node="false"
        :props="defaultProps"
        :load="loadNode"
        node-key="id"
        lazy
      />
    </el-scrollbar>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="confirmSelect">
          确定
        </el-button>
        <el-button @click="cancel">
          取消
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss">
  .area-select-dialog {
    width: 400px;
  }
</style>
