<template>
    <el-dialog v-model="props.mirrorDialog" :title="title" width="30%" :before-close="handleClose">
        <el-form ref="formRef" :model="formData" label-width="100px" :rules="rules">
            <el-form-item prop="name" label="镜像名">
                <el-input v-model="formData.name" placeholder="请输入镜像名" @blur="handleBlur" />
            </el-form-item>
            <el-form-item prop="contextPath" label="服务路径">
                <el-input v-model="formData.contextPath" placeholder="请输入服务路径" />
            </el-form-item>
            <el-form-item prop="version" label="版本">
                <el-select v-model="formData.id" :disabled="!versionList" placeholder="请填写对应镜像名选择版本"
                    @change="handleChange">
                    <el-option v-for="item in versionList" :key="item.id" :label="item.version" :value="item.id" />
                </el-select>
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="onConfirm">确定</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang='ts'>
import { ref } from 'vue'
import { getImageService, getImageVersion } from '@/services/api/imageService/index';

const props = defineProps({
    mirrorDialog: {
        type: Boolean,
        require: true
    }
})

const emits = defineEmits(['update:mirrorDialog', 'mirrorData'])

const formData = ref({
    id: '',
    name: '',
    contextPath: '',
    version: '',
})

const versionList = ref([]) as any

const formRef = ref()
const title = ref('新增服务镜像')

const rules = ref({
    name: [{ required: true, message: '请输入镜像名', trigger: 'blur' }],
    // contextPath: [{ required: true, message: '请输入服务路径', trigger: 'blur' }],
})

const handleBlur = async () => {
    if (formData.value.name) {
        const res: any = await getImageService({ name: formData.value.name })
        if (res.code === 200 && res.data.records.length !== 0) {
            const imageId = res.data.records[0].id
            const ver: any = await getImageVersion({ imageId })
            console.log(ver);
            if (ver.code === 200) versionList.value = ver.data
        }
    }
}

const handleChange = (e: any) => {
    versionList.value.map((item: any) => {
        if (item.id == e) {
            formData.value.version = item.version
        }
    })
}

const handleClose = () => {
    formRef.value?.resetFields()
    formData.value = {
        id: '',
        name: '',
        contextPath: '',
        version: '',
    }
    emits('update:mirrorDialog', false)
}

const onConfirm = () => {
    formRef.value?.validate((valid: Boolean, fields: any) => {
        if (valid) {
            emits('mirrorData', formData.value)
        } else {
            console.log('error submit!', fields)
        }
    })
}

defineExpose({
    formData,
    title
})
</script>
 
<style lang = "scss" scoped>
</style>