<template>
    <div class="choice_box jiao" @click.stop="">
        <!-- <div class="title">设置附件</div> -->
        <div class="box">
            <div class="set_type" style="margin-top: 0;">
                <span>附件类型：</span>
                <el-select v-model="checkJson.type" @change="changeAnswer">
                    <el-option v-for="item in options" :key="item.type" :label="item.name" :value="item.type">
                    </el-option>
                </el-select>
            </div>
            <div class="set_type">
                <span>题目分数：</span><el-input v-model="checkJson.score" class="input" placeholder="请输入分数"
                    style="width: 120px" @change="numberPan"></el-input>
            </div>
            <div class="set_file">
                <div class="set_type">
                    <span>模板上传：</span>
                    <div class="btn" @click.stop="addImg($event)" v-loading="proVisible">
                        <el-button type="primary" size="mini">上传模板</el-button>
                        <input type="file" accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf" style="display: none" multiple="multiple"
                            @change="beforeUpload($event)" />
                    </div>
                </div>
                <div class="file_box" v-if="checkJson.mobanFile && checkJson.mobanFile.length" v-loading="loading">
                    <div class="file_item" v-for="(item, index) in checkJson.mobanFile" :key="index">
                        <div class="file_name">{{ item.name }}</div>
                        <div class="file_btns">
                            <div class="file_btn" @click="downloadFile(index)">下载</div>
                            <div class="file_btn" @click="delFile(index)">删除</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="set_title">
                <span>表单问题：</span>
                <!-- <el-input v-model="checkJson.title" class="input" placeholder="请输入标题"></el-input> -->
                <textarea v-autoHeight="68" rows="2" class="binfo_input binfo_textarea" cols v-model="checkJson.title"
                    placeholder=""></textarea>
                <!-- <editor-bar v-model="checkJson.title" @change="change"></editor-bar> -->
            </div>
            <div class="set_title">
                <span>问题描述：</span>
                <textarea v-autoHeight="68" rows="2" class="binfo_input binfo_textarea" cols v-model="checkJson.detail"
                    placeholder="请输入描述"></textarea>
            </div>
            <!-- <div class="set_options">
                <div class="title">附件答案：</div>
                <div class="xuan_body">
                    <el-input v-model="checkJson.answer" class="input" placeholder="请输入答案"></el-input>
                </div>
            </div> -->
        </div>
    </div>
</template>

<script>

