<template>
    <div class="c_box">
        <!-- <div class="mask"></div> -->
        <!-- <div v-if="!checkJson">暂未设置题目</div> -->
        <!-- <div v-if="!cJson">暂未设置题目</div> -->
        <div class="choices" v-if="!cJson">
            <div class="binfo_input">
                <div><span>填写者上传区</span></div>
            </div>
        </div>
        <div v-else class="choice_box">
            <!-- <div class="title"><div>{{ `（${option[checkJson.type].name}）` }}</div><div v-html="checkJson.title"></div></div> -->
            <div class="title" style="display: flex;">
                <!-- + `（${option[checkJson.type].name}）` -->
                <span style="min-width: fit-content;">{{ tindex + 1 + "、" }}</span>
                <span>{{ checkJson.title }}</span>
                <span style="color: #efa030;min-width: fit-content;" v-if="checkJson.score">（{{ '分值：' + checkJson.score
            +
            '分' }}）</span>
                <!-- </div><div v-html="checkJson.title"></div> -->
            </div>
            <div class="detail" v-if="checkJson.detail" v-html="checkJson.detail"
                style="color: #00000099;margin-top: 5px;">
            </div>
            <div class="choices">
                <div class="uploadBtn" v-if="checktype == 1">
                    <div class="btn" @click.stop="addImg($event)">
                        <span>添加本地文件</span>
                        <input type="file" accept="*" style="display: none" multiple="multiple"
                            @change="beforeUpload($event)" />
                    </div>
                    <div class="btn" @click="openFileBox()">
                        <span>从资源库添加</span>
                    </div>
                    <div class="switch">
                        <el-switch
                            active-color="#3681fc"
                            v-model="isTong">
                        </el-switch>
                        <span @click="isTong = !isTong">同步至资源库</span>
                    </div>
                </div>
                <div class="binfo_input">
                    <div class="fileBox" v-if="checkJson.file && checkJson.file.length">
                        <div class="fileC">
                            <div class="file" v-for="(item, index) in checkJson.file" :key="index"
                                @click.stop="checkFile(item)">
                                <img class="del" src="../../../../../../assets/icon/fileIcon/deleteworks.png"
                                    @click.stop="delFile(index)" />
                                <img class="download" src="../../../../../../assets/icon/fileIcon/download.png"
                                    @click.stop="downloadFile(item)"
                                    :style="{ right: checktype != 1 ? '10px' : '45px' }" />
                                <img class="img" :src="wordIcon" alt="" v-if="item.type == 1" />
                                <img class="img" :src="videoIcon" alt="" v-if="item.type == 2" />
                                <img class="img" :src="item.url" alt="" v-if="item.type == 3" />
                                <img class="img" :src="wordIcon" alt="" v-if="item.type == 4" />
                                <img class="img" :src="fileIcon" alt="" v-if="item.type == 5" />
                                <div class="name">
                                    <el-tooltip :content="item.name" placement="top" effect="dark">
                                        <span>{{ item.name }}</span>
                                    </el-tooltip>
                                </div>
                            </div>
                        </div>
                        <!-- @click.stop="addImg($event)" -->
                        <!-- <div class="btn" @click.stop="openFileBox()">
                            <span>点击添加文件</span>
                            <input type="file" accept="*" style="display: none" multiple="multiple" @change="beforeUpload($event)" />
                        </div> -->
                    </div>
                    <!-- @click.stop="addImg($event)"  @click.stop="addImg($event)" -->
                    <div class="uploadQ" v-else>
                        <span>填写者上传区</span>
                        <!-- <input type="file" accept="*" style="display: none" multiple="multiple" @change="beforeUpload($event)" /> -->
                    </div>
                    <div v-if="proVisible" class="mask">
                        <div class="progressBox">
                            <div class="lbox">
                                <img src="../../../../../../assets/loading.gif" />上传中，请稍后
                            </div>
                            <!-- <div style="margin-bottom: 10px">
                                <span>{{
                                    isFinishSize
                                }}M</span>
                                /
                                <span>{{
                                    isAllSize
                                }}M</span>
                            </div> -->
                            <!-- <el-progress :text-inside="true" :stroke-width="20" :percentage="progress
                                ? progress
                                : 0
                                " style="width: 80%"></el-progress> -->
                        </div>
                    </div>
                </div>
                <!-- <textarea  :readonly="checktype == 2" rows="2" v-autoHeight="68" class="binfo_input binfo_textarea" cols v-model="checkJson.answer2"
                    placeholder=""></textarea> -->
            </div>
        </div>
        <wpdf :dialogVisiblePdf.sync="dialogVisiblePdf" :url="wurl"></wpdf>
        <wVideo :dialogVisibleVideo.sync="dialogVisibleVideo" :url="wurl"></wVideo>
        <wOffice :dialogVisibleOffice.sync="dialogVisibleOffice" :url="wurl"></wOffice>
        <checkfile :dialogVisiblefile.sync="dialogVisiblefile" @setCheckJson="setCheckJson"></checkfile>
    </div>
