<template>
    <Modal v-model="showFormModal" :footer-hide="true">
        <template #header>
            <Space>
                <span>上传图片配置（configuration for uploading image）</span>
                <Poptip placement="bottom" width="400" word-wrap>
                    <Button type="info" shape="circle" size="small" icon="md-help"></Button>
                    <template #content>
                        <Typography>
                            <blockquote>
                                假设已经拥有一个图片上传的 HTTP 接口。该接口:
                                <ul>
                                    <li>接收<code>Content-Type: multipart/form-data</code>数据</li>
                                    <li>能够通过<code>response.url</code>得到上传成功的图片 URL</li>
                                </ul>
                            </blockquote>
                            <Title :level="6">API（必填）</Title>
                            <Paragraph>
                                后端接口的 URL。示例 https://api.example.com/upload
                            </Paragraph>
                            <Title :level="6">Field（必选）</Title>
                            <Paragraph>
                                上传图片时，该图片文件在 form-data 中的字段名
                            </Paragraph>
                            <Title :level="6">More Fields（可选）</Title>
                            <Paragraph>
                                其他附带字段名，比如 token，可用于辅助鉴权
                            </Paragraph>
                        </Typography>
                    </template>
                </Poptip>
            </Space>
        </template>
        <Form ref="uploadImgFormRef" :model="configForm" :label-width="80" style="width: 300px">
            <FormItem label="API" prop="uploadImgAPI" required>
                <Tooltip content="上传图片的后端 API 接口" placement="top" max-width="300">
                    <Input type="text" v-model="configForm.uploadImgAPI"
                        placeholder="example: https://api.example.com/upload" style="width: 290px;"></Input>
                </Tooltip>
            </FormItem>
            <FormItem label="Field" prop="uploadImgField" required>
                <Tooltip content="上传图片时，该图片文件在 form-data 中的字段名" placement="top" max-width="300">
                    <Input type="text" v-model="configForm.uploadImgField"
                        placeholder="File Field. example: image or file ..." style="width: 290px;"></Input>
                </Tooltip>
            </FormItem>
            <FormItem v-for="(field, index) in configForm.otherField" :key="index" :label="'Field ' + (index + 1)"
                :prop="'otherField.' + index + '.key'"
                :rules="{ required: true, message: 'Field Key can not be empty', trigger: 'blur' }">
                <Space>
                    <Tooltip content="其他附带字段名，比如 token，可用于辅助鉴权" placement="top" max-width="300">
                        <Input type="text" v-model="field.key" placeholder="Field Key" style="width: 80px;"></Input>
                    </Tooltip>
                    <Input type="text" v-model="field.value" placeholder="Field Value" style="width: 200px;"></Input>
                    <Button @click="removeField(index)">Delete</Button>
                </Space>
            </FormItem>
            <FormItem>
                <Button type="dashed" long @click="addField()" icon="md-add">Add More Field</Button>
            </FormItem>
            <FormItem>
                <Button type="primary" @click="handleSubmit()">Submit</Button>
                <Button @click="handleReset()" style="margin-left: 8px">Reset</Button>
            </FormItem>
        </Form>
    </Modal>
</template>

<script setup>
import { ref, reactive, watch, useTemplateRef } from "vue";

const props = defineProps({
    visible: {
        type: Boolean,
        required: true,
        default: false,
    },
    uploadImgAPI: {
        type: String,
        required: true,
        default: '',
    },
    uploadImgField: {
        type: String,
        required: true,
        default: '',
    },
    // 示例 [{ key: 'token', value: 'uuid' }]
    otherField: {
        type: Array,
        required: true,
        default: [],
    },
});

const emit = defineEmits([
    'update:visible',
    'update:uploadImgAPI',
    'update:uploadImgField',
    'update:otherField',
]);

const uploadImgFormRef = useTemplateRef('uploadImgFormRef');

// 是否弹出对话框。要求双向绑定
const showFormModal = ref(props.visible);
watch(() => props.visible, (visible) => {
    showFormModal.value = visible;
})
watch(showFormModal, (visible) => {
    emit('update:visible', visible);
})

const configForm = reactive({
    // 上传图片的后端 API 接口
    uploadImgAPI: props.uploadImgAPI,
    // 上传图片时，FormData 的文件字段
    uploadImgField: props.uploadImgField,
    // 上传图片时，FormData 里附带的其他字段和数值
    otherField: JSON.parse(JSON.stringify(props.otherField)),
});

const addField = () => {
    configForm.otherField.push({ key: '', value: '' });
};

const removeField = (index) => {
    configForm.otherField.splice(index, 1)
};

const handleSubmit = () => {
    uploadImgFormRef.value.validate((valid) => {
        if (valid) {
            emit('update:uploadImgAPI', configForm.uploadImgAPI);
            emit('update:uploadImgField', configForm.uploadImgField);
            emit('update:otherField', JSON.parse(JSON.stringify(configForm.otherField)));
            showFormModal.value = false;
        }
    })
};

const handleReset = () => {
    uploadImgFormRef.value.resetFields();
};
</script>
