
<template>
    <div class="app-container">
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-upload :show-file-list="false" class="upload-demo" with-credentials :headers="{
                    'Authorization': 'Bearer ' + token
                }" action="https://xxgl.zzxcx.net/stage-api/file/info" :data="{
    id: priceId,
    type: type

}" :on-preview="handlePreview" :on-success="handleSuccess" :on-remove="handleRemove" :before-remove="beforeRemove"
                    multiple :on-exceed="handleExceed" :file-list="fileList">
                    <el-button size="small" type="primary">点击上传</el-button>

                </el-upload>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" v-hasPermi="['price:gallery:remove']" icon="el-icon-delete" size="mini"
                    :disabled="multiple" @click="handleDelete">删除</el-button>
            </el-col>

            <right-toolbar :showSearch.sync="showSearch" @queryTable="getFileList"></right-toolbar>
        </el-row>
        <el-table @selection-change="handleSelectionChange" :data="tableData" style="width: 100%">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <!-- <el-table-column prop="fileId" label="文件id"> -->
            <!-- </el-table-column> -->
            <el-table-column align="center" prop="fileUrl" label="文件缩略图">
                <template slot-scope="scope">
                    <div style="width:250px;margin: auto;">

                        <el-image v-if="getFileType(scope.row) == 'image'" :src="scope.row.fileUrl"
                            :preview-src-list="[scope.row.fileUrl]"></el-image>
                        <video preload="metadata" style="object-fit:contain;width: 100%;"
                            v-else-if="getFileType(scope.row) == 'video'" controls :src="scope.row.fileUrl"></video>
                        <span v-else>不支持预览的文件格式</span>
                    </div>

                </template>

            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">

                    <el-button size="mini" type="text" icon="el-icon-download"
                        @click="handleDownload(scope.row)">下载</el-button>

                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['price:gallery:remove']">删除</el-button>
                </template>
            </el-table-column>

        </el-table>
    </div>
</template>
   
<script>
import VueGallery from 'vue-gallery';
import { getFileList, delFile, uploadFile, getFileInfo } from '@/api/price/gallery'
import { getToken } from '@/utils/auth'
export default {
    data: function () {
        return {
            //文件列表
            fileList: [],
            token: getToken(),
            priceId: 0,
            type: 0,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            tableData: [{
                date: '2016-05-02',
                name: '王小虎',
                address: '上海市普陀区金沙江路 1518 弄'
            }, {
                date: '2016-05-04',
                name: '王小虎',
                address: '上海市普陀区金沙江路 1517 弄'
            }, {
                date: '2016-05-01',
                name: '王小虎',
                address: '上海市普陀区金沙江路 1519 弄'
            }, {
                date: '2016-05-03',
                name: '王小虎',
                address: '上海市普陀区金沙江路 1516 弄'
            }],
            images: [
                {
                    title: 'Fruits',
                    type: 'video/mp4',
                    href: 'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4',
                    preload: 'auto'
                }
            ],
            index: null
        };
    },
    methods: {
        //判断文件的类型
        getFileType(row) {
            let suffix = row.filePath.substring(row.filePath.lastIndexOf(".") + 1);
            let type = ''
            switch (suffix) {
                case 'mp4':
                case 'WebM':
                case 'Ogg':
                    type = 'video'
                    break;
                case 'png':
                case 'jpg':
                case 'webp':
                    type = 'image'
                    break
                case 'pdf':
                    type = 'pdf'
                    break
                default:
                    type = 'other'

            }
            return type


        },

        // 下载图片的操作
        handleDownload(row) {
            let type = this.getFileType(row)
            let url = row.fileUrl
            let path = row.filePath
            let reg = /\.\w+$/;
            let fileName = path.replace(reg, '');

            switch (type) {
                case 'image':
                    let image = new Image()  //创建图片对象
                    image.setAttribute('crossOrigin', 'anonymous') //设置允许跨域
                    image.src = url //赋值src
                    image.onload = () => {
                        //等待图片加载完成创建canvas
                        let canvas = document.createElement('canvas')
                        //将图片绘制到canvas画布上
                        canvas.width = image.width
                        canvas.height = image.height
                        let ctx = canvas.getContext('2d')
                        ctx.drawImage(image, 0, 0, image.width, image.height)
                        //此处同样是利用canvas自带API将画布数据导出为bolb流格式
                        canvas.toBlob((blob) => {
                            let url = URL.createObjectURL(blob)
                            const a = document.createElement("a");
                            console.log(this)
                            a.download = fileName;
                            // 直接将canvas导出的bolb:URL 格式赋值为a标签的href属性 同样进行点击触发下载
                            a.href = url;
                            document.body.appendChild(a);
                            a.click();
                            document.removeChild(a);
                            canvas = null
                            // 释放URL对象
                            URL.revokeObjectURL(url)
                        })
                    }

                    break;
                default:
                    var xhr = new XMLHttpRequest();
                    xhr.open('get', url, true); // 也可以使用POST方式，根据接口
                    // 						xhr.setRequestHeader("dis_k",`cb9a62d3796e276f8707318b3c48ed3d`);
                    // xhr.setRequestHeader("dis_t",`1617786336`);
                    xhr.responseType = "blob"; // 返回类型blob
                    xhr.onload = function () {
                        if (this.status === 200) {
                            var blob = this.response;
                            var reader = new FileReader();

                            reader.readAsDataURL(blob); // 转换为base64，可以直接放入a表情href
                            reader.onload = function (e) {
                                var a = document.createElement('a');
                                a.download = fileName; //下载文件名
                                a.href = e.target.result;
                                a.click();
                                window.URL.revokeObjectURL(e.target.result)
                            };
                        }
                    };
                    xhr.send();

                    break;

            }

        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.fileId || this.ids;
            this.$confirm('是否确认删除这' + (this.ids.length || 1) + '数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                console.log(ids)
                return delFile(ids.toString());
            }).then(() => {
                this.getFileList(this.priceId);
                this.msgSuccess("删除成功");
            })
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.fileId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePreview(file) {
            console.log(file);
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}？`);
        },
        getFileList() {
            let type = this.$route.query.type
            let id = this.$route.query.id
            let params = {

            }
            switch (type) {
                case '1':
                    params.fileId = id
                    break;
                case '2':
                    params.engineId = id
                    break;
                case '3':
                    params.controllerId = id
                    break;
                case '4':
                    params.fdjId = id
                    break;

            }
            getFileList(params).then(response => {
                this.tableData = response.rows

            });

        },
        handleSuccess() {
            this.msgSuccess("上传成功");
            this.getFileList()

        }
    },
    created() {
        this.priceId = this.$route.query.id
        this.type = this.$route.query.type
        this.getFileList()

    },
    components: {
        'gallery': VueGallery
    },
}
</script> 
   
<style scoped>
.app-container {
    padding: 20px;
}

.image {
    float: left;
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center center;
    border: 1px solid #ebebeb;
    margin: 5px;
}
</style>