</template>

<script>
import "../../../../../../common/aws-sdk-2.235.1.min.js";

import videoIcon from '../../../../../../assets/icon/fileIcon/isVideo.png'
import wordIcon from '../../../../../../assets/icon/fileIcon/isWord.png'
import fileIcon from '../../../../../../assets/icon/fileIcon/word2.png'

import wVideo from "../../../file/wVideo.vue";
import wpdf from "../../../file/wPdf2.vue";
import wOffice from "../../../file/wOffice.vue";
import checkfile from "../../../file/checkfile.vue";
export default {
    components: {
        wpdf,
        wVideo,
        wOffice,
        checkfile
    },
    props: {
        tindex: {
            type: Number
        },
        cJson: {
            type: Object,
        },
        checktype: {
            type: Number,
            default: 1
        },
        see: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            option: {
                1: { name: '附件' },
            },
            userid: this.$route.query.userid,
            checkJson: undefined,
            progress: 0,
            isFinishSize: 0,
            proVisible: false,
            isAllSize: 0,
            videoIcon: videoIcon,
            wordIcon: wordIcon,
            fileIcon: fileIcon,
            dialogVisiblePdf: false,
            dialogVisibleVideo: false,
            dialogVisibleOffice: false,
            dialogVisiblefile: false,
            wurl: "",
            isTong: false
        }
    },
    watch: {
        checkJson: {
            handler(newValue) {
                this.$emit('update:cJson', newValue)
            },
            deep: true
        },
    },
    methods: {
        depthCopy(s) {
            return JSON.parse(JSON.stringify(s));
        },
        openFileBox() {
            this.dialogVisiblefile = true
        },
        addImg(e) {
            var el = e.currentTarget;
            el.getElementsByTagName("input")[0].click();
            e.target.value = "";
        },
        beforeUpload(event, type) {
            // const loading = this.openLoading();
            let file = "";
            let cfindex2 = 0;
            for (var cfindex = 0; cfindex < event.target.files.length; cfindex++) {
                file = event.target.files[cfindex];

                var credentials = {
                    accessKeyId: "AKIATLPEDU37QV5CHLMH",
                    secretAccessKey: "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",
                }; //秘钥形式的登录上传
                window.AWS.config.update(credentials);
                window.AWS.config.region = "cn-northwest-1"; //设置区域

                var bucket = new window.AWS.S3({ params: { Bucket: "ccrb" } }); //选择桶
                var _this = this;

                // _this.progress = 0;
                _this.proVisible = true;
                // _this.isFinishSize = 0;
                // _this.isAllSize = (file.size / 1024 / 1024).toFixed(2);
                let _name = file.name
                let size = file.size;
                _this.$forceUpdate();
                if (file) {
                    var params = {
                        Key:
                            file.name.split(".")[0] +
                            new Date().getTime() +
                            "." +
                            file.name.split(".")[file.name.split(".").length - 1],
                        ContentType: file.type,
                        Body: file,
                        "Access-Control-Allow-Credentials": "*",
                        ACL: "public-read",
                    }; //key可以设置为桶的相抵路径，Body为文件， ACL最好要设置
                    var options = {
                        partSize: 2048 * 1024 * 1024,
                        queueSize: 2,
                        leavePartsOnError: true,
                    };
                    bucket
                        .upload(params, options)
                        .on("httpUploadProgress", function (evt) {
                            //这里可以写进度条
                            // console.log("Uploaded : " + parseInt((evt.loaded * 80) / evt.total) + '%');
                            // _this.progress = parseInt((evt.loaded / evt.total) * 100);
                            // _this.isFinishSize = (evt.loaded / 1024 / 1024).toFixed(2);
                            // _this.$forceUpdate();
                        })
                        .send(function (err, data) {
                            cfindex2++;

                            // _this.progress = 100;
                            // _this.isFinishSize = _this.isAllSize;
                            // _this.$forceUpdate();
                            // setTimeout(() => {
                            //     _this.proVisible = false;
                            //     _this.$forceUpdate();
                            // }, 1000);
                            setTimeout(() => {
                                if (
                                    cfindex2 == event.target.files.length ||
                                    cfindex2 > event.target.files.length
                                ) {
                                    _this.proVisible = false;
                                }
                            }, 1000);
                            // loading.close();
                            if (err) {
                                _this.$message.error("上传失败");
                            } else {
                                let _type = 2;
                                var imgA = [
                                    "png",
                                    "jpg",
                                    "jpeg",
                                    "bmp",
                                    "gif",
                                    "webp",
                                    "psd",
                                    "svg",
                                    "tiff",
                                ];
                                var fileA = [
                                    "DOC",
                                    "DOCX",
                                    "DOCM",
                                    "DOTM",
                                    "DOTX",
                                    "PPTX",
                                    "PPSX",
                                    "PPT",
                                    "PPS",
                                    "PPTM",
                                    "POTM",
                                    "PPAM",
                                    "POTX",
                                    "PPSM",
                                    "XLSX",
                                    "XLS",
                                ];
                                var videoA = [
                                    "AVI",
                                    "NAVI",
                                    "MPEG",
                                    "ASF",
                                    "MOV",
                                    "WMV",
                                    "3GP",
                                    "RM",
                                    "RMVB",
                                    "FLV",
                                    "F4V",
                                    "H.264",
                                    "H.265",
                                    "REAL VIDEO",
                                    "MKV",
                                    "WebM",
                                    "HDDVD",
                                    "MP4",
                                    "MPG",
                                    "M4V",
                                    "MGV",
                                    "OGV",
                                    "QTM",
                                    "STR",
                                    "AMC",
                                    "DVX",
                                    "EVO",
                                    "DAT",
                                    "OGG",
                                    "OGM",
                                ];
                                if (
                                    fileA.indexOf(
                                        data.Location.split(".")[
                                            data.Location.split(".").length - 1
                                        ].toLocaleUpperCase()
                                    ) != -1
                                ) {
                                    _type = 1; //word 文件
                                } else if (
                                    videoA.indexOf(
                                        data.Location.split(".")[
                                            data.Location.split(".").length - 1
                                        ].toLocaleUpperCase()
                                    ) != -1
                                ) {
                                    _type = 2; //视频
                                } else if (
                                    imgA.indexOf(
                                        data.Location.split(".")[
                                            data.Location.split(".").length - 1
                                        ].toLocaleLowerCase()
                                    ) != -1
                                ) {
                                    _type = 3; //图片
                                } else if (
                                    'pdf'.indexOf(
                                        data.Location.split(".")[
                                            data.Location.split(".").length - 1
                                        ].toLocaleLowerCase()
                                    ) != -1
                                ) {
                                    _type = 4; //pdf
                                } else {
                                    _type = 5; //文件
                                }
                                if (_this.checkJson.file) {
                                    _this.checkJson.file.push({
                                        name: _name,
                                        url: data.Location,
                                        type: _type,
                                    });
                                } else {
                                    _this.checkJson.file = []
                                    _this.checkJson.file.push({
                                        name: _name,
                                        url: data.Location,
                                        type: _type,
                                    });
                                }
                                if(_this.isTong){
                                    let _file = {
                                        name: _name,
                                        url: data.Location,
                                        type: _type,
                                        size: _this.formatFileSize(size)
                                    }
                                    _this.addSource(_file)
                                }
                                _this.$forceUpdate();

                                console.log(_this.checkJson);
                                console.log(data.Location);
                            }
                        });
                }
            }
        },
        addSource(file) {
            let params = [{
                n: encodeURIComponent(file.name),
                file: encodeURIComponent(file.url),
                type: file.type,
                pid: '0',
                uid: this.userid,
                size: file.size,
            }];
            this.ajax
                .post(this.$store.state.api + "addSourceFile", params)
                .then((res) => {
                    // if (_ctype == 2) {
                    //     this.$message.success('上传成功');
                    // }
                })
                .catch((err) => {
                    console.error(err);
                });
        },
        formatFileSize(bytes) {
            if (bytes < 1024) {
                return bytes + "B";
            } else if (bytes < 1048576) {
                return (bytes / 1024).toFixed(2) + "KB";
            } else if (bytes < 1073741824) {
                return (bytes / 1048576).toFixed(2) + "MB";
            } else {
                return (bytes / 1073741824).toFixed(2) + "GB";
            }
        },
        setCheckJson(name, url, type) {
            if (this.checkJson.file) {
                this.checkJson.file.push({
                    name: name,
                    url: url,
                    type: type,
                });
            } else {
                this.checkJson.file = []
                this.checkJson.file.push({
                    name: name,
                    url: url,
                    type: type,
                });
            }
            this.$forceUpdate();
        },
        checkFile(item) {
            if (item.type == 3) {
                this.$hevueImgPreview(item.url);
            } else if (item.type == 5) {
                this.downloadFile(item);
            } else if (item.type == 1) {
                this.dialogVisibleOffice = true
                this.wurl = item.url
            } else if (item.type == 2) {
                this.dialogVisibleVideo = true
                this.wurl = item.url
            } else if (item.type == 4) {
                this.dialogVisiblePdf = true
                this.wurl = item.url
            }
        },
        downloadFile(f) {
            var credentials = {
                accessKeyId: "AKIATLPEDU37QV5CHLMH",
                secretAccessKey: "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",
            }; //秘钥形式的登录上传
            window.AWS.config.update(credentials);
            window.AWS.config.region = "cn-northwest-1"; //设置区域
            let url2 = f.url;
            let _url2 = "";
            if (
                url2.indexOf("https://view.officeapps.live.com/op/view.aspx?src=") != -1
            ) {
                _url2 = url2.split(
                    "https://view.officeapps.live.com/op/view.aspx?src="
                )[1];
            } else {
                _url2 = url2;
            }
            let _this = this;

            _this.downLoading = _url2
            var s3 = new window.AWS.S3({ params: { Bucket: "ccrb" } });
            let name = decodeURIComponent(_url2.split("https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/")[1])
            var params = {
                Bucket: "ccrb",
                Key: name
            };
            s3.getObject(params, function (err, data) {
                _this.downLoading = ''
                if (err) console.log(err, err.stack); // an error occurred
                else {
                    let url = window.URL.createObjectURL(new Blob([data.Body]));
                    let a = document.createElement("a");
                    a.name = f.name;
                    a.href = url;
                    a.download = f.name;
                    a.click();
                    console.log(data);
                }          // sxuccessful response

            });
        },
        delFile(index) {
            this.checkJson.file.splice(index, 1)
            this.$forceUpdate();
        }
    },
    mounted() {
        this.checkJson = this.cJson ? this.depthCopy(this.cJson) : undefined

    }
}
</script>