const getFile = (url) => {
  return new Promise((resolve, reject) => {
    var credentials = {
        accessKeyId: "AKIATLPEDU37QV5CHLMH",
        secretAccessKey: "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",
      }; //秘钥形式的登录上传
      window.AWS.config.update(credentials);
      window.AWS.config.region = "cn-northwest-1"; //设置区域
      let url2 = 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;
      }
      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) {
        if (err) {
          console.log(err, err.stack)
          resolve({ data: 1 });
        }else {
          resolve({ data: data.Body });
          console.log(data); 
        }
      });
  });
};
// import EditorBar from "../../../../../tools/wangEnduit";
export default {
    components: {
        // EditorBar,
    },
    props: {
        cJson: {
            type: Object,
        },
    },
    data() {
        return {
            ctype: 1,
            options: [
                { type: 1, name: '附件' },
                // { type: 2, name: '多选题' }
            ],
            checkJson: {},
            proVisible: false,
            loading: false
        }
    },
    directives: {
        autoHeight: {
            update(el, binding) {
                const { value } = binding
                if (value && typeof value === 'number') {
                    el.style.height = `${value}px`
                } else {
                    el.style.height = 'auto'
                }
            },
            componentUpdated(el) {
                el.style.height = `${el.scrollHeight + 5}px`
            },
        },
    },
    watch: {
        checkJson: {
            handler(newVal) {
                this.$emit("setJson", newVal)
            },
            deep: true
        }
    },
    methods: {
        depthCopy(s) {
            return JSON.parse(JSON.stringify(s));
        },
        numberPan() {
            if (/[^\d]/.test(this.checkJson.score) || this.checkJson.score < 0) {
                this.$message.error('请输入大于0的数字')
                this.checkJson.score = ''
            }
        },
        changeAnswer() {
            this.checkJson.answer = []
        },
        change(val) {
            this.checkJson.title = val
            this.$forceUpdate();
            console.log(val);
        },
        addImg(e) {
            var el = e.currentTarget;
            el.getElementsByTagName("input")[0].click();
            e.target.value = "";
        },
        delFile(index){
            this.checkJson.mobanFile.splice(index, 1);
            this.$forceUpdate();
            this.$emit("setJson", this.checkJson)
        },
        downloadFile(index){
            this.loading = true;
            let file = this.checkJson.mobanFile[index]
            getFile(file.url).then((data) => {
                this.loading = false;
                if (data.data != 1) {
                    // 下载文件, 并存成ArrayBuffer对象
                    const file_name =file.name; // 获取文件名
                    const file_data = data.data; // 获取文件数据
                    let url = window.URL.createObjectURL(new Blob([file_data]));
                    let a = document.createElement("a");
                    a.name = file_name;
                    a.href = url;
                    a.download = file_name;
                    a.click();
                    console.log(data); 
                    this.$message.success("下载成功");
                }else {
                    this.$message.error("下载失败");
                }
            });

        },
        beforeUpload(event) {
            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.mobanFile) {
                                    _this.checkJson.mobanFile.push({
                                        name: _name,
                                        url: data.Location,
                                        type: _type
                                    });
                                    _this.$forceUpdate();
                                } else {
                                    _this.checkJson.mobanFile = [];
                                    _this.checkJson.mobanFile.push({
                                        name: _name,
                                        url: data.Location,
                                        type: _type
                                    });
                                    _this.$forceUpdate();
                                }
                                _this.$forceUpdate();

                                console.log(_this.checkJson);
                                _this.$emit("setJson", _this.checkJson)
                                console.log(data.Location);
                            }
                        });
                }
            }
        },
    },
    mounted() {
        console.log(1);
        // console.log(this.cJson);
        if (!this.cJson) {
            this.checkJson = {
                title: "标题",
                type: 1,
                detail: ""
            };
        } else {
            this.checkJson = this.depthCopy(this.cJson);
        }

    },
}
</script>

<style scoped>
.choice_box {
    margin-top: 10px;
    width: 100%;
    background: #f5f6f7;
    padding: 10px 10px 10px 36px;
    box-sizing: border-box;
    position: relative;
}

.choice_box>.box {}

.set_type {
    margin-top: 10px;
    display: flex;
    align-items: center;
}

.set_title {
    margin-top: 10px;
    display: flex;
    align-items: flex-start;
    /* flex-direction: column; */
}

.set_type>span,
.set_title>span {
    min-width: fit-content;
    font-size: 15px;
    min-width: 90px;
    text-align: right;
}

.set_options {
    margin-top: 10px;
}

.set_options>.title {
    font-size: 15px;
}

.xuan_body {
    margin-top: 10px;
    font-size: 14px;
}

.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: 48px;
    /* border: 1px solid #3682fc00; */
    border: 1px solid #CAD1DC;
}

.binfo_textarea {
    border: 1px solid #CAD1DC;
    font-size: 16px;
    resize: none;
    /* background: #f6f6f6; */
    font-family: 'Microsoft YaHei';
}

.binfo_input:focus-visible {
    border: 1px solid #3681FC !important;
}

/* .jiao::before{
    content: '';
    position: absolute;
    width: 0px;
    height: 0px;
    top: -20px;
    left: 15px;
    border-left: 12px solid transparent;
    border-right: 12px solid transparent;
    border-bottom: 10px solid #f6f6f6;
    border-top: 10px solid transparent;
} */


.file_box {
   
    width: 100%;
    box-sizing: border-box;
    margin: 10px 0;
}

.file_item {
    display: flex;
    width: 100%;
    padding: 5px;
    box-sizing: border-box;
    border-radius: 5px;
}

.file_item+.file_item {
    margin-top: 10px;
}

.file_name {
    color: #747474;
}

.file_item:hover{
  background: #fff;
}

.file_btns {
    margin-left: auto;
    display: flex;
    align-items: center;
}

.file_btn+.file_btn {
    margin-left: 10px;
}

.file_btn {
    color: #3681fc;
    cursor: pointer;
}
</style>