<template>
  <div class="c_box">
    <div class="mask" v-if="!isOpen"></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[cJson.type].name}）` }}</div><div v-html="cJson.title"></div></div> -->
      <div class="title" style="display: flex;">
        <!-- <span @click.stop="updateTitle()" style="min-width:fit-content">{{
          `（${option[cJson.type].name}）`
        }}</span> -->
        <span @click.stop="updateTitle()" v-if="!updateList.title">{{
          cJson.title ? cJson.title : "输入问题"
        }}</span>
        <input
          v-if="updateList.title"
          ref="titleRef"
          class="editInput"
          v-model="checkJson.title"
          @blur="save"
          @keyup.enter="save"
          placeholder="输入问题"
        />
        <span style="color: #efa030;min-width:fit-content" v-if="cJson.score"
          >（{{ cJson.score ? "分值：" + cJson.score + "分" : "" }}）</span
        >
        <!-- </div><div v-html="cJson.title"></div> -->
      </div>
      <div
        class="detail"
        v-if="!updateList.detail"
        @click.stop="updateDetail()"
      >{{ cJson.detail ? cJson.detail : "暂无描述" }}</div>
      <input
        v-if="updateList.detail"
        ref="detailRef"
        class="editInput"
        v-model="checkJson.detail"
        @blur="save"
        style="margin-top: 10px;color: rgb(136, 139, 146);"
        @keyup.enter="save"
        placeholder="请填写描述说明"
      />
      <div class="uploadFileBox">
        <div v-loading="proVisible">
          <el-button @click.stop="addFile()" type="primary" size="mini"
            >上传模板</el-button
          >
        </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"
            @click.stop=""
          >
            <div class="file_name">{{ item.name }}</div>
            <div class="file_btns">
              <div class="file_btn" @click.stop="downloadFile(index)">下载</div>
              <div class="file_btn" @click.stop="delFile(index)">删除</div>
            </div>
          </div>
        </div>
      </div>
      <div class="choices">
        <div class="binfo_input">
          <div><span>填写者上传区</span></div>
        </div>
        <!-- <textarea readonly rows="2" class="binfo_input binfo_textarea" cols
                    placeholder=""></textarea> -->
      </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);
      }
    });
  });
};

export default {
  props: {
    cJson: {
      type: Object
    },
    isOpen: {
      type: Boolean,
      default: false
    },
    index: {
      type: String,
      default: ""
    },
		cJson2:{
			type:Object
		},
  },
  data() {
    return {
      option: {
        1: { name: "附件" }
        // 2: { name: '多选题' }
      },
      updateList: {
        title: false,
        detail: false
      },
      checkJson: {},
      proVisible: false,
      loading: false
    };
  },
  watch: {
    checkJson: {
      handler(newVal) {
        // console.log("测试测试保存",newVal)
        this.$emit("setJson", newVal, this.index);
      },
      deep: true
    },
		isOpen(newValue) {
      if (newValue) {
        if (!this.cJson2 || Object.keys(this.cJson2).length == 0) {
          this.checkJson = {
            title: "标题",
            type: 1,
            answer: ""
          };
        } else {
          this.checkJson = this.depthCopy(this.cJson2);
        }
      }
    }
  },
  methods: {
    depthCopy(s) {
      return JSON.parse(JSON.stringify(s));
    },
    updateTitle() {
      this.updateList.title = true;
      this.$nextTick(() => {
        this.$refs.titleRef.focus();
      });
    },
    updateDetail() {
      this.updateList.detail = true;
      this.$nextTick(() => {
        this.$refs.detailRef.focus();
      });
    },
    save() {
      for (let key in this.updateList) {
        this.updateList[key] = false;
      }
    },
    addFile() {
      let input = document.createElement("input");
      input.type = "file";
      // input.accept = ".wav";
      // input.accept = "audio/*, .txt, .pdf, .xlsx";
      input.accept = ".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf";
      input.multiple = true;
      input.click();
      input.onchange = async () => {
        let files = input.files;
        let file = "";
        let cfindex2 = 0;
        for (var cfindex = 0; cfindex < files.length; cfindex++) {
          file = files[cfindex];
          if (!/\.(docx|doc|xls|xlsx|ppt|pptx|pdf)$/i.test(file.name)) {
            return this.$message.error(
              "请上传.docx,.doc,.xls,.xlsx,.ppt,.pptx,.pdf格式的文件"
            );
          }
          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 == files.length || cfindex2 > 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();
                  _this.$emit("setJson", _this.checkJson, _this.index);
                  console.log(data.Location);
                }
              });
          }
        }
      };
    },
    delFile(index) {
      this.checkJson.mobanFile.splice(index, 1);
      this.$forceUpdate();
      this.$emit("setJson", this.checkJson, this.index);
    },
    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("下载失败");
        }
      });
    }
  },
  mounted() {
    // if (!this.cJson || Object.keys(this.cJson).length == 0) {
    //   this.checkJson = {
    //     title: "标题",
    //     type: 1,
    //     detail: ""
    //   };
    // } else {
    //   this.checkJson = this.depthCopy(this.cJson2);
    // }
  }
};
</script>

<style scoped>
@import "../../global_styles.css";

.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;
}

.binfo_input > div {
  border: 1.5px dashed #dfdfdf;
  height: 120px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgb(249, 250, 251);
  color: rgb(124, 124, 124);
  border-radius: 5px;
}

.uploadFileBox {
  margin-top: 10px;
}

.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;
  transition: 0.2s;
}

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

.file_name {
  color: #747474;
}

.file_item:hover {
  background: #f0f2f5;
}

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

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

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