<style scoped>
.c_box {
    width: 100%;
    position: relative;
}

/* .mask {
    position: absolute;
    height: 100%;
    width: 100%;
    z-index: 2;
} */

.choice_box {
    white-space: pre-line;
}

.choice_box>.title {
    font-weight: bold;
    width: 100%;
    word-break: break-all;
}

.choice_box>.choices {
    margin-top: 10px;
}

.binfo_input {
    width: 100%;
    margin: 0;
    padding: 10px;
    display: block;
    min-width: 0;
    outline: none;
    box-sizing: border-box;
    background: none;
    border: none;
    border-radius: 5px;
    background: #fff;
    font-size: 16px;
    resize: none;
    font-family: 'Microsoft YaHei';
    min-height: 120px;
    /* border: 1px solid #3682fc00; */
    border: 1.5px solid #e0e0e0;
    position: relative;
}

.binfo_input>.uploadQ {
    /* border: 1.5px dashed #dfdfdf; */
    height: 120px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f9fafb;
    color: rgb(124, 124, 124);
    border-radius: 5px;
    cursor: pointer;
}

.mask {
    background-color: rgb(0 0 0 / 30%);
    /* position: fixed; */
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 90;
    display: flex;
    align-items: center;
    justify-content: center;
}

.progressBox {
    width: 300px;
    height: 150px;
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 0 6px 1px #bfbfbf;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    position: relative;
    color: #6c6c6c;
}

