<template>
    <div class="sc-material-image">
        <el-image
            v-if="isImage && modelValue"
            :src="modelValue"
            :preview-src-list="[modelValue]"
            fit="cover"
            class="sc-material-image__preview"
            preview-teleported
        />
        <video
            v-else-if="!isImage && modelValue"
            :src="modelValue"
            class="sc-material-image__preview sc-material-image__video"
            controls
        />
        <sc-material-picker
            :model-value="modelValue"
            :multiple="false"
            :lock-file-type="fileType"
            value-type="url"
            :title="pickerTitle"
            :button-text="buttonTextResolved"
            @update:model-value="onPick"
        />
        <el-input
            v-if="showInput"
            :model-value="modelValue"
            :placeholder="inputPlaceholder"
            clearable
            class="sc-material-image__input"
            @update:model-value="onPick"
        />
    </div>
</template>

<script>
export default {
    name: "ScMaterialImage",
    props: {
        modelValue: { type: String, default: "" },
        /** 1 图片 2 视频 */
        fileType: { type: String, default: "1" },
        title: { type: String, default: "" },
        buttonText: { type: String, default: "" },
        showInput: { type: Boolean, default: true },
        inputPlaceholder: { type: String, default: "或填写图片地址" },
    },
    emits: ["update:modelValue", "change"],
    computed: {
        isImage() {
            return String(this.fileType) !== "2";
        },
        pickerTitle() {
            if (this.title) return this.title;
            return this.isImage ? "选择图片" : "选择视频";
        },
        buttonTextResolved() {
            if (this.buttonText) return this.buttonText;
            return this.isImage ? "选择图片" : "选择视频";
        },
    },
    methods: {
        onPick(val) {
            const url = val == null ? "" : String(val);
            this.$emit("update:modelValue", url);
            this.$emit("change", url);
        },
    },
};
</script>

<style scoped>
.sc-material-image {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
    width: 100%;
}
.sc-material-image__preview {
    width: 120px;
    height: 120px;
    border-radius: 4px;
    border: 1px solid var(--el-border-color-lighter);
}
.sc-material-image__video {
    object-fit: contain;
    background: #000;
}
.sc-material-image__input {
    max-width: 360px;
    width: 100%;
}
</style>
