<template>
  <el-dialog
    :title="lang.ssEnglishWrite"
    :visible.sync="engEvaDialogVisible"
    :append-to-body="true"
    width="800px"
    :before-close="handleClose"
    class="dialog_diy fullStyle"
  >
    <div class="engUpBox">
      <div class="engUpTop2">
        <div class="engTitle">
          <div>{{ lang.ssEssayTitle }}</div>
          <div>{{ evaEngJson.teacherJson.engTitle }}</div>
        </div>
        <div class="engText">
          <div>{{ lang.ssEssayContent }}</div>
          <div
            class="cont"
            v-html="evaEngJson.teacherJson.englishText"
            @click="checkImg(getImgList(evaEngJson.teacherJson.englishText))"
          ></div>
        </div>
        <div class="tcNewButton" @click="setType(1)">
          {{
            courseDetail &&
            (courseDetail.userid == uid ||
              (courseDetail.course_teacher &&
                courseDetail.course_teacher.indexOf(uid) != -1))
              ? lang.ssTeacherScoring
              : lang.ssViewTeacherEvaluation
          }}
        </div>
      </div>
      <div
        class="correctBox"
        :style="{ height: `calc(100% - ${topHeight}px)` }"
      >
        <div :class="type == 0 ? 'oldBox' : 'halfOldBox'">
          <div class="oldMes">
            {{ lang.ssOriginalAuthor.replace(/\*/g, evaEngJson.message.username) }}
          </div>
          <div class="oldText">
            <div class="detailBox">
              <div class="oldDetail">
                <div>{{ lang.ssTitleColon }}</div>
                <div>{{ evaEngJson.studentJson.engTitle }}</div>
              </div>
              <div class="oldDetail1">
                <div>{{ lang.ssContentColon }}</div>
                <div v-html="evaEngJson.studentJson.engText"></div>
              </div>
              <div
                class="oldDetail"
                v-if="
                  evaEngJson.studentJson.imgList &&
                  evaEngJson.studentJson.imgList.length > 0
                "
              >
                <div>{{ lang.ssImageColon }}</div>
                <div class="oldImg">
                  <img :src="evaEngJson.studentJson.imgList[0].url" alt="" />
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="type == 1" class="halfOldBox loadingText">
          <div
            class="oldMes"
            style="
              background: rgb(224 236 255);
              display: flex;
              flex-direction: row;
              flex-wrap: nowrap;
              align-items: center;
            "
          >
            <div
              class="allName"
              style="background: #aacaff; min-width: 100%; width: 100%"
            >
              {{ lang.ssTeacherScoring }}
            </div>
          </div>
          <div class="oldText" style="margin-top: 10px">
            <div class="detailBox" style="position: relative">
              <div
                class="addEva"
                v-if="
                  evaEngJson.teacherJson.textJson &&
                  evaEngJson.teacherJson.textJson.startJson.length > 0
                "
              >
                <!-- <el-rate
                  v-model="evaEngJson.teacherJson.textJson.score"
                  class="engRate"
                ></el-rate> -->
                <div>{{ lang.ssScoringCriteria }}</div>
                <div class="setEngEva">
                  <div
                    v-for="(item, index) in evaEngJson.teacherJson.textJson
                      .startJson"
                    :key="index"
                    class="engStartBox"
                  >
                    <div class="scoreItem">
                      <div>{{ item.title }}</div>
                      <div>
                        <el-rate
                          v-model="startList.scoreList[index]"
                          :disabled="
                            !(
                              courseDetail &&
                              (courseDetail.userid == uid ||
                                (courseDetail.course_teacher &&
                                  courseDetail.course_teacher.indexOf(uid) !=
                                    -1))
                            )
                          "
                        ></el-rate>
                      </div>
                    </div>
                    <div>{{ item.detile }}</div>
                  </div>
                </div>
              </div>
              <div v-else>
                <div>{{ lang.ssMarkScore }}：</div>
                <div>
                  <el-input
                    v-model="startList.score"
                    @change="isNumber($event)"
                  ></el-input>
                </div>
              </div>
              <div class="oldDetail">
                <div>{{ lang.ssHomeworkEvaluation }}</div>
                <el-input
                  type="textarea"
                  :rows="10"
                  resize="none"
                  v-model="teacherList.engText"
                  v-if="
                    courseDetail &&
                    (courseDetail.userid == uid ||
                      (courseDetail.course_teacher &&
                        courseDetail.course_teacher.indexOf(uid) != -1))
                  "
                />
                <el-input
                  type="textarea"
                  :rows="10"
                  resize="none"
                  v-model="teacherList.engText"
                  disabled
                  v-else
                />
              </div>
              <el-button
                type="primary"
                @click="getAiPj"
                style="position: absolute; bottom: -50px; right: 0"
                v-if="
                  courseDetail &&
                  (courseDetail.userid == uid ||
                    (courseDetail.course_teacher &&
                      courseDetail.course_teacher.indexOf(uid) != -1))
                "
                >{{ lang.ssAIEvaluation }}</el-button
              >
            </div>
          </div>
        </div>
        <!-- <div class="oldBox" style="position: relative">
          <div
            class="oldMes"
            style="
              background: rgb(224 236 255);
              display: flex;
              flex-direction: row;
              flex-wrap: nowrap;
              align-items: center;
            "
          >
            <div
              class="allName"
              :style="{ background: type == 0 ? '#aacaff' : '' }"
              @click="setType(0)"
            >
              AI评价
            </div>
            <div
              class="allName"
              :style="{ background: type == 1 ? '#aacaff' : '' }"
              @click="setType(1)"
            >
              教师评价
            </div>
          </div>
          <div
            v-if="type == 0"
            style="
              height: calc(100% - 45px);
              margin: 10px 0 0 0;
              overflow: auto;
            "
          >
            <div class="oldText loadingText" style="margin-top: 10px">
              <div class="detailBox" style="min-width: 300px">
                <div class="oldDetail" style="min-width: 300px">
                  <div>作业原文：</div>
                  <div v-html="evaEngJson.studentJson.engText"></div>
                </div>
                <div class="oldDetail" style="min-width: 300px">
                  <div>{{ lang.ssHomeworkEvaluation }}</div>
                  <div v-if="!aiList.engText">暂无AI评价</div>
                  <div v-else v-html="html"></div>
                </div>
              </div>
            </div>
            <el-button
              type="primary"
              @click="getAiPj"
              style="position: absolute; top: 50px; right: 20px"
              >AI评价</el-button
            >
          </div>
          <div v-if="type == 1" class="oldText" style="margin-top: 10px">
            <div class="detailBox">
              <div class="oldDetail">
                <div>作业原文：</div>
                <div v-html="evaEngJson.studentJson.engText"></div>
              </div>
              <div class="oldDetail">
                <div>{{ lang.ssHomeworkEvaluation }}</div>
                <el-input
                  type="textarea"
                  :rows="10"
                  resize="none"
                  v-model="teacherList.engText"
                />
              </div>
            </div>
          </div>
        </div> -->
      </div>
    </div>
    <span
      slot="footer"
      class="dialog-footer"
      style="z-index: 999; position: relative"
    >
      <el-button @click="close()">{{ lang.ssCancelBtn }}</el-button>
      <el-button type="primary" @click="addCode">{{ lang.ssConfirmBtn }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import MarkdownIt from "markdown-it";
import { myMixin } from "@/mixins/mixin.js";
export default {
  mixins: [myMixin],
  props: ["engEvaDialogVisible", "evaEngJson", "uid", "tType", "courseDetail"],
  data() {
    return {
      topHeight: 0,
      type: 0,
      aiList: {
        engTitle: "",
        engText: "",
      },
      teacherList: {
        engTitle: "",
        engText: "",
      },
      time: null,
      md: new MarkdownIt(),
      startList: {
        scoreList: [],
        score: 0,
      },
    };
  },
  computed: {
    html() {
      return this.teacherList.engText
        ? this.md.render(this.teacherList.engText)
        : "";
    },
  },
  methods: {
    handleClose(done) {
      this.close();
      done();
    },
    close() {
      this.$emit("update:engEvaDialogVisible", false);
    },
    isNumber(e) {
      let value = /^\d+$/.test(e);
      // let value = e.replace(/[^d]/g, ""); // 只能输入数字
      if (value == true) {
        if (e < 0) {
          this.$message.error(this.lang.ssEnterValueGreaterThanZero);
          this.startList.score = "";
          return;
        } else if (e > 100) {
          this.$message.error(this.lang.ssValueCannotExceed100);
          this.startList.score = "";
          return;
        }
      } else {
        this.startList.score = "";
        this.$message.error(this.lang.ssPleaseEnterNumber);
        return;
      }
    },
    checkImg(list) {
      if (!list.length) {
        return;
      }
      this.$hevueImgPreview({
        multiple: true, // 开启多图预览模式
        imgList: list, // 需要预览的多图数组
      });
    },
    getImgList() {
      return function (val) {
        let srcList = []; // 定义一个数组用来接收后面的img地址

        val.replace(
          /<img [^>]*src=['"]([^'"]+)[^>]*>/g,
          function (match, capture) {
            // 查找匹配的元素   match为整个img标签  capture为src中的内容
            srcList.push(capture);
          }
        );
        return srcList;
      };
    },
    setType(i) {
      if (this.type == i) {
        this.type = 0;
      } else {
        this.type = i;
      }
      this.$forceUpdate();
    },
    getAiPj() {
      const loading = this.$loading.service({
        background: "rgba(255, 255, 255)",
        target: document.querySelectorAll(".loadingText")[0],
      });
      let param = {
        model: "gpt-3.5-turbo",
        temperature: 0,
        max_tokens: 2048,
        top_p: 1,
        frequency_penalty: 0,
        presence_penalty: 0,
        messages: [
          {
            role: "user",
            content:
              "请对这篇文章进行评价:" + this.evaEngJson.studentJson.engText
          },
        ],
        uid: this.uid,
        stream: false,
      };
      this.ajax.post("https://gpt.cocorobo.cn/chat", param).then(
        (res) => {
          if (
            res.data.FunctionResponse &&
            res.data.FunctionResponse.result &&
            res.data.FunctionResponse.result == "无效请求,请重新发起对话"
          ) {
            this.$message.error(this.lang.ssEssayTooLongForAI);
            return;
          }
          this.teacherList.engText =
            res.data.FunctionResponse.choices[0].message.content;
          loading.close();
        },
        (err) => {
          console.log(err);
          loading.close();
        }
      );
    },
    addCode() {
      let params = {
        id: this.evaEngJson.message.id,
        aic: JSON.stringify(this.startList),
        tc: this.teacherList.engText,
      };
      this.ajax
        .get(this.$store.state.api + "addEngEva", params)
        .then((res) => {
          this.$message.success(this.lang.ssEvaluationSuccess);
        })
        .catch((err) => {
          this.$message.error(this.lang.ssNetworkPoor);
          console.error(err);
        });
    },
  },
  mounted() {},
  watch: {
    engEvaDialogVisible: {
      handler(newVal) {
        if (newVal) {
          if (this.evaEngJson.message.aiCode) {
            if (
              JSON.parse(this.evaEngJson.message.aiCode).scoreList.length > 0
            ) {
              this.startList.scoreList = JSON.parse(
                this.evaEngJson.message.aiCode
              ).scoreList;
            } else {
              this.startList.score = JSON.parse(
                this.evaEngJson.message.aiCode
              ).score;
            }
          }
          this.teacherList.engText = this.evaEngJson.message.teacherCode;
          if (this.startList.scoreList.length == 0) {
            for (
              var i = 0;
              i < this.evaEngJson.teacherJson.textJson.startJson.length;
              i++
            ) {
              this.startList.scoreList.push(0);
            }
          }
          this.type = 0;
          const loading = this.$loading.service({
            background: "rgba(255, 255, 255)",
            target: document.querySelectorAll(".loadingText")[0],
          });
          loading.close();
          this.$forceUpdate();
          this.timer = setInterval(() => {
            this.topHeight = document.querySelectorAll(".engUpTop2")[0]
              .offsetHeight
              ? document.querySelectorAll(".engUpTop2")[0].offsetHeight + 50
              : 0 - 50;
          }, 500);
          // setTimeout(() => {
          //   this.topHeight =
          //     document.querySelectorAll(".engUpTop2")[0].offsetHeight;
          // }, 500);
        } else {
          clearInterval(this.timer);
        }
      },
      deep: true,
    },
  },
  created() {},
};
</script>

<style scoped>
.dialog_diy >>> .el-dialog__header {
  background: #454545 !important;
  padding: 15px 20px;
}

.dialog_diy >>> .el-dialog__title {
  color: #fff;
}

.dialog_diy >>> .el-dialog__headerbtn {
  top: 19px;
}

.dialog_diy >>> .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}

.dialog_diy >>> .el-dialog__headerbtn .el-dialog__close:hover {
  color: #fff;
}
.dialog_diy >>> .el-dialog__body,
.dialog_diy >>> .el-dialog__footer {
  background: #fafafa;
}

.fullStyle >>> .el-dialog__body {
  height: calc(100% - 125px) !important;
  box-sizing: border-box;
  padding: 30px 0 !important;
  background: #fff !important;
}

.fullStyle >>> .el-dialog {
  width: 100% !important;
  max-width: 100% !important;
  height: 100% !important;
  margin: 0 !important;
}

.fullStyle {
  width: 100% !important;
  max-width: 100% !important;
  height: 100% !important;
  margin: 0 auto !important;
}

.fullStyle >>> .el-dialog__footer {
  background: #fff !important;
}
.engUpBox {
  width: 100%;
  height: 100%;
}

.engTitle,
.engText {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: flex-start;
  padding: 0 20px 20px 20px;
  box-sizing: border-box;
}

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

.correctBox {
  width: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: flex-start;
}

.oldBox,
.halfOldBox {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  align-items: center;
  border-top: 1px solid #d9d9d9;
  border-left: 1px solid #d9d9d9;
  border-right: 1px solid #d9d9d9;
}
.halfOldBox {
  width: 50% !important;
}
.oldBox > div:first-child,
.halfOldBox > div:first-child {
  width: 100%;
  text-align: center;
  background: #d9d9d9;
  height: 35px;
  line-height: 35px;
  font-weight: bold;
}

.oldText {
  width: 100%;
  height: calc(100% - 35px);
  overflow: auto;
  margin: 10px 0;
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  align-content: center;
  align-items: center;
}

.detailBox {
  width: 50%;
  padding: 10px;
  background: #f6f6f6;
  border-radius: 5px;
}

.oldDetail,
.oldDetail1 {
  padding-bottom: 30px;
}

.oldImg {
  width: 30px;
  height: 30px;
}

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

.allName {
  min-width: 50%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-word;
  cursor: pointer;
  text-align: center;
  border: 1px solid #bcc2cc;
  box-sizing: border-box;
}

/* 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;
}
.tcNewButton {
  color: #fff;
  background-color: #409eff;
  border-color: #409eff;
  width: 90px;
  height: 40px;
  min-width: 90px;
  border-radius: 5px;
  line-height: 40px;
  float: right;
  margin: 0 20px 10px 0;
  text-align: center;
  cursor: pointer;
}
.setEngEva {
  background: #fff;
  padding: 10px;
  margin: 5px 0;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-sizing: border-box;
}
.engStartBox {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  align-items: flex-start;
  margin-bottom: 5px;
}
.scoreItem {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-bottom: 5px;
}
.scoreItem > div:first-child {
  font-size: 15px;
  font-weight: bold;
}
.scoreItem > div:last-child >>> .el-rate {
  height: 25px !important;
}
.scoreItem > div:last-child >>> .el-rate__item {
  font-size: 25px !important;
}
.scoreItem > div:last-child >>> .el-rate__icon {
  font-size: 25px !important;
}
</style>