<template>
    <ele-page flex-table>
        <ele-card flex-table header="营销素材">
            <div class="flex">
                <FileGroup
                    :selected-id="searchParams.sourceCate"
                    :source-type="searchParams.sourceType"
                    @groupSelect="handleGroupSelect"
                />
                <div
                    class="flex-1 ml-4"
                    v-loading="loading"
                    element-loading-text="上传中..."
                >
                    <div class="flex items-center">
                        <el-button
                            type="primary"
                            v-permission="'marketing:material:download'"
                            @click="handleDownload"
                            >下载图片</el-button
                        >
                        <el-button
                            type="danger"
                            @click="handleDelete"
                            v-permission="'marketing:material:delete'"
                            >删除图片</el-button
                        >
                        <el-button
                            type="danger"
                            @click="handleDelete"
                            v-permission="'marketing:material:batchDelete'"
                            >批量删除</el-button
                        >

                        <el-input
                            v-model="searchParams.sourceNameLike"
                            placeholder="请输入图片名称"
                            style="width: 200px; margin: 0 14px 0 30px"
                        />
                        <el-button
                            type="primary"
                            @click="getImageList"
                            style="width: 90px"
                            >查询</el-button
                        >
                        <el-button
                            plain
                            type="primary"
                            @click="handleReset"
                            style="width: 90px"
                            >重置</el-button
                        >
                    </div>

                    <el-checkbox-group
                        style="height: calc(100vh - 270px)"
                        v-model="checkList"
                        class="flex flex-wrap items-start content-start overflow-auto"
                        @change="handlecheckboxChange"
                    >
                        <el-upload
                            ref="uploadRef"
                            v-model:file-list="form.images"
                            list-type="picture-card"
                            :show-file-list="false"
                            multiple
                            accept="image/*"
                            :http-request="uploadFile"
                            style="margin-right: 14px; margin-top: 12px"
                        >
                            <div class="flex flex-col items-center">
                                <el-icon :size="24"><Plus /></el-icon>
                                <el-text type="info" style="margin-top: 20px"
                                    >上传图片</el-text
                                >
                            </div>
                        </el-upload>
                        <div
                            class="pos-relative default-image-item"
                            v-for="(item, index) in imageList"
                            :key="index"
                        >
                            <el-checkbox
                                :value="item.id"
                                class="checkbox-item"
                            />
                            <el-image
                                style="
                                    width: 146px;
                                    height: 146px;
                                    border-radius: 6px;
                                "
                                :src="item.sourceUrl"
                                fit="cover"
                            />

                            <div class="mask-error">
                                <span>{{ item.sourceName }}</span>
                            </div>
                        </div>
                    </el-checkbox-group>

                    <ele-pagination
                        v-model:current-page="pageParams.pageNum"
                        v-model:page-size="pageParams.pageSize"
                        :total="total"
                        layout="total,prev, pager, next, sizes, jumper"
                        @update:currentPage="handleCurrentChange"
                        @update:pageSize="handlePageSizeChange"
                    />
                </div>
            </div>
        </ele-card>
    </ele-page>
</template>

<script setup>
    import { ref, reactive, nextTick } from 'vue';
    import { Plus } from '@element-plus/icons-vue';
    import request from '@/utils/request';
    import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
    import FileGroup from './components/file-group.vue';

    const imageList = ref([]);
    const checkList = ref([]);
    const total = ref(0);
    const form = reactive({
        images: []
    });

    const searchParams = ref({
        sourceNameLike: '',
        sourceType: '1', //1图片 2视频
        sourceCate: '-1' //-1全部 1素材
    });
    const handleGroupSelect = (item) => {
        searchParams.value.sourceCate = item.id;
        getImageList(searchParams.value);
    };

    const pageParams = ref({ pageNum: 1, pageSize: 50 });
    const getImageList = (data = {}) => {
        request
            .get('/baseinfo/source/pagelist', {
                params: { ...pageParams.value, ...searchParams.value, ...data }
            })
            .then((res) => {
                if (res.data.code == 200) {
                    imageList.value = res.data.rows;
                    total.value = res.data.total || 0;
                }
            });
    };
    onMounted(() => {
        getImageList();
    });
    //重置
    const handleReset = () => {
        searchParams.value.sourceNameLike = '';
        getImageList();
    };

    //页码变化
    const handleCurrentChange = (val) => {
        pageParams.value.pageNum = val;
        getImageList();
    };
    //每页显示多少条
    const handlePageSizeChange = (val) => {
        pageParams.value.pageSize = val;
        getImageList();
    };

    //执行图片上传并新增到列表
    const loading = ref(false);
    function uploadFile(file) {
        loading.value = true;
        let formData = new FormData();
        formData.append('file', file.file);
        request
            .post('/common/upload', formData, { showTips: false })
            .then((res) => {
                if (res.data.code == 200) {
                    handleAddImage(res.data, file.name);
                }
            })
            .finally(() => {
                loading.value = false;
            });
    }
    //添加图片
    const handleAddImage = (res, name) => {
        let params = {
            sourceUrl: res.url,
            sourceName: name,
            sourceType: searchParams.value.sourceType,
            sourceCate: searchParams.value.sourceCate
        };
        request.post('/baseinfo/source/add', params).then((res) => {
            if (res.data.code == 200) {
                getImageList();
            }
        });
    };

    //选中图片
    const handlecheckboxChange = (value) => {
        //单选
        // let last = value[value.length - 1];
        // checkList.value = [last];
        //多选
        checkList.value = value;
    };

    //删除图片
    const handleDelete = () => {
        if (checkList.value.length == 0) {
            ElMessage({ type: 'warning', message: '请选择图片' });
            return;
        }
        ElMessageBox.confirm('是否删除选中的图片？', '提示').then(() => {
            request
                .post('/baseinfo/source/deleteBatch', {
                    idList: checkList.value
                })
                .then((res) => {
                    if (res.data.code == 200) {
                        ElMessage({ type: 'success', message: '删除成功' });
                        getImageList();
                    }
                });
        });
    };
    //下载图片
    const handleDownload = () => {
        if (checkList.value.length == 0) {
            ElMessage({ type: 'warning', message: '请选择图片' });
            return;
        }
        // Find the selected image from the imageList
        const selectedImage = imageList.value.find(
            (img) => img.id === checkList.value[0]
        );
        if (selectedImage) {
            window.open(selectedImage.sourceUrl);
        }
    };
</script>

<style lang="scss" scoped>
    .default-image-item {
        margin-right: 14px;
        margin-top: 14px;
        margin-bottom: 0;
        position: relative;
        border-radius: 6px;
        border: 1px solid #e4e7ed;
        &:hover {
            .checkbox-item {
                opacity: 1;
            }
        }
        .checkbox-item {
            position: absolute;
            top: -8px;
            left: 0;
            opacity: 0;
            &.is-checked {
                opacity: 1;
            }
        }
        .mask-error {
            width: 100%;
            height: 30px;
            background-color: rgba(0, 0, 0, 0.2);
            position: absolute;
            bottom: 0;
            left: 0;
            color: #fff;
            padding: 0 5px;
            box-sizing: border-box;
            display: flex;
            align-items: center;
            justify-content: center;
            border-bottom-left-radius: 6px;
            border-bottom-right-radius: 6px;

            span {
                width: 100%;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                text-align: center;
                font-size: 12px;
                font-weight: 500;
            }
        }
    }
</style>
