<template>
    <div class="c_box">
        <!-- <div class="mask"></div> -->
        <div v-if="!checkJson">暂未设置题目</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="c_title">
                <div class="title">
                    {{ `（${option[checkJson.type].name}）` + checkJson.title }}<span style="color: #efa030;"
                        v-if="checkJson.score">（{{ '分值：' + checkJson.score + '分' }}）</span>
                </div>

                <!-- </div><div v-html="checkJson.title"></div> -->
                <div class="p_box" v-if="isTeacher == 1 && checkJson.score">
                    <el-input v-model="checkJson.score2" class="c_input" @change="numberPan"
                        placeholder="请输入得分"></el-input><span style="margin: 0 10px;">/</span><span>{{ checkJson.score
                        }}分</span>
                </div>
                <div class="p_box" v-if="isTeacher == 2 && checkJson.score2">
                    <span>{{ checkJson.score2 }}分</span><span style="margin: 0 10px;">/</span><span>{{ checkJson.score
                    }}分</span>
                </div>
            </div>
            <div class="choices">
                <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" v-loading="downLoading == item.url" @click.stop="checkFile(item)">
                                <img class="del" src="../../../../../assets/icon/fileIcon/deleteworks.png"  @click.stop="delFile(index)" v-if="checktype == 1" />
                                <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>
                        <div class="btn" @click.stop="addImg($event)" v-if="checktype == 1">
                            <span>点击添加本地文件</span>
                            <input type="file" accept="*" style="display: none" @change="beforeUpload($event)" />
                        </div>
                    </div>
                    <div class="uploadQ" @click.stop="addImg($event)" v-else-if="checktype == 1">
                        <span>点击添加本地文件</span>
                        <input type="file" accept="*" style="display: none" @change="beforeUpload($event)" />
                    </div>
                    <div class="uploadQ" v-else>
                        <span>暂无添加附件</span>
                    </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>
    </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 wpdf from "../../../test/file/wPdf2.vue";
import wVideo from "../../../test/file/wVideo.vue";
import wOffice from "../../../test/file/wOffice.vue";

export default {
    components: {
        wpdf,
        wVideo,
        wOffice,
    },
    props: {
        cJson: {
            type: Object,
        },
        checktype: {
            type: Number,
            default: 1
        },
        see: {
            type: Boolean,
            default: false
        },
        isTeacher: {
            type: Number,
            default: 2
        }
    },
    data() {
        return {
            option: {
                1: { name: '附件' },
            },
            checkJson: undefined,
            progress: 0,
            isFinishSize: 0,
            proVisible: false,
            isAllSize: 0,
            videoIcon: videoIcon,
            wordIcon: wordIcon,
            fileIcon: fileIcon,
            downLoading: '',
            dialogVisiblePdf:false,
            dialogVisibleVideo:false,
            dialogVisibleOffice:false,
            wurl: "",
        }
    },
    watch: {
        checkJson: {
            handler(newValue) {
                this.$emit('update:cJson', newValue)
            },
            deep: true
        },
    },
    methods: {
        depthCopy(s) {
            return JSON.parse(JSON.stringify(s));
        },
        addImg(e) {
            var el = e.currentTarget;
            el.getElementsByTagName("input")[0].click();
            e.target.value = "";
        },
        numberPan() {
            if (/[^\d]/.test(this.checkJson.score2) || this.checkJson.score2 < 0) {
                this.$message.error('请输入大于0的数字')
                this.checkJson.score2 = ''
            }
            if(parseInt(this.checkJson.score2) > parseInt(this.checkJson.score)){
                this.$message.error('不能输入大于得分的数字')
                this.checkJson.score2 = this.checkJson.score
            }
        },
        beforeUpload(event, type) {
            // const loading = this.openLoading();
            var file = event.target.files[0];
            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);
            _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) {
                        _this.progress = 100;
                        _this.isFinishSize = _this.isAllSize;
                        _this.$forceUpdate();
                        setTimeout(() => {
                            _this.proVisible = false;
                            _this.$forceUpdate();
                        }, 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: file.name,
                                    url: data.Location,
                                    type: _type,
                                });
                            } else {
                                _this.checkJson.file = []
                                _this.checkJson.file.push({
                                    name: file.name,
                                    url: data.Location,
                                    type: _type,
                                });
                            }
                            _this.$forceUpdate();

                            console.log(_this.checkJson);
                            console.log(data.Location);
                        }
                    });
            }
        },
        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

            });
        },
        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
            }
        },
        delFile(index) {
            this.checkJson.file.splice(index, 1)
        }
    },
    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 {}

.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: 12px 14px;
    display: block;
    min-width: 0;
    outline: none;
    box-sizing: border-box;
    background: none;
    border: none;
    border-radius: 4px;
    background: #fff;
    font-size: 16px;
    resize: none;
    font-family: 'Microsoft YaHei';
    min-height: 120px;
    /* border: 1px solid #3682fc00; */
    border: 1.5px solid #CAD1DC;
    position: relative;
}

.binfo_input>.uploadQ {
    border: 1px dashed #CAD1DC;
    height: 120px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgb(243, 244, 246);
    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;
}
.choice_box> .c_title {
    display: flex;
    justify-content: space-between;
}
.choice_box> .c_title .title {
    font-weight: bold;
    width: 100%;
    word-break: break-all;
}

.choice_box> .c_title .p_box{
    margin-left: 5px;
    min-width: fit-content;
    display: flex;
    align-items: center;
}

.c_input {
    width: 90px;
}

.c_input >>> .el-input__inner{
    padding: 0 5px;
    text-align: right;
}
</style>