<template>
  <div class="engBox">
    <div class="engTitle">
      <div>作文题目：</div>
      <div>{{ englishList.engTitle }}</div>
    </div>
    <div class="engText">
      <div>作文内容：</div>
      <div class="cont" v-html="englishList.englishText"></div>
    </div>

    <div
      v-for="(item, index) in myAnswerList.imgList"
      :key="index"
      class="imgListCss"
    >
      <div class="itemImg">
        <img :src="item.url" alt="" />
        <div class="itemDeleteImg" @click="deleteImgList">
          <img src="../../../../assets/icon/english/delete.png" alt="" />
        </div>
      </div>
    </div>

    <div class="chooseUpload" @click="type = 1" v-if="type == 0">+在线编写</div>
    <div
      class="chooseUpload"
      @click="uploadDialogVisible = true"
      v-if="type == 0"
    >
      +图片上传
    </div>

    <div class="loadingImageText" v-if="type == 1">
      <div class="ftypeBox">
        <div class="ftypeTitle">
          <div>标题：</div>
          <div>
            <el-input
              v-model="myAnswerList.engTitle"
              placeholder="请填写你的作文题目"
            ></el-input>
          </div>
        </div>
        <div class="ftypeText">
          <div>正文：</div>
          <div>
            <el-input
              type="textarea"
              :rows="20"
              resize="none"
              v-model="myAnswerList.engText"
            ></el-input>
          </div>
        </div>

        <div class="upImg" @click="uploadDialogVisible = true">
          <img src="../../../../assets/icon/english/uploadImg.png" alt="" />
        </div>
      </div>
    </div>

    <el-dialog
      title="图片上传"
      :visible.sync="uploadDialogVisible"
      :append-to-body="true"
      width="30%"
      :before-close="handleClose"
      class="dialog_diy"
    >
      <div
        class="chapter_add"
        @click="addImg($event)"
        v-if="myAnswerList.imgList.length == 0"
      >
        <div class="up_photo2">
          <img src="../../../../assets/icon/plwork1.png" alt />
          <span>点击上传文件</span>
        </div>
        <input
          type="file"
          accept="video/mp4, video/quicktime, video/x-msvideo,application/pdf, application/.ppt, .pptx, .xlsx, .xls, application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document, image/*"
          multiple="multiple"
          style="display: none"
          @change="beforeUpload($event)"
        />
      </div>
      <div class="chapter_add" v-else>
        <div class="isUpImg">
          <img :src="myAnswerList.imgList[0].url" alt="" />
        </div>
        <div class="deleteImg" @click="deleteImgList">
          <img src="../../../../assets/icon/english/delete.png" alt="" />
        </div>
      </div>
      <div style="text-align: center">如已进行填写，确认后将清空内容噢。</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="checkImage">取 消</el-button>
        <el-button type="primary" @click="uploadIsType">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: ["englishList", "myAnswerList1", "userid"],
  data() {
    return {
      type: 0,
      myAnswerList: {
        engTitle: "",
        engText: "",
        imgList: [],
      },
      uploadDialogVisible: false,
      noneBtnImg: false,
      baseFile: "",
    };
  },
  watch: {
    myAnswerList1: {
      handler(newVal) {
        if (
          !this.myAnswerList1.engTitle &&
          !this.myAnswerList1.engText &&
          !this.myAnswerList1.imgList.length
        ) {
          this.myAnswerList = {
            engTitle: "",
            engText: "",
            imgList: [],
          };
          this.type = 0;
        } else {
          this.myAnswerList = newVal;
          this.type = 1;
        }
      },
      deep: true,
    },
  },
  methods: {
    handleClose(done) {
      done();
    },
    imgChange() {
      var _tmp = this.myAnswerList.imgList;
      this.noneBtnImg = _tmp.length >= 1;
    },
    addImg(e) {
      var el = e.currentTarget;
      el.getElementsByTagName("input")[0].click();
      e.target.value = "";
    },
    deleteImgList() {
      this.myAnswerList.imgList = [];
    },
    uploadIsType() {
      this.type = 1;
      this.uploadDialogVisible = false;
      this.getImageNav();
    },
    checkImage() {
      if (
        this.myAnswerList.imgList.length > 0 &&
        this.myAnswerList.imgList[0].url
      ) {
        this.getImageNav();
      } else {
        this.uploadDialogVisible = false;
      }
      this.uploadDialogVisible = false;
    },
    async beforeUpload(event) {
      // this.$message.success('进入上传')
      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;
      var photoA = [
        "BMP",
        "GIF",
        "PNG",
        "JPEG",
        "JPG",
        "TIF",
        "PCX",
        "TGA",
        "EXIF",
        "FPX",
        "SVG",
        "APNG",
      ];
      if (
        photoA.indexOf(
          file.name
            .split(".")
            [file.name.split(".").length - 1].toLocaleUpperCase()
        ) == -1
      ) {
        _this.$message.error("请上传图片!");
        return;
      }

      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,
          partSize: 1024 * 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 * 80) / evt.total);
          })
          .send(function (err, data) {
            // _this.progress = 100;

            if (err) {
              var a = _this.$refs.upload1.uploadFiles;
              a.splice(a.length - 1, a.length);
              _this.$message.error("上传失败");
            } else {
              // _this.$message.success('上传成功')
              _this.myAnswerList.imgList.push({
                name: file.name,
                url: data.Location,
              });
              _this.pngToWhiteBg(file);
              _this.imgChange();
              console.log(data.Location);
              // _this.$message.success('上传成功'+data.Location)
            }
          });
      }
    },
    pngToWhiteBg(file) {
      const _file = file;
      let read = new FileReader();
      read.readAsDataURL(file); // 文件转base64
      return new Promise((resolve, reject) => {
        read.onload = (e) => {
          let img = new Image();
          img.src = e.target.result;
          img.onload = async () => {
            // 生成canvas
            let canvas = document.createElement("canvas");
            let context = canvas.getContext("2d");
            // 绘制图片到canvas上
            canvas.width = img.width;
            canvas.height = img.height;

            // 在canvas绘制前填充白色背景
            context.fillStyle = "#fff";
            context.fillRect(0, 0, canvas.width, canvas.height);
            context.drawImage(img, 0, 0);
            let base64 = canvas.toDataURL(file["type"], 1);
            this.baseFile = base64;
          };
        };
      });
    },
    getImageNav() {
      let url = this.baseFile;
      const loading = this.$loading.service({
        background: "rgba(255, 255, 255)",
        target: document.querySelectorAll(".loadingImageText")[0],
      });
      let param = {
        messages: [
          {
            role: "user",
            content: [
              {
                type: "text",
                text: `NOTICE
Role: 你是一个专门解读图片的大师，你可以把图片里面的文字全部提取出来，然后根据Format example的要求返回
ATTENTION: Use '##' to SPLIT SECTIONS, not '#'. Output format carefully referenced "Format example".

-----
## Format example
{
    "title":"标题",
    "content":"内容"
}`,
              },
              {
                type: "image_url",
                image_url: {
                  url: url,
                },
              },
            ],
          },
        ],
        max_tokens: 4096,
        uid: "a77e9404-efec-11e9-96f9-028edca3b798",
        stream: false,
      };
      this.ajax.post("https://gpt4.cocorobo.cn/imageAnalyse", param).then(
        (res) => {
          if (
            res.data.FunctionResponse &&
            res.data.FunctionResponse.result &&
            res.data.FunctionResponse.result == "无效请求,请重新发起对话"
          ) {
            this.$message.error("你的作文内容太长，无法使用图片识别!");
            loading.close();
            return;
          }
          let aiImageNav = res.data.FunctionResponse.choices
            ? res.data.FunctionResponse.choices[0].message.content
            : "";
            try {
            aiImageNav = JSON.parse(aiImageNav);
            this.myAnswerList.engTitle = aiImageNav.title;
            this.myAnswerList.engText = aiImageNav.content;
          } catch (error) {
            // this.getImageNav();
            this.myAnswerList.engTitle = '';
            this.myAnswerList.engText = aiImageNav;
          }
          console.log(aiImageNav);
          // this.myAnswerList.engTitle = aiImageNav.title;
          // this.myAnswerList.engText = aiImageNav.content;
          this.type = 1;
          loading.close();
        },
        (err) => {
          console.log(err);
          loading.close();
        }
      );
    },
  },
  mounted() {
    if (
      !this.myAnswerList1.engTitle &&
      !this.myAnswerList1.engText &&
      !this.myAnswerList1.imgList.length
    ) {
      this.myAnswerList = {
        engTitle: "",
        engText: "",
        imgList: [],
      };
      this.type = 0;
    } else {
      this.myAnswerList = JSON.parse(JSON.stringify(this.myAnswerList1));
      this.type = 1;
    }
  },
};
</script>

