<template>
  <el-dialog v-model="dialogVisible" :title="`${fxdyObj.label || ''} 绑定`">
    <div style="height: calc(84vh - 200px);overflow: auto;">
      <fxdyTree v-if="dialogVisible" ref="fxdyTreeRef" v-model="formData.fbRiskunitTreeId" @change="fxdyChange">
      </fxdyTree>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineExpose, defineEmits, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import { getApi, postApi } from "@/api/tobAcco_api.js";
import fxdyTree from './fxdyTree.vue';

const { proxy } = getCurrentInstance()

const emits = defineEmits(['close', 'ok'])
// const { KHLX } = proxy.$dict("KHLX");


const fxdyObj = ref({})
const currSelectObj = ref({})
// 表单数据
const formData = ref({
  dictCode: null,
  fbRiskunitTreeId: undefined,
})


const fxdyTreeRef = ref(null)
// 控制弹窗显示
const dialogVisible = ref(false)

// 提交表单并关闭弹窗
const submitForm = () => {

  if (currSelectObj.value?.children?.length > 0) {
    ElMessage({
      type: 'warning',
      message: '不可绑定父级！',
    })
    return
  }
  if (!formData.value.fbRiskunitTreeId) {
    ElMessage({
      type: 'warning',
      message: '请选择风险单元！',
    })
    return
  }
  const params = {
    dictCode: formData.value.dictCode,
    fbRiskunitTreeId: [formData.value.fbRiskunitTreeId],
    dictName: formData.value.dictName,
    fbName: currSelectObj.value?.name
  }

  postApi(params, `/mosty-jcgl/fxdy/dictBinding`).then(res => {
    ElMessage({
      type: 'success',
      message: '风险单元绑定成功！',
    })
    emits('ok')
    dialogVisible.value = false
  })
}

// 关闭前处理
const handleClose = () => {
  // 可以在这里添加关闭前的处理逻辑
  dialogVisible.value = false
  emits('close')
}

// 公开方法：打开弹窗
const open = (obj) => {

  fxdyObj.value = obj
  formData.value = {
    dictCode: obj.id,
    dictName: obj.label,
    fbRiskunitTreeId: undefined
  }
  dialogVisible.value = true
}
const fxdyChange = (obj) => {


  currSelectObj.value = obj
  // formData.value.level = obj.positionType
}

// 将打开弹窗的方法暴露给父组件
defineExpose({ open })
</script>

<style scoped>
.dialog-footer {
  text-align: center;
}
</style>
