<template>
  <div class="JoinLine">
    <h6
      v-if="judgeAnswer == 'userAnswer' || judgeAnswer == 'studentAnswer'"
      class="standardTitle"
      style="margin: 10px 0 8px 24px"
    >
      {{ judgeAnswer == "userAnswer" ? "Your answer" : "Student answers" }}
    </h6>
    <h6
      v-else-if="judgeAnswer == 'standardAnswer'"
      class="standardTitle"
      style="margin: 10px 0 8px 24px"
    >
      Standard answer
    </h6>
    <div class="main">
      <div style="text-align: center">{{ curQue.title }}</div>
      <div :id="'container' + number" class="container">
        <div class="left">
          <ul>
            <div>{{ curQue.conTitle }}</div>
            <li
              :class="['left' + index + number]"
              v-for="(item, index) in curQue.con"
              :key="'left' + index"
            >
              <!--             :style="{
              background:
                JSON.stringify(data).indexOf(item.nodeId) != -1
                  ? '#F0F0F0'
                  : '',
            }" -->
              <div>
                <img
                  v-if="item.img_list.length > 0"
                  :src="item.img_list[0].id"
                  alt=""
                  @load="conImageload"
                />
                <div
                  class="text"
                  :class="[
                    'left' + index,

                    judgeAnswer == 'standardAnswer' ? 'correct' : '',
                    YouranswerClass(item, 'left'),
                  ]"
                  v-if="
                    item.detail.wordsList.length > 0 || item.detail.sentence
                  "
                >
                  <!-- 大于0就说明分词了 -->
                  <template v-if="item.detail.wordsList.length > 0">
                    <div
                      v-for="(it, wordIndex) in item.detail.wordsList"
                      :key="'word' + wordIndex"
                    >
                      <template v-if="item.detail.pyPosition == 'top'">
                        <p
                          style="
                            font-family: 'GB-PINYINOK-B';
                            font-size: 14px;
                            line-height: 20px;
                          "
                        >
                          {{ it.pinyin }}
                        </p>
                        <p
                          style="
                            font-family: 'FZJCGFKTK';
                            font-size: 20px;
                            line-height: 150%;
                          "
                        >
                          {{ it.chs }}
                        </p>
                      </template>
                      <template v-else>
                        <p
                          style="
                            font-family: 'FZJCGFKTK';
                            font-size: 20px;
                            line-height: 150%;
                          "
                        >
                          {{ it.chs }}
                        </p>
                        <p
                          style="
                            font-family: 'GB-PINYINOK-B';
                            font-size: 14px;
                            line-height: 20px;
                          "
                        >
                          {{ it.pinyin }}
                        </p>
                      </template>
                    </div>
                  </template>
                  <template v-else>
                    {{ item.detail.sentence }}
                  </template>
                </div>
              </div>
              <span>{{ item.Number }}</span>
              <img
                v-if="JSON.stringify(data).indexOf(item.nodeId) == -1"
                name="source"
                :id="item.nodeId"
                src="../../../assets/adult/LineImg.png"
                alt=""
              />
              <img
                v-else
                :id="item.nodeId"
                name="target"
                src="../../../assets/adult/LineImg-select.png"
                alt=""
              />
            </li>
          </ul>
        </div>
        <div class="right">
          <ul>
            <div>{{ curQue.optionTitle }}</div>
            <li
              :class="['right' + index + number]"
              v-for="(item, index) in curQue.option"
              :key="'right' + index"
            >
              <!--             :style="{
              background:
                JSON.stringify(data).indexOf(item.nodeId) != -1
                  ? '#F0F0F0'
                  : '',
            }" -->
              <img
                v-if="JSON.stringify(data).indexOf(item.nodeId) == -1"
                name="source"
                :id="item.nodeId"
                src="../../../assets/adult/LineImg.png"
                alt=""
              />
              <img
                v-else
                :id="item.nodeId"
                name="target"
                src="../../../assets/adult/LineImg-select.png"
                alt=""
              />
              <span>{{ item.Number }}</span>
              <div>
                <img
                  v-if="item.img_list.length > 0"
                  :src="item.img_list[0].id"
                  alt=""
                  @load="conImageload"
                />
                <div
                  class="text"
                  :class="[
                    'right' + index,
                    judgeAnswer == 'standardAnswer' ? 'correct' : '',
                    YouranswerClass(item, 'right'),
                  ]"
                  v-if="
                    item.detail.wordsList.length > 0 || item.detail.sentence
                  "
                >
                  <!-- 大于0就说明分词了 -->
                  <template v-if="item.detail.wordsList.length > 0">
                    <div
                      v-for="(it, wordIndex) in item.detail.wordsList"
                      :key="'word' + wordIndex"
                    >
                      <template v-if="item.detail.pyPosition == 'top'">
                        <p
                          style="
                            font-family: 'GB-PINYINOK-B';
                            font-size: 14px;
                            line-height: 20px;
                          "
                        >
                          {{ it.pinyin }}
                        </p>
                        <p
                          style="
                            font-family: 'FZJCGFKTK';
                            font-size: 20px;
                            line-height: 150%;
                          "
                        >
                          {{ it.chs }}
                        </p>
                      </template>
                      <template v-else>
                        <p
                          style="
                            font-family: 'FZJCGFKTK';
                            font-size: 20px;
                            line-height: 150%;
                          "
                        >
                          {{ it.chs }}
                        </p>
                        <p
                          style="
                            font-family: 'GB-PINYINOK-B';
                            font-size: 14px;
                            line-height: 20px;
                          "
                        >
                          {{ it.pinyin }}
                        </p>
                      </template>
                    </div>
                  </template>
                  <template v-else>
                    {{ item.detail.sentence }}
                  </template>
                </div>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <!-- 清除所有连线及连线的状态 -->
    <div class="fuwei" :class="[TaskModel == 'ANSWER' ? 'notAllow' : '']">
      <div @click="clearLine">
        <img src="../../../assets/adult/fuwei.png" alt="" />
        复位
      </div>
    </div>
  </div>