.progressBox>>>.el-progress-bar__outer {
    background-color: #d1dfff !important;
}

.progressBox .lbox {
    height: 50px;
    font-size: 19px;
    display: flex;
    align-items: center;
    color: #747474;
}

.progressBox .lbox img {
    width: 40px;
    margin-right: 20px;
}

.closeCss {
    position: absolute;
    top: 8px;
    right: 8px;
    cursor: pointer;
    width: 20px;
    height: 20px;
}

.closeCss>img {
    width: 100%;
    height: 100%;
}

.binfo_input>.fileBox {}

.binfo_input>.fileBox .fileC {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    cursor: pointer;
}

.binfo_input>.fileBox .fileC>.file {
    width: 200px;
    height: 140px;
    margin: 10px 10px 10px 0px;
    border-radius: 15px;
    box-shadow: rgb(223, 218, 218) 0px 0px 6px 1px;
    overflow: hidden;
    margin-right: 15px;
    position: relative;
    display: flex;
    flex-direction: column;
}

.binfo_input>.fileBox .fileC>.file>.img {
    width: 100%;
    height: calc(100% - 35px);
    object-fit: cover;
}

.binfo_input>.fileBox .fileC>.file>.del {
    position: absolute;
    width: 25px;
    top: 10px;
    right: 10px;
    cursor: pointer;
}

