<template>
    <hc-new-dialog v-model="isShow" title="租户数据源配置" widths="400px" is-footer-center @close="dialogClose">
        <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="left" label-width="auto">
            <el-form-item label="数据源：" prop="datasourceId">
                <el-select v-model="formModel.datasourceId" placeholder="请选择数据源" filterable block>
                    <el-option v-for="item in sourceList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button hc-btn @click="dialogClose">取消</el-button>
            <el-button hc-btn type="primary" :loading="submitLoading" @click="dialogSubmit">提交</el-button>
        </template>
    </hc-new-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { deepClone, getArrValue } from 'js-fast-way'
import mainApi from '~api/system/tenant'
import { get } from '~api'

const props = defineProps({
    info: {
        type: Object,
        default: () => ({}),
    },
})

//事件
const emit = defineEmits(['finish'])

//双向绑定
// eslint-disable-next-line no-undef
const isShow = defineModel('modelValue', {
    default: false,
})

//监听可否编辑
const dataInfo = ref(props.info)
watch(() => props.info, (data) => {
    dataInfo.value = data
}, { immediate: true, deep: true })

//监听显示
watch(isShow, (val) => {
    if (val) {
        initFormData()
    }
})

//菜单表单
const formRef = ref(null)
const formModel = ref({})
const formRules = {
    datasourceId: [{ required: true, message: '请选择数据源', trigger: 'change' }],
}

//初始化表单
const sourceList = ref([])
const initFormData = async () => {
    submitLoading.value = false
    formModel.value = deepClone(dataInfo.value)
    //获取数据源列表
    const { data } = await get({
        url: '/api/blade-develop/datasource/select',
    })
    sourceList.value = getArrValue(data)
}

//提交表单
const submitLoading = ref(false)
const dialogSubmit = async () => {
    submitLoading.value = true
    const { error, code, msg } = await mainApi.datasource(formModel.value)
    if (!error && code === 200) {
        submitLoading.value = false
        window?.$message?.success('操作成功')
        emit('finish')
        dialogClose()
    } else {
        window?.$message?.error(msg ?? '操作失败')
    }
}

//关闭弹窗
const dialogClose = () => {
    isShow.value = false
    submitLoading.value = false
    formModel.value = {}
}
</script>