</template>

<script>
//这里可以导入其它文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》from ‘《组件路径》';
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: ["curQue", "TaskModel", "number", "judgeAnswer"],
  data() {
    //这里存放数据
    return {
      data: {
        userAnswerJudge: "",
        data: [],
      },
      allimgnumber: 0,
      lodimgnumber: 0,
    };
  },
  //计算属性 类似于data概念
  computed: {},
  //监控data中数据变化
  watch: {
    curQue(val, oldval) {
      this.$forceUpdate(); //触发更新函数更新高度
    },
  },
  //方法集合
  methods: {
    // 判断对错
    YouranswerClass(item, type) {
      if (this.judgeAnswer == "studentAnswer") {
        let clss = "error";
        this.data.data.forEach((items) => {
          if (type == "left") {
            if (items.source == item.nodeId) {
              if (items.correct) {
                clss = "correct";
              }
            }
          } else {
            if (items.target == item.nodeId) {
              if (items.correct) {
                clss = "correct";
              }
            }
          }
        });
        return clss;
      } else {
        return "";
      }
    },
    //   清除所有连线
    clearLine() {
      if (this.judgeAnswer) {
        return;
      }
      if (!this.TaskModel || this.TaskModel != "ANSWER") {
        this.data.data.forEach((item) => {
          if (item.source) {
            if (item.source.indexOf("Isexample") == -1) {
              item.source = null;
              item.target = null;
            }
          }
        });
        this.data.userAnswerJudge = "";
        this.jsPlumb.deleteEveryConnection(); //清除连线方法
        this.$set(
          this.curQue,
          "Bookanswer",
          JSON.parse(JSON.stringify(this.data))
        );

        this.data.data.forEach((item) => {
          this.jsPlumb.connect({
            source: item.source,
            target: item.target,
          });
        });
      }
    },
    showPlumb() {
      this.jsPlumb = this.$jsPlumb.getInstance({
        Container: "container" + this.number + this.judgeAnswer, // 选择器id
        EndpointStyle: { radius: 1, fill: "#74B5CA" }, // 端点样式
        PaintStyle: { stroke: "#DE4444", strokeWidth: 2 }, // 绘画样式，默认8px线宽  #456
        HoverPaintStyle: { stroke: "#18A0FB", strokeWidth: null }, // 默认悬停样式  默认为null
        ConnectionOverlays: [
          //   // 此处可以设置所有箭头的样式
          //   [
          //     "Arrow",
          //     {
          //       // 设置参数可以参考中文文档
          //       location: 1,
          //       length: 12,
          //       paintStyle: {
          //         stroke: "#7663EC",
          //         fill: "#7663EC",
          //       },
          //     },
          //   ],
          //   [
          //     "Label",
          //     {
          //       location: 0.1,
          //       cssClass: "aLabel", //hover时label的样式名
          //       events: {
          //         click: (info) => {
          //           console.log(info);
          //         },
          //       },
          //       visible: true,
          //     },
          //   ],
        ],
        Connector: ["Straight"], // 要使用的默认连接器的类型：直线，折线，曲线等
        DrapOptions: { cursor: "crosshair", zIndex: 2000 },
      });
      this.jsPlumb.batch(() => {
        for (let i = 0; i < this.curQue.con.length; i++) {
          this.initLeaf(this.curQue.con[i].nodeId, "source");
        }
        for (let j = 0; j < this.curQue.option.length; j++) {
          this.initLeaf(this.curQue.option[j].nodeId, "target");
        }
      });
      this.setjsPlumb(true, true);
      //点击连线
      this.jsPlumb.bind("click", (conn, originalEvent) => {
        if (this.judgeAnswer) {
          return;
        }
        let index = conn.sourceId.indexOf("Isexample");
        if (index != -1) {
          return;
        }
        if (!this.TaskModel || this.TaskModel != "ANSWER") {
          // 删除点击的线
          this.curQue.con.forEach((item, i) => {
            if (item.nodeId == conn.sourceId) {
              this.$set(this.data.data[i], "source", null);
              this.$set(this.data.data[i], "target", null);
            }
          });
          let node = document.getElementById(conn.sourceId);
          this.jsPlumb.removeAllEndpoints(node);
          sessionStorage.setItem("LineData", JSON.stringify(this.data));
          this.$set(
            this.curQue,
            "Bookanswer",
            JSON.parse(JSON.stringify(this.data))
          );
        }
      });

      //连线时触发
      this.jsPlumb.bind("connection", (conn, originalEvent) => {
        if (!this.TaskModel || this.TaskModel != "ANSWER") {
          let fig = false;
          this.data.data.forEach((item) => {
            if (item.source == conn.sourceId && item.target == conn.targetId) {
              fig = true;
            }
          });
          if (!fig) {
            this.curQue.con.forEach((item, i) => {
              if (conn.sourceId == item.nodeId) {
                this.$set(this.data.data[i], "source", conn.sourceId);
                this.$set(this.data.data[i], "target", conn.targetId);
              }
            });
            this.changeAllCorrect();
            sessionStorage.setItem("LineData", JSON.stringify(this.data));
            this.$set(
              this.curQue,
              "Bookanswer",
              JSON.parse(JSON.stringify(this.data))
            );
          }
        }
      });

      //右键触发
      this.jsPlumb.bind("contextmenu", (conn, originalEvent) => {
        console.log(conn, originalEvent);
      });
    },
    //  初始化规则使其可以连线、拖拽
    initLeaf(id, type) {
      const ins = this.jsPlumb;
      const elem = document.getElementById(id);
      if (type === "source") {
        ins.makeSource(elem, {
          anchor: [1, 0.5, 0.5, 0.5], // 左 上 右 下  数字我调不太准确 可改成left right
          allowLoopback: false, //允许回连
          maxConnections: 1, //最大连接数（-1表示不限制）
        });
      } else {
        ins.makeTarget(elem, {
          anchor: [0, 0.5, 0, 0],
          allowLoopback: false,
          maxConnections: 1,
        });
      }
    },

    setjsPlumb(sourceFlag, targetFlag) {
      const source = document.getElementsByName("source");
      const target = document.getElementsByName("target");
      this.jsPlumb.setSourceEnabled(source, sourceFlag);
      this.jsPlumb.setTargetEnabled(target, targetFlag);
      this.jsPlumb.setDraggable(source, false); // 是否支持拖拽
      this.jsPlumb.setDraggable(target, false); // 是否支持拖拽
    },
    conImageload() {
      this.lodimgnumber++;
      let _this = this;
      if (_this.lodimgnumber == _this.allimgnumber) {
        _this.curQue.option.forEach((item, index) => {
          for (let i = 0; i < this.curQue.con.length; i++) {
            let nodeleft = document.getElementsByClassName(
              `left${i + this.number}`
            )[0];
            let noderight = document.getElementsByClassName(
              `right${index + this.number}`
            )[0];
            if (nodeleft.offsetHeight > noderight.offsetHeight) {
              noderight.style.height = nodeleft.offsetHeight + "px";
            } else {
              nodeleft.style.height = noderight.offsetHeight + "px";
            }
          }
        });
      }
    },
    // 判断是否全对
    changeAllCorrect() {
      let flag = true;
      this.data.data.forEach((item) => {
        this.curQue.con.forEach((items) => {
          if (item.source && item.target) {
            if (item.source == items.nodeId) {
              if (
                Object.prototype.toString
                  .call(items.AnswerList)
                  .indexOf("Number") != -1
              ) {
                if (
                  item.target != this.curQue.option[items.AnswerList].nodeId
                ) {
                  flag = false;
                }
              } else {
                flag = false;
              }
            }
          } else {
            flag = false;
          }
        });
      });
      if (flag) {
        this.data.userAnswerJudge = "[JUDGE##T##JUDGE]";
      } else {
        this.data.userAnswerJudge = "[JUDGE##F##JUDGE]";
      }
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    if (!this.curQue.Bookanswer) {
      // sData = JSON.parse(sessionStorage.getItem("LineData"));
    } else {
      this.data = JSON.parse(JSON.stringify(this.curQue.Bookanswer));
    }
    this.curQue.con.forEach((item, i) => {
      let nodeId = item.Isexample
        ? "left_" + i + this.number + "Isexample" + this.judgeAnswer
        : "left_" + i + this.number + this.judgeAnswer;
      item.nodeId = nodeId;
      if (item.img_list.length > 0) {
        this.allimgnumber++;
      }
      if (item.Isexample) {
        this.data.data.push({
          source: item.nodeId,
          target: "right_" + item.AnswerList + this.number + this.judgeAnswer,
          index: i,
          answer: item.AnswerList,
        });
      }
    });
    this.curQue.option.forEach((item, i) => {
      let nodeId = item.Isexample
        ? "right_" + i + this.number + "Isexample" + this.judgeAnswer
        : "right_" + i + this.number + this.judgeAnswer;
      item.nodeId = nodeId;
      if (item.img_list.length > 0) {
        this.allimgnumber++;
      }
    });
    this.curQue.con.forEach((item, i) => {
      if (!item.Isexample) {
        this.data.data.push({
          answer: item.AnswerList,
          index: i,
          source: null,
          target: null,
          // userAnswerJudge:
          //   Object.prototype.toString.call(item.AnswerList).indexOf("Number") ==
          //   -1
          //     ? ""
          //     : "[JUDGE##F##JUDGE]",
        });
      }
    });

    if (this.judgeAnswer == "studentAnswer") {
      let conData = JSON.parse(JSON.stringify(this.curQue));
      this.curQue.con.forEach((item, i) => {
        let nodeId = item.Isexample
          ? "left_" + i + this.number + "Isexample" + this.judgeAnswer
          : "left_" + i + this.number + this.judgeAnswer;
        item.nodeId = nodeId;
        if (item.img_list.length > 0) {
          this.allimgnumber++;
        }
        if (item.Isexample) {
          this.data.data.push({
            source: item.nodeId,
            target: "right_" + item.AnswerList + this.number + this.judgeAnswer,
            index: i,
            answer: item.AnswerList,
          });
        }
      });
      this.curQue.option.forEach((item, i) => {
        let nodeId = item.Isexample
          ? "right_" + i + this.number + "Isexample" + this.judgeAnswer
          : "right_" + i + this.number + this.judgeAnswer;
        item.nodeId = nodeId;
        if (item.img_list.length > 0) {
          this.allimgnumber++;
        }
      });
      this.curQue = JSON.parse(JSON.stringify(conData));
    }
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.showPlumb();
    // 根据记录自动连起来
    if (this.allimgnumber == 0) {
      for (let i = 0; i < this.curQue.con.length; i++) {
        let nodeleft = document.getElementsByClassName(
          `left${i + this.number}`
        )[this.judgeAnswer == "standardAnswer" ? 1 : 0];
        let noderight = document.getElementsByClassName(
          `right${i + this.number}`
        )[this.judgeAnswer == "standardAnswer" ? 1 : 0];
        if (nodeleft && noderight) {
          if (nodeleft.offsetHeight > noderight.offsetHeight) {
            noderight.style.height = nodeleft.offsetHeight + "px";
          } else {
            nodeleft.style.height = noderight.offsetHeight + "px";
          }
        }
      }
    }
    this.data.data.forEach((item) => {
      if (item.source && item.target) {
        item.source = item.source + this.judgeAnswer;
        item.target = item.target + this.judgeAnswer;
      }
    });
    if (this.judgeAnswer == "standardAnswer") {
      this.data.data = [];
      this.curQue.con.forEach((item) => {
        if (
          Object.prototype.toString.call(item.AnswerList).indexOf("Number") !=
          -1
        ) {
          this.data.data.push({
            source: item.nodeId,
            target: this.curQue.option[item.AnswerList].nodeId,
          });
        }
      });
    } else if (this.judgeAnswer == "studentAnswer") {
      this.data.data.forEach((item) => {
        this.curQue.con.forEach((con) => {
          if (item.source == con.nodeId) {
            if (
              Object.prototype.toString
                .call(con.AnswerList)
                .indexOf("Number") != -1
            ) {
              if (item.target == this.curQue.option[con.AnswerList].nodeId) {
                item.correct = true;
              }
            }
          }
        });
      });
    }

    if (this.data.data.length > 0) {
      this.data.data.forEach((item) => {
        this.jsPlumb.connect({
          source: item.source,
          target: item.target,
        });
      });
    }
  },
  //生命周期-创建之前
  beforeCreated() {},
  //生命周期-挂载之前
  beforeMount() {},
  //生命周期-更新之前
  beforUpdate() {},
  //生命周期-更新之后
  updated() {
    for (let i = 0; i < this.curQue.con.length; i++) {
      let nodeleft = document.getElementsByClassName(`left${i}`)[0];
      let noderight = document.getElementsByClassName(`right${i}`)[0];
      if (nodeleft && noderight) {
        if (nodeleft.offsetHeight > noderight.offsetHeight) {
          noderight.style.height = nodeleft.offsetHeight + "px";
        } else {
          nodeleft.style.height = noderight.offsetHeight + "px";
        }
      }
    }
  },
  //生命周期-销毁之前
  beforeDestory() {},
  //生命周期-销毁完成
  destoryed() {},
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated() {},
};
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
.correct {
  background: rgba(44, 167, 103, 0.1) !important;
  /* 正确答案 */
  border: 1px solid #2ca767 !important;
}
.error {
  background: rgba(237, 52, 45, 0.1) !important;
  /* 错误颜色 */
  border: 1px solid #ed342d !important;
}
.JoinLine {
  width: 100%;
  .main {
    background: #f7f7f7;
    border: 1px solid rgba(0, 0, 0, 0.1);
    box-sizing: border-box;
    border-radius: 8px;
    padding: 24px 40px;
  }
  .container {
    position: relative;
    display: flex;
    justify-content: center;
    ul {
      list-style: none;
      li {
        // width: 333px;
        // // height: 64px;
        // background: #ffffff;
        // border: 1px solid rgba(0, 0, 0, 0.1);
        // box-sizing: border-box;
        // border-radius: 8px;
        margin-bottom: 16px;
        display: flex;
        align-items: center;
        > img {
          width: 24px;
          height: 24px;
        }
      }
    }
    .left {
      width: 50%;
      ul {
        > div {
          text-align: center;
          font-weight: bold;
          font-size: 16px;
          line-height: 150%;
          color: #000000;
          margin-bottom: 16px;
        }
        li {
          padding: 8px 0;
          display: flex;
          justify-content: flex-end; //右对齐
          > div {
            font-size: 16px;
            line-height: 150%;
            color: #000000;
            img {
              max-width: 238px;
              height: 158px;
            }
            .text {
              max-width: 200px;
              width: 100%;
              padding: 8px 16px;
              background: #ffffff;
              border: 1px solid rgba(0, 0, 0, 0.1);
              box-sizing: border-box;
              border-radius: 8px;
              display: flex;
              flex-wrap: wrap;
              p {
                margin: 0;
              }
            }
          }
          span {
            width: 24px;
            height: 24px;
            font-family: "robot";
            font-style: normal;
            font-weight: normal;
            font-size: 16px;
            line-height: 150%;
            text-align: center;
            color: #ffffff;
            background: #a7a7a7;
            border-radius: 50%;
            margin-left: 8px;
            margin-right: 12px;
          }
          > img {
            cursor: pointer;
            width: 24px;
            height: 24px;
          }
        }
      }
    }
    .right {
      width: 50%;
      margin-left: 88px;
      ul {
        > div {
          width: 334px;
          text-align: center;
          font-weight: bold;
          font-size: 16px;
          line-height: 150%;
          color: #000000;
          margin-bottom: 16px;
        }
        li {
          padding: 8px 0;
          > img {
            margin-left: 16px;
            width: 24px;
            height: 24px;
          }
          > span {
            width: 24px;
            height: 24px;
            font-family: "robot";
            font-style: normal;
            font-weight: normal;
            font-size: 16px;
            line-height: 150%;
            text-align: center;
            color: #ffffff;
            background: #a7a7a7;
            border-radius: 50%;
            margin-left: 12px;
            margin-right: 8px;
          }
          div {
            img {
              max-width: 238px;
              height: 158px;
            }
            .text {
              max-width: 200px;
              padding: 8px 16px;
              background: #ffffff;
              border: 1px solid rgba(0, 0, 0, 0.1);
              box-sizing: border-box;
              border-radius: 8px;
              display: flex;
              align-items: center;
              flex-wrap: wrap;
              p {
                margin: 0;
              }
            }
          }
        }
      }
    }
  }
  .fuwei {
    margin-top: 16px;
    height: 40px;
    &.notAllow {
      > div {
        cursor: not-allowed;
      }
    }
    > div {
      float: right;
      width: 72px;
      height: 40px;
      background: #ffffff;
      border: 1px solid rgba(0, 0, 0, 0.1);
      box-sizing: border-box;
      border-radius: 8px;
      display: flex;
      align-items: center;
      font-weight: bold;
      font-size: 16px;
      line-height: 150%;
      display: flex;
      align-items: center;
      text-align: center;
      color: #000000;
      cursor: pointer;
      img {
        margin-left: 8px;
        width: 24px;
        height: 24px;
      }
    }
  }
}
</style>
<style lang="scss">
.jtk-connector {
  path {
    cursor: pointer;
  }
}
</style>