.binfo_input>.fileBox .fileC>.file>.download {
    position: absolute;
    width: 25px;
    top: 10px;
    right: 35px;
    cursor: pointer;
    opacity: .8;
}


.binfo_input>.fileBox .fileC>.file>.name {
    height: 35px;
    width: 100%;
    background: #f9f9f9;
    display: flex;
    align-items: center;
    padding: 0 10px;
    box-sizing: border-box;
}

.binfo_input>.fileBox .fileC>.file>.name>span {
    display: block;
    text-overflow: ellipsis;
    max-width: 100%;
    white-space: nowrap;
    overflow: hidden;
}

.binfo_input>.fileBox .btn {
    width: 100%;
    height: 40px;
    background: #007bff;
    color: #fff;
    border-radius: 15px;
    margin-top: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}

.uploadBtn {
    display: flex;
    margin-bottom: 10px;
    align-items: center;
    width: 100%;
    justify-content: flex-end;
}

.uploadBtn .btn {
    display: flex;
    cursor: pointer;
    align-items: center;
    height: 30px;
    padding: 0 8px;
    background: #fff;
    color: #3681FC;
    border: 1px solid #3681FC;
    box-sizing: border-box;
    border-radius: 4px;
    font-size: 14px;
    align-items: center;
    margin-right: 10px;
}

.uploadBtn .switch{
    display: flex;
    align-items: center;
    cursor: pointer;
}
.uploadBtn .switch > span{
    margin-left: 5px;
}
</style>