<template>
    <div class="process-prod">
      <!-- 上传文件弹窗 -->
      <el-dialog
        :visible.sync="showOpen"
        width="800px"
        :before-close="beforeClose"
        append-to-body
        title="上传文件"
      >
      <el-row>
        <el-col :span="3">
            <el-upload
                class="tuzhi-upload"
                ref="upload"
                :action="baseURL + '/common/upload'"
                :before-upload="handleBeforeUpload"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
                name="file"
                multiple
                :file-list="fileList"
                :headers="headers">
                <el-button size="small" type="primary" :loading="loading">选择文件上传</el-button>
            </el-upload>
        </el-col>
        
      </el-row>
      <div class="upload-list">
        <el-table :data="drawingList">
            <el-table-column align="left" label="名称" width="315" prop="fileOriginalName" >
                <template slot-scope="scope">
                    <div>
                        <i class="el-icon-document"></i>
                        {{scope.row.fileOriginalName}}
                    </div>
                </template>
            </el-table-column>
            <el-table-column align="left" label="大小" prop="fileSize" >
            </el-table-column>
            <el-table-column align="center" label="操作" >
                <template slot-scope="scope">
                    <el-button size="small" type="primary" @click="delItem(scope.row, scope.$index)">删除</el-button>
                    <el-button size="small" type="primary" @click="download(scope.row, scope.$index)">下载</el-button>
                </template>
            </el-table-column>
        </el-table>
      </div>
      
    </el-dialog>
  </div>
</template>
<script>
import {download} from "@/api/mes/pro/process";
import { getToken } from "@/utils/auth";
export default {
    props: {
        process: {
            type: Object,
            default: () => ({}),
        }
    },
    data() {
        return {
            drawingList: [],
            fileList: [],
            baseURL: process.env.VUE_APP_BASE_API,
            headers: {
                Authorization: "Bearer " + getToken()
            },
            showOpen: false,
            loading: false
        }
    },
    watch: {
        process(val) {
            if (val && val.drawingList && val.drawingList.length > 0) {
                this.drawingList = val.drawingList
            } else {
                this.drawingList = [] 
            }
        }
    },
    created (){
    },
    methods: {
        download(row) {
            download(row.filePath).then(res => {
                if(['png', 'jpeg', 'jpg'].indexOf(row.fileOriginalName.substring(row.fileOriginalName.lastIndexOf('.') + 1)) > -1) {
                    const imgUrl = `data: image/jpeg;base64,${btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ''))}`
                    // 将图片的src属性作为URL地址
                    const a = document.createElement('a')
                    const event = new MouseEvent('click')
                    a.download = row.fileOriginalName // '下载图片名称'
                    a.href = imgUrl // base图片地址
                    a.dispatchEvent(event)
                } else {
                    let blob = new Blob([res]);
                    //创建读取文件FileReader
                    let reader = new FileReader();
                    reader.readAsText(blob, "utf-8");
                    reader.onload = () => {
                        try{//这里返回的数据是JSON格式
                            //此处对fileReader读出的结果进行JSON解析
                            //会出现错误，需要进行捕获
                            let res = JSON.parse(reader.result);
                            //文件不存在或出现错误
                            console.log(res);
                            //弹出提示
                            //根据你业务处理
                    
                        }catch(err){//捕获异常 无法解析JSON格式 这里返回的数据是文件流 可供下载
                            console.log("pdf存在",res)
                            //以'a'标签的形式自点击下载
                            let downloadElement = document.createElement("a");
                            let href = window.URL.createObjectURL(blob); //创建下载的链接
                            downloadElement.href = href;
                            downloadElement.download = row.fileOriginalName; //下载后文件名
                            document.body.appendChild(downloadElement);
                            downloadElement.click(); //点击下载
                            document.body.removeChild(downloadElement); //下载完成移除元素
                            window.URL.revokeObjectURL(href); //释放掉blob对象
                        }
                    }
                }
            })
        },
        beforeClose(done) {
        // 更新父组件的processItemList
            this.$emit("updateItem", this.drawingList);
            done();
        },
        handleBeforeUpload(file) {
            this.loading = true
            // 校检文件后缀名
            // if(file && file.name && file.name.substring(file.name.lastIndexOf('.') + 1) === 'apk') {
            return true;
            // } else {
            // this.$message.error('请上传APK安装包');
            // this.loading = false
            // return false;
            // }
        },
        delItem(item, index) {
            this.drawingList.splice(index, 1)
        },
        handleUploadSuccess(res, file, fileList) {
            if (fileList.every(item => item.status == 'success')) {
                fileList.map((item, index) => {
                /** 这时只需要push进带有response的数据就好 */
                    console.log('item', item)
                    if(item.response) {
                        this.fileList.push({
                        name: item.response.data.originalFilename,
                        url: item.response.data.filePath
                        })
                        this.drawingList.push({filePath: item.response.data.filePath, fileOriginalName: item.response.data.originalFilename, fileSize: item.response.data.size})
                    }
                    if(index === fileList.length - 1) {
                        console.log('清除')
                        this.$refs.upload.clearFiles(); 
                    }
                })
            }
            // console.log('resresres', res, fileList)
            this.loading = false
            // // 如果上传成功
            // if (res.code == 200) {
            //     this.$message.success("文件上传成功");
            // } else {
            //     this.$message.error("文件上传失败");
            // }
            // this.$refs.upload.clearFiles(); 
        },
        handleUploadError() {
            this.loading = false
            this.$message.error("文件上传失败");
        }
    }
}
</script>
<style lang="scss">
.el-icon-document {
    color: #3578ff;
}
.tuzhi-upload .el-upload-list {
    display: none !important;
}
</style>