<script setup>
import XImage from "../../../components/XImage/Index.vue";
import {reactive, ref, watch} from "vue";
import Api from "../../../api/index.js";
import UploadButton from "../../../components/upload/UploadButton.vue";
import {Message} from "@arco-design/web-vue";

const {id} = defineProps({
    id: {
        type: Number,
        default: null,
    }
});
const visible = ref(false);
const materialList = reactive([]);
const getMaterialList = async () => {
    const {data} = await Api.merchant.getMaterialList(id);
    materialList.length = 0;
    materialList.push(...data);
}

watch(
    () => visible.value,
    (val) => {
        if (val) getMaterialList();
    },
    {deep: true}
)

const uploadSuccess = async (url) => {
    const {msg} = await Api.merchant.addMaterial({
        id: id,
        image: url
    });
    Message.success(msg);
    await getMaterialList();
}

const deleteImage = async (id) => {
    const {msg} = await Api.merchant.delMaterial(id);
    Message.success(msg);
    await getMaterialList();
}
</script>

<template>
    <!-- 素材库 -->
    <a-button v-if="!$slots.default" type="primary" @click="visible=true">
        <template #icon>
            <icon-apps/>
        </template>
        素材库
    </a-button>
    <div @click="visible=true" v-else>
        <slot></slot>
    </div>

    <a-modal
        title-align="start"
        :width="820"
        v-model:visible="visible"
        title="素材库">
        <UploadButton :multiple="true" :api="Api.system.uploadFile2" @success="uploadSuccess">
            <template #upload-button>
                <a-button>
                    <template #icon>
                        <icon-plus/>
                    </template>
                    从本地添加到素材
                </a-button>
            </template>
        </UploadButton>

        <div class="box">
            <x-image
                @delete="deleteImage(v.id)"
                height="80px"
                width="80px"
                v-for="v in materialList"
                :key="v.id"
                :src="v.image">
            </x-image>
        </div>
    </a-modal>
</template>

<style scoped lang="scss">
.box {
    @apply p-[20px] mt-[20px] flex gap-[14px] flex-wrap;
    border: 1px solid #E5E6EB;
}
</style>