<style scoped>
.engBox {
  width: 90%;
  margin: 0 auto;
}

.engTitle,
.engText {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: flex-start;
  margin-bottom: 20px;
}

.engTitle > .div:first-child,
.engText > div:first-child {
  min-width: 75px;
}

.chooseUpload {
  width: 100%;
  height: 300px;
  text-align: center;
  line-height: 300px;
  border: 1px dashed #c4c4c4;
  border-radius: 5px;
  margin-bottom: 20px;
  cursor: pointer;
}

.ftypeBox {
  margin: 20px auto 0;
}
.ftypeTitle {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: center;
}
.ftypeTitle > div:first-child {
  min-width: 42px;
  font-weight: bold;
}
.ftypeTitle > div:last-child {
  width: calc(100% - 42px);
}
.ftypeText {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: flex-start;
  margin-top: 20px;
}
.ftypeText > div:first-child {
  min-width: 42px;
  margin-top: 10px;
  font-weight: bold;
}
.ftypeText > div:last-child {
  width: 100%;
}
.upImg {
  width: 30px;
  height: 30px;
  float: right;
  cursor: pointer;
}
.upImg > img,
.isUpImg > img,
.deleteImg > img,
.itemImg > img,
.itemDeleteImg > img {
  width: 100%;
  height: 100%;
}

