<script setup>
    import { onMounted, onUnmounted, ref } from 'vue';
    import { REQUEST_UPLOAD_FILE } from '@/config/urls';
    import auth from '@/utils/auth';
    // import { storeToRefs } from 'pinia';
    import { useMediaStore } from '@/stores';
    import { MessagePlugin } from 'tdesign-vue-next';
    import eventBus from '@/utils/eventBus';

    const mediaStore = useMediaStore();
    const { getMediaList, createMedia, deleteMedia } = mediaStore;

    const sortieId = ref();
    const visible = ref(false);

    const files = ref([]);
    function init() {
        if (!sortieId.value) return;
        getMediaList(sortieId.value).then(({ data }) => {
            (data || []).forEach(item => {
                const temp = item;
                temp.status = 'success';
                temp.raw = {};
            });
            files.value = [...(data || []), ...files.value];
        }).catch(({ message }) => {
            if (message) MessagePlugin.error(message);
        });
    }

    const mediaList = ref([]);
    function loadList() {
        if (!sortieId.value) return;
        getMediaList(sortieId.value).then(({ data }) => {
            mediaList.value = [...(data || [])];
        }).catch(({ message }) => {
            if (message) MessagePlugin.error(message);
        });
    }

    function onCancel() {
        files.value = [];
        mediaList.value = [];
    }

    const subject = ref('image');

    const ABRIDGE_NAME = [10, 7];

    const formatResponse = (res) => {
        if (!res) {
            return { status: 'fail', error: '上传失败，原因：文件过大或网络不通' };
        }
        return res;
    };

    function beforeUpload(UploadFile) {
        const { type = 'image' } = UploadFile || {};
        if (type.includes('image')) {
            subject.value = 'image';
        }
        if (type.includes('video')) {
            subject.value = 'video';
        }
        return true;
    }

    const handleSuccess = ({ currentFiles = [], response = [] } = {}) => {
        console.log('aaa', currentFiles, response);
        const medias = currentFiles.map(({ name, size, type, status, response: { code, data } }) => {
            if (status !== 'success') return null;
            if (code !== 200) return null;
            let typeInt;
            if (type.includes('image')) {
                typeInt = 1;
            }
            if (type.includes('video')) {
                typeInt = 2;
            }
            return {
                name,
                size,
                type: typeInt,
                url: data,
            };
        }).filter(Boolean);
        // const { name, size, type } = currentFiles[0] || {};
        // const { code, data } = response[0] || {};
        // if (code !== 200) return;
        // let typeInt;
        // if (type.includes('image')) {
        //     typeInt = 1;
        // }
        // if (type.includes('video')) {
        //     typeInt = 2;
        // }
        const formData = {
            id: sortieId.value,
            medias,
        };
        createMedia(formData).then(() => {
            if (!visible.value) return;
            loadList();
        }).catch(({ message }) => {
            if (message) MessagePlugin.error(message);
        });
    };

    const handleRemove = ({ file } = {}) => {
        if (file.status !== 'success') return;
        let mediaId;

        if (file.id) {
            mediaId = file.id;
        } else {
            const { response: { data } } = file;
            const media = mediaList.value.find(({ url }) => url === data);
            mediaId = media?.id;
        }

        if (!mediaId) return;
        deleteMedia(mediaId).catch(({ message }) => {
            if (message) MessagePlugin.error(message);
        });
    };

    onMounted(() => {
        eventBus.on('show-media-manage', (row) => {
            if (!row.id) return;
            sortieId.value = row.id;
            init();
            visible.value = true;
        });
    });

    onUnmounted(() => {
        eventBus.off('show-media-manage');
    });
</script>

<template>
    <t-dialog
        :class="s.root"
        v-model:visible="visible"
        width="fit-content"
        :footer="null"
        @closed="onCancel"
    >
        <template #header>
            <div style="flex: 1; text-align: center;">媒体管理</div>
        </template>

        <t-upload
            v-model="files"
            placeholder="支持上传图片、视频文件"
            :action="REQUEST_UPLOAD_FILE(subject)"
            :headers="{
                Authorization: `Bearer ${auth.getToken()}`,
            }"
            theme="file-flow"
            multiple
            :abridge-name="ABRIDGE_NAME"
            auto-upload
            show-thumbnail
            allow-upload-duplicate-file
            :format-response="formatResponse"
            :before-upload="beforeUpload"
            @success="handleSuccess"
            @remove="handleRemove"
        />
    </t-dialog>
</template>

<style lang="less" module="s">
    .root {
        //
    }
</style>
