<template>
    <vxe-modal v-model="show" :z-index="1006" @hide="onClose" :title="title" width="600" esc-closable mask-closable
        show-footer>
        <template #default>
            <el-form ref="formRef" :model="form" inline label-position="right">
                <template v-for="(item, index) in formColumn" :key="index">
                    <el-form-item v-if="!['id', '_X_ROW_KEY'].includes(item)" :label="item" :prop="item">
                        <el-input v-model="form[item]" placeholder="" clearable />
                    </el-form-item>
                </template>
            </el-form>
        </template>
        <template #footer>
            <el-button type="primary" @click="onSubmit">确认</el-button>
        </template>
    </vxe-modal>
</template>

<script lang="ts" setup name="InformationInfoDialog">
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { addInformationInfoApi, updateInformationInfoApi } from '@/api/customer'
import { ElMessage, type FormInstance } from 'element-plus'

const route = useRoute()

const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    },
    title: {
        type: String,
        default: "新增资料"
    },
    informationInfo: {
        type: Object,
        default: () => { }
    }
})

const emits = defineEmits(['onChange'])

const show = ref(false)
const formRef = ref<FormInstance>()
const formColumn = ref<any>([])
const form = ref<any>({})

watch(
    () => props.visible,
    (val) => {
        show.value = val
        formColumn.value = Object.keys(props.informationInfo)
        form.value = props.informationInfo
    }
)

const addInformationInfo = async () => {
    const params = {
        informationType: route.query.informationType,
        json: JSON.stringify(form.value)
    }
    const { data } = await addInformationInfoApi(params)
    if (data?.code == 200) {
        ElMessage.success(`${data?.message}`)
        emits('onChange', 'add')
    } else {
        ElMessage.error(`${data?.message}`)
    }
}

const updateInformationInfo = async () => {
    delete form.value['_X_ROW_KEY']
    const params = {
        informationType: route.query.informationType,
        json: JSON.stringify(form.value)
    }
    const { data } = await updateInformationInfoApi(params)
    if (data?.code == 200) {
        ElMessage.success(`${data?.message}`)
        emits('onChange', 'update')
    } else {
        ElMessage.error(`${data?.message}`)
    }
}

const onSubmit = () => {
    if (props.title == '新增资料') {
        addInformationInfo()
    } else {
        updateInformationInfo()
    }
}

const onClose = () => {
    emits('onChange', 'close')
}

</script>

<style lang="scss" scoped></style>