.chapter_add {
  width: 180px;
  margin: 0 auto;
  position: relative;
  text-align: center;
}

.up_photo2 {
  width: 180px;
  box-sizing: border-box;
  min-width: 180px;
  height: 180px;
  max-height: 180px;
  min-height: 180px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgb(242, 246, 255);
  /* padding: 25px; */
  margin-bottom: 10px;
}

.up_photo2 img {
  width: 50%;
  height: auto;
}

.up_photo2 span {
  color: #898989;
}

.isUpImg {
  width: 180px;
  min-width: 180px;
  height: 180px;
  max-height: 180px;
  min-height: 180px;
}

.deleteImg {
  width: 20px;
  height: 20px;
  cursor: pointer;
  position: absolute;
  top: 0;
  right: 0;
}

.imgListCss {
  margin: 10px 0;
}

.itemImg {
  width: 50px;
  height: 50px;
  position: relative;
}

.itemDeleteImg {
  width: 15px;
  height: 15px;
  cursor: pointer;
  position: absolute;
  top: -5px;
  right: -5px;
}

/* table 样式 */
.cont >>> table {
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
}

.cont >>> table td,
.cont >>> table th {
  border-bottom: 1px solid #ccc;
  border-right: 1px solid #ccc;
  /* padding: 20px 5px; */
  padding: 5px 10px;
  max-width: 0px;
  height: 30px;
  vertical-align: baseline;
  box-sizing: border-box;
}

.cont >>> table th {
  border-bottom: 2px solid #ccc;
  text-align: center;
}

/* blockquote 样式 */
.cont >>> blockquote {
  display: block;
  border-left: 8px solid #d0e5f2;
  padding: 5px 10px;
  margin: 10px 0;
  line-height: 1.4;
  font-size: 100%;
  background-color: #f1f1f1;
}

/* code 样式 */
.cont >>> code {
  display: inline-block;
  /* *display: inline; */
  zoom: 1;
  background-color: #f1f1f1;
  border-radius: 3px;
  padding: 3px 5px;
  margin: 0 3px;
}

.cont >>> pre code {
  display: block;
}

/* ul ol 样式 */
.cont >>> ul,
ol {
  margin: 10px 0 10px 20px;
}

/* code 样式 */
.cont {
  /* -webkit-user-modify: read-write; */
  overflow-wrap: break-word;
  -webkit-line-break: after-white-space;
}
</style>