
<style lang="less" scoped>
.add_assess {
  h5 {
    padding: 30px 35px 0 35px;
    margin-bottom: 20px;
    font-size: 14px;
    span {
      color: #ff545b;
      margin-right: 3px;
    }
  }
  .table_map {
    border-bottom: 10px solid #dee2ea;
    .table_top_box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 37px;
      .table_top_box_left {
        display: flex;
        flex-wrap: wrap;
        /deep/.el-input--mini .el-input__inner {
          width: 200px;
        }
        .num_box {
          margin-left: 50px;
          /deep/ .el-input__inner {
            width: 40px;
            text-align: center;
          }
          .num {
            display: flex;
            /deep/.el-form-item__error {
              width: 100px;
              margin-left: -20px;
            }
          }
        }
      }
    }
    .move_btn {
      font-size: 14px;
      margin-left: 10px;
      display: flex;
      div {
        width: 12px;
        height: 16px;
        margin-right: 8px;
        img {
          width: 100%;
          height: 100%;
          cursor: pointer;
        }
      }
    }
  }
  /deep/ .el-form-item--mini.el-form-item,
  .el-form-item--small.el-form-item {
    margin-bottom: 0;
  }
  .hint_msg {
    font-size: 12px;
    color: red;
    margin-top: 14px;
  }
  .change_table_btns {
    width: 100%;
    margin-top: 20px;
    display: flex;
    justify-content: center;
    padding: 10px;
    box-sizing: border-box;
    border-top: 10px solid #dee2ea;
    div {
      width: 80px;
      height: 30px;
      line-height: 30px;
      border-radius: 2px;
      border: 1px solid #21cbc7;
      color: #21cbc7;
      font-size: 14px;
      padding: 0 5px;
      margin: 0 30px;
      cursor: pointer;
      &:nth-child(1) {
        &:hover {
          background: rgba(97, 218, 215, 0.1);
        }
      }
      &:nth-child(2) {
        border-color: #ff5b5b;
        color: #ff5b5b;
        &:hover {
          background: rgba(255, 91, 91, 0.1);
        }
      }
    }
  }
  .rich_text {
    padding: 10px 37px;
  }
}
.rich_text {
}
.quill-editor.ql-editor {
  padding-left: 0 !important;
}
/**富文本编辑器样式修改***/
.ql-snow .ql-picker.ql-size .ql-picker-label::before,
.ql-snow .ql-picker.ql-size .ql-picker-item::before,
.ql-snow .ql-picker.ql-header .ql-picker-label::before,
it .ql-editor,
.quill-editor {
  padding-top: 0px !important;
  margin-top: -8px;
  min-height: 48px;
  p {
    padding-top: 8px;
  }
}
.ql-editor.ql-blank::before {
  padding-top: 0px;
}
.btns {
  margin-top: 20px;
}
/deep/ .el-input--mini {
  font-size: 14px;
}
/deep/ .el-form-item.is-success .el-input__inner,
.el-form-item.is-success .el-textarea__inner {
  border-color: #c9c9c9 !important;
}
/deep/ .el-form-item.is-success .el-textarea__inner {
  border-color: #c9c9c9 !important;
}
/deep/ .el-form-item.is-success .el-textarea__inner {
  border-color: #c9c9c9 !important;
}
</style>  
<template>
  <div class="add_assess">
    <el-form
      size="mini"
      :model="scaleData"
      label-position="left"
      ref="scaleFormRef"
    >
      <div
        class="table_map"
        v-for="(table, tableIndex) in scaleData.klScaleParent"
        :key="tableIndex"
      >
        <h5><span>*</span>量表内容:</h5>
        <div class="table_top_box">
          <div class="table_top_box_left">
            <el-form-item
              label="标题："
              label-width="70px"
              :prop="`klScaleParent[${tableIndex}].content`"
              :rules="rules.title"
            >
              <el-input
                :ref="`klScaleParent[${tableIndex}].content`"
                :id="`klScaleParent[${tableIndex}].content`"
                maxlength="20"
                v-model.trim="table.content"
              />
            </el-form-item>
            <div style="margin: 0 20px">
              <el-form-item label="内容类型：" label-width="100px">
                <el-select
                  v-model="table.textType"
                  placeholder="请选择"
                  @change="initializationTableData($event, tableIndex)"
                >
                  <el-option label="问题选项" :value="11"> </el-option>
                  <el-option label="概述文本" :value="12"> </el-option>
                </el-select>
              </el-form-item>
              <div class="hint_msg">
                注：内容类型修改后已填的所在标题下的内容将会清空
              </div>
            </div>

            <div v-if="table.textType === 11">
              <el-form-item label="结果类型：" label-width="100px">
                <el-radio-group
                  v-model="table.resultType"
                  @change="initializationTableData($event, tableIndex)"
                >
                  <el-radio :label="2">直接结果</el-radio>
                  <el-radio :label="1">计分结果</el-radio>
                </el-radio-group>
              </el-form-item>
              <div class="hint_msg">
                注：结果类型修改后已填的所在标题下的内容将会清空
              </div>
            </div>
            <div
              class="num_box"
              v-if="table.resultType === 1 && table.textType === 11"
            >
              <div class="num">
                <el-form-item
                  label="系数："
                  label-width="70px"
                  :prop="`klScaleParent[${tableIndex}].factor`"
                  :ref="`klScaleParent[${tableIndex}].factor`"
                  :rules="rules.tableFactor"
                >
                  <el-input
                    type="number"
                    maxlength="6"
                    v-model.number="table.factor"
                  />
                </el-form-item>
                <el-form-item
                  label="常数："
                  label-width="70px"
                  style="margin-left: 10px"
                  :prop="`klScaleParent[${tableIndex}].constant`"
                  :rules="rules.tableConstant"
                >
                  <el-input
                    :ref="`klScaleParent[${tableIndex}].constant`"
                    type="number"
                    maxlength="6"
                    v-model.number="table.constant"
                  />
                </el-form-item>
              </div>

              <div class="hint_msg">
                注：结果类型修改后已填的所在标题下的内容将会清空
              </div>
            </div>
          </div>
          <div class="move_btn" v-if="scaleData.klScaleParent.length > 1">
            <div
              @click="CHANGE_TABLE({ tableIndex, type: 'up' })"
              @mouseover="moveTopHover = true"
              @mouseout="moveTopHover = false"
              v-if="tableIndex"
              title="上移"
            >
              <img
                :src="
                  moveTopHover
                    ? require('@/images/icon_hover_top.png')
                    : require('@/images/icon_default_top.png')
                "
                alt=""
              />
            </div>
            <div
              v-if="tableIndex !== scaleData.klScaleParent.length - 1"
              @click="CHANGE_TABLE({ tableIndex, type: 'down' })"
              @mouseover="moveBottomHover = true"
              @mouseout="moveBottomHover = false"
              title="下移"
            >
              <img
                :src="
                  moveBottomHover
                    ? require('@/images/icon_hover_down.png')
                    : require('@/images/icon_default_down.png')
                "
                alt=""
              />
            </div>
          </div>
        </div>
        <ScaleTable
          v-if="table.textType === 11"
          :tableData="table.klScaleSaveGroup"
          :tableIndex="tableIndex"
          :tableResultType="table.resultType"
          @CHANGE_FORM_DATA="CHANGE_FORM_DATA"
          @CHANGE_TABLE_ROW="CHANGE_TABLE_ROW"
          @CHANGE_ISSUE_CONTENT="CHANGE_ISSUE_CONTENT"
          ref="ScaleTable"
        />
        <div class="rich_text" v-if="table.textType === 12">
          <el-form-item
            label="概述："
            label-width="70px"
            :ref="`klScaleParent[${tableIndex}].klScaleSaveGroup[0].content`"
            :prop="`klScaleParent[${tableIndex}].klScaleSaveGroup[0].content`"
            :rules="rules.fwbContent"
          >
            <!-- klScaleParent[${tableIndex}].klScaleSaveGroup[${scope.$index}].content -->
            <quillEditor
              v-model="table.klScaleSaveGroup[0].content"
              :options="editorOption"
              class="ql-editor"
              ref="quillEditor"
              @change="onEditorChange($event)"
            ></quillEditor>
          </el-form-item>
        </div>
        <div class="change_table_btns">
          <div @click="CHANGE_TABLE({ tableIndex, type: 1 })">
            <i class="el-icon-plus"></i>
            新增标题
          </div>
          <div
            v-if="scaleData.klScaleParent.length > 1"
            @click="CHANGE_TABLE({ tableIndex, type: -1 })"
          >
            <i class="el-icon-minus"></i>
            删除标题
          </div>
        </div>
      </div>
    </el-form>
    <el-form
      size="mini"
      :model="scoreresults"
      label-position="left"
      ref="ScoreResultsRef"
    >
      <ScoreResultsTable
        ref="ScoreResultsTable"
        v-if="ScoreResultsShow"
        :list="scoreresults.scoreresultsdatas"
        @CHANEG_SCORE_RESULT="CHANEG_SCORE_RESULT"
      />
    </el-form>
    <!-- 暂时用的按钮 -->
    <!-- <button
      style="position: fixed; bottom: 20px; right: 20px; font-size: 16px"
      @click="assessCommitTest"
    >
      暂时用的按钮
    </button> -->
  </div>
</template>

<script>
import ScaleTable from "./scale-table.vue";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor, Quill } from "vue-quill-editor";
import config from "@api/config";
import { container, ImageExtend, QuillWatch } from "quill-image-extend-module";
Quill.register("modules/ImageExtend", ImageExtend);
import ScoreResultsTable from "./ScoreResultsTable.vue";
import rules from "./rules";
const defaultDate = {
  groupId: new Date().valueOf().toString(),
  issueId: new Date().valueOf().toString() + "-" + new Date().valueOf(),
  two_constant: 0,
  two_content: "",
  two_factor: 1,
  two_orderNo: 0,
  two_remark: "",
  two_resultType: null,
  two_ruleCode: "",
  two_score: 0,
  two_selectType: 21,
  two_status: 0,
  two_textType: 21,
  content: "",
  orderNo: 0,
  pushInfo: "",
  remark: "",
  result: "",
  ruleCode: "",
  score: null,
  status: 1,
  textType: 31
};
const defaultTable = {
  constant: 0,
  content: "",
  factor: 1,
  klScaleSaveGroup: [
    {
      ...defaultDate
    }
  ],
  orderNo: 0,
  remark: "string",
  resultType: 2,
  ruleCode: "string",
  score: null,
  status: 1,
  textType: 11
};
export default {
  components: { ScaleTable, quillEditor, ScoreResultsTable },
  props: {
    childScaleData: {
      default: null
    }
  },
  data() {
    return {
      rules: rules,
      moveTopHover: false,
      moveBottomHover: false,
      scaleData: {
        conceptId: 0,
        klScaleParent: [
          // 表格层
          {
            constant: 0,
            content: "",
            factor: 1,
            klScaleSaveGroup: [
              // 问题层+结果层（包括分组）
              {
                groupId: 0,
                issueId: 0,
                two_constant: 0,
                two_content: "",
                two_factor: 1,
                two_orderNo: 0,
                two_remark: "",
                two_resultType: null,
                two_ruleCode: "",
                two_score: 0,
                two_selectType: 21,
                two_status: 1,
                two_textType: 21,
                content: "",
                orderNo: 0,
                pushInfo: "",
                remark: "",
                result: "",
                ruleCode: "",
                score: null,
                status: 1,
                textType: 31
              }
            ],
            orderNo: 0,
            remark: "string",
            resultType: 2,
            ruleCode: "string",
            score: "",
            status: 1,
            textType: 11
          }
        ],
        modifier: "0"
      },
      toolbars: [
        [
          ["bold", "underline", "strike"],
          [{ list: "ordered" }, { list: "bullet" }],
          [{ script: "sub" }, { script: "super" }],
          [{ color: [] }, { background: [] }],
          [{ align: [] }],
          ["image"]
        ]
      ],
      editorOption: {
        modules: {
          ImageExtend: {
            loading: true,
            name: "upfile",
            size: 1,
            sizeError: () => {
              this.$message({
                showClose: true,
                message: "请上传 1M 以内的图片！",
                type: "warning"
              });
            },
            action: config.urls.promptServer,
            response: (res) => {
              if (res.code == "0") {
                return config.imgHost + res.data.url;
              } else {
                this.$message({
                  showClose: true,
                  message: res.msg,
                  type: "warning"
                });
              }
            }
          },
          toolbar: {
            container: container,
            handlers: {
              image: function () {
                QuillWatch.emit(this.quill.id);
              }
            }
          }
        }
      },
      toolbarMode: 0,
      scoreresults: {
        scoreresultsdatas: [
          // todo me: 最后处理数据记得将orderNo设不唯一的值
          {
            content: {
              max: null,
              min: null
            },
            orderNo: null,
            pushInfo: "",
            remark: null,
            result: "",
            ruleCode: null,
            score: null,
            status: 2,
            textType: 31
          }
        ]
      }
    };
  },
  methods: {
    getElementTop(element) {
      console.log('element',element);
      var actualTop = element.offsetTop;
      var current = element.parentNode;
      console.log("actualTop", actualTop);
      console.log("current", current.offsetTop);
      while (current !== null) {
        actualTop += current.offsetTop;
        current = current.parentNode;
      }
      return actualTop;
    },
    getDom(ref) {
      // console.log("???", this.getElementTop(document.getElementById(ref)));
      return this.getElementTop(document.getElementById(ref));
    },
    CHANGE_ISSUE_CONTENT(data) {
      const { value, tableIndex, rowIndex, name } = data;
      console.log(value, tableIndex, rowIndex, name);
      const thisIssueId =
        this.scaleData.klScaleParent[tableIndex].klScaleSaveGroup[rowIndex]
          .issueId;
      console.log(thisIssueId);
      this.scaleData.klScaleParent[tableIndex].klScaleSaveGroup.forEach(
        (item) => {
          if (item.issueId === thisIssueId) item[name] = value;
        }
      );
    },
    onEditorChange(e) {
      e.quill.deleteText(1000, 4);
      // e.quill.getLength()>1000
    },
    assessCommitTest() {
      console.dir(this.formtParams());
    },
    formtParams() {
      // console.log("this.scaleData.klScaleParent");
      // console.dir(this.scaleData.klScaleParent);
      // 提交数据的处理 start....
      // 1. 新建一个整体对象
      const params = {
        conceptId: 0,
        klScaleParent: [],
        modifier: "0"
      };
      // 2. 遍历数据
      this.scaleData.klScaleParent.forEach((table, tableIndex) => {
        if (table.textType === 11) {
          // 3. 将第一层数据格式顺序放进新对象（对应一个表格的数据）
          params.klScaleParent.push({
            ...table,
            klScaleSaveGroup: []
          });
          // 4. 建立一个新数组  用于后边赋值  params.klScaleParent[tableIndex].klScaleSaveGroup = groupArr;
          let groupArr = [];
          // 5. 遍历数据 添加组、问题、以及选项。
          table.klScaleSaveGroup.forEach((group, groupIndex) => {
            const groupFindIndex = groupArr.findIndex((item) => {
              return item.groupNum === group.groupId;
            });
            // 6. 查看数组中有没有同组的，如果没有同组的，直接push
            if (groupFindIndex === -1) {
              groupArr.push({
                groupNum: group.groupId,
                klScaleSub: [
                  {
                    issueId: group.issueId,
                    constant: group.two_constant,
                    content: group.two_content,
                    factor: group.two_factor,
                    orderNo: 0,
                    remark: group.two_remark,
                    resultType: group.two_resultType,
                    ruleCode: group.two_ruleCode,
                    score: group.two_score,
                    selectType: group.two_selectType,
                    status: group.two_status,
                    textType: group.two_textType,
                    klScaleDetail: [
                      {
                        content: group.content,
                        orderNo: 0,
                        pushInfo: group.pushInfo,
                        remark: group.remark,
                        result: group.result,
                        ruleCode: group.ruleCode,
                        score: group.score,
                        status: group.status,
                        textType: group.textType
                      }
                    ]
                  }
                ]
              });
            } else {
              // 7. 查看数组中有没有同组的，如果有，则判断同组的是否有issueId相同的
              const issueIdFindIndex = groupArr[
                groupFindIndex
              ].klScaleSub.findIndex(
                (issItem) => issItem.issueId === group.issueId
              );
              if (issueIdFindIndex === -1) {
                // 8. 如果没有相同的issueId，则在该组中添加当前项的问题
                groupArr[groupFindIndex].klScaleSub.push({
                  issueId: group.issueId,
                  constant: group.two_constant,
                  content: group.two_content,
                  factor: group.two_factor,
                  orderNo: 0,
                  remark: group.two_remark,
                  resultType: group.two_resultType,
                  ruleCode: group.two_ruleCode,
                  score: group.two_score,
                  selectType: group.two_selectType,
                  status: group.two_status,
                  textType: group.two_textType,
                  klScaleDetail: [
                    {
                      content: group.content,
                      orderNo: 0,
                      pushInfo: group.pushInfo,
                      remark: group.remark,
                      result: group.result,
                      ruleCode: group.ruleCode,
                      score: group.score,
                      status: group.status,
                      textType: group.textType
                    }
                  ]
                });
              } else {
                // 9. 如果有相同的issueId，则在该组的该问题中，添加一个新的选项
                groupArr[groupFindIndex].klScaleSub[
                  issueIdFindIndex
                ].klScaleDetail.push({
                  content: group.content,
                  orderNo: 0,
                  pushInfo: group.pushInfo,
                  remark: group.remark,
                  result: group.result,
                  ruleCode: group.ruleCode,
                  score: group.score,
                  status: group.status,
                  textType: group.textType
                });
              }
            }
          });
          // 10. 将groupArr赋值到提交数据中
          params.klScaleParent[tableIndex].klScaleSaveGroup = groupArr;
        } else if (table.textType === 12) {
          // 文本类型单独处理
          // console.dir(table);
          params.klScaleParent.push({
            ...table,
            klScaleSaveGroup: [
              {
                groupNum: 0,
                klScaleSub: [
                  {
                    constant: 0,
                    content: table.klScaleSaveGroup[0].content,
                    factor: 0,
                    orderNo: 0,
                    remark: "string",
                    resultType: null,
                    ruleCode: "string",
                    score: null,
                    selectType: 0,
                    status: 1,
                    textType: 21,
                    klScaleDetail: []
                  }
                ]
              }
            ]
          });
        }
      });

      // 11.将得分结果中的content转成字符串  max和min
      const scoreresultPatam = this.scoreresults.scoreresultsdatas.map(
        (item, index) => {
          return {
            ...item,
            orderNo: index,
            content: JSON.stringify(item.content)
          };
        }
      );
      // 12. 创建一个得分结果的表格  并将数据赋值上
      const table = {
        constant: 0,
        content: "得分结果",
        factor: 0,
        klScaleSaveGroup: [
          {
            groupNum: 0,
            klScaleSub: [
              {
                constant: 0,
                content: "得分范围",
                factor: 0,
                klScaleDetail: [...scoreresultPatam],
                orderNo: 0,
                remark: "string",
                resultType: null,
                ruleCode: "string",
                score: null,
                selectType: 21,
                status: 2,
                textType: 21
              }
            ]
          }
        ],
        orderNo: 0,
        remark: "string",
        resultType: null,
        ruleCode: "string",
        score: null,
        status: 2,
        textType: 13
      };
      // 13. 将得分结果加入到提交数据中
      if (this.ScoreResultsShow) {
        params.klScaleParent.push(table);
      }
      // 14  提交数据设置新的orderNo,删除issueId
      params.klScaleParent.forEach((tableItem, tableIndex) => {
        tableItem.orderNo = tableIndex;
        tableItem.klScaleSaveGroup.forEach((groupItem, groupIndex) => {
          groupItem.groupNum = groupIndex;
          groupItem.klScaleSub.forEach((issueItem, issueIndex) => {
            issueItem.orderNo = issueIndex;
            issueItem.issueId && delete issueItem.issueId;
            issueItem.klScaleDetail.forEach((optionItem, optionIndex) => {
              optionItem.orderNo = optionIndex;
            });
          });
        });
      });

      return params;
      // 提交数据的处理 end....
    },
    // 提交 （父级调用）
    assessCommit() {
      // new Promise((resolve))
      let valid1 = new Promise((resolve, reject) => {
        this.$refs["scaleFormRef"].validate((valid, object, err) => {
          if (valid) {
            resolve(true);
          } else {
            reject({ type: "c", object });
            return false;
          }
        });
      });
      let valid2 = new Promise((resolve, reject) => {
        this.$refs["ScoreResultsRef"].validate((valid, object) => {
          if (valid) {
            resolve(true);
          } else {
            reject({ type: "c", object });
            return false;
          }
        });
      });
      if (this.ScoreResultsShow) {
        return [valid1, valid2];
      }
      return [valid1];
    },
    /**
     * 增/删/得分结果表格
     * @param  type : 1：add  0:remove
     * @param  index :当前行索引
     */
    CHANEG_SCORE_RESULT(type, index) {
      // 节流： 阻止用户频繁点击
      if (this.timer) return;
      this.timer = setTimeout(() => {
        clearTimeout(this.timer);
        this.timer = null;
      }, 500);
      if (type === 1) {
        this.scoreresults.scoreresultsdatas.splice(index + 1, 0, {
          content: {
            max: null,
            min: null
          },
          orderNo: null,
          pushInfo: "",
          remark: null,
          result: "",
          ruleCode: null,
          score: null,
          status: 2,
          textType: 31
        });
      } else {
        this.$delete(this.scoreresults.scoreresultsdatas, index);
      }
    },
    /**
     * 增/删/移动表格
     * @param  tableIndex :当前表格
     * @param  type :类型 1：新增；-1：删除；up：上移；down：下移
     */
    CHANGE_TABLE(val) {
      // 节流： 阻止用户频繁点击
      if (this.timer) return;
      this.timer = setTimeout(() => {
        clearTimeout(this.timer);
        this.timer = null;
      }, 500);
      const { tableIndex, type } = val;
      switch (type) {
        case 1:
          this.scaleData.klScaleParent.splice(
            tableIndex + 1,
            0,
            JSON.parse(JSON.stringify(defaultTable))
          );
          break;
        case -1:
          this.$delete(this.scaleData.klScaleParent, tableIndex);
          break;
        case "up":
          const thisTable = this.scaleData.klScaleParent[tableIndex];
          const beforeTable = this.scaleData.klScaleParent[tableIndex - 1];
          this.$set(this.scaleData.klScaleParent, tableIndex - 1, thisTable);
          this.$set(this.scaleData.klScaleParent, tableIndex, beforeTable);
          break;
        case "down":
          const thisTable1 = this.scaleData.klScaleParent[tableIndex];
          const afterTable = this.scaleData.klScaleParent[tableIndex + 1];
          this.$set(this.scaleData.klScaleParent, tableIndex + 1, thisTable1);
          this.$set(this.scaleData.klScaleParent, tableIndex, afterTable);
          break;
      }
    },
    /**
     * 修改表格数据（添加、删除 ：组、问题、选项）
     * @param  type         类型：1/-1：新增/删除组; 2/-2：新增/删除问题; 3/-3：新增/删除选项
     * @param  tableIndex   单个量表的index
     * @param  rowIndex     表格 当前行的index
     * @param  groupId      当前组id
     * @param  issueId      当前问题id
     */
    CHANGE_TABLE_ROW(val) {
      // 节流： 阻止用户频繁点击
      if (this.timer) return;
      this.timer = setTimeout(() => {
        clearTimeout(this.timer);
        this.timer = null;
      }, 500);
      const { type, tableIndex, rowIndex, groupId, issueId } = val;
      const child = { ...defaultDate };
      switch (type) {
        case 1: //type 1: 添加组
          // 设置新的 groupId、issueId
          child.groupId = new Date().valueOf().toString();
          child.issueId = child.groupId + "-" + new Date().valueOf();
          // 使用当前的组id（groupId）  找到最后一个groupId为当前groupId的索引;
          let groupIndex;
          this.scaleData.klScaleParent[tableIndex].klScaleSaveGroup.forEach(
            (item, i) => {
              if (item.groupId === groupId) {
                groupIndex = i;
              }
            }
          );
          // 将新的组插入到当前组后边
          this.scaleData.klScaleParent[tableIndex].klScaleSaveGroup.splice(
            groupIndex + 1,
            0,
            child
          );
          break;
        case 2: //type 2: 添加问题
          // 设置新的 groupId（相同的组id）、issueId
          child.groupId = groupId;
          child.issueId = child.groupId + "-" + new Date().valueOf();
          let issueIndex;
          // 使用当前的组id（issueId）  找到最后一个issueId为当前issueId的索引;
          this.scaleData.klScaleParent[tableIndex].klScaleSaveGroup.forEach(
            (item, i) => {
              if (item.issueId === issueId) {
                issueIndex = i;
              }
            }
          );
          // 将新的组插入到当前组后边
          this.scaleData.klScaleParent[tableIndex].klScaleSaveGroup.splice(
            issueIndex + 1,
            0,
            child
          );

          break;
        case 3: //type 3: 添加选项
          // 设置新的 groupId（相同的组id）、issueId（相同的组问题id）
          child.groupId = groupId;
          child.issueId = issueId;
          // 添加相同问题的内容、常数、系数、选择
          const thisRowData =
            this.scaleData.klScaleParent[tableIndex].klScaleSaveGroup[rowIndex];
          child.two_content = thisRowData.content;
          child.two_factor = thisRowData.two_factor;
          child.two_constant = thisRowData.two_constant;
          child.two_selectType = thisRowData.two_selectType;
          // 将新的组插入到当前组后边
          this.scaleData.klScaleParent[tableIndex].klScaleSaveGroup.splice(
            rowIndex + 1,
            0,
            child
          );
          break;
        case -1: //type -1: 删除组 => 删除所有组id为当前组id的数据
          const newTableBygroupId = this.scaleData.klScaleParent[
            tableIndex
          ].klScaleSaveGroup.filter((item) => item.groupId !== groupId);
          this.$set(
            this.scaleData.klScaleParent[tableIndex],
            "klScaleSaveGroup",
            newTableBygroupId
          );
          break;
        case -2: //type -2: 删除问题 => 删除所有问题id为当前问题id的数据
          const newTableByissueId = this.scaleData.klScaleParent[
            tableIndex
          ].klScaleSaveGroup.filter((item) => item.issueId !== issueId);
          this.$set(
            this.scaleData.klScaleParent[tableIndex],
            "klScaleSaveGroup",
            newTableByissueId
          );
          break;
        case -3: //type -3: 删除选项
          this.$delete(
            this.scaleData.klScaleParent[tableIndex].klScaleSaveGroup,
            rowIndex
          );
          break;
      }
    },
    CHANGE_FORM_DATA(tableIndex, rowIndex, name, val) {
      this.$set(
        this.scaleData.klScaleParent[tableIndex].klScaleSaveGroup[rowIndex],
        name,
        val
      );
    },
    // 清空选项
    initializationTableData(e, tableIndex) {
      this.$set(this.scaleData.klScaleParent[tableIndex], "klScaleSaveGroup", [
        { ...defaultDate }
      ]);
    },
    resizeTable() {
      this.$refs.ScaleTable.forEach((item) => {
        item.resizeTable();
      });
      this.$refs.ScoreResultsTable &&
        this.$refs.ScoreResultsTable.resizeTable();
      // this.$refs.ScaleTable.resizeTable();
    }
  },
  watch: {
    scaleData: {
      handler() {
        console.log("监听");
      },
      deep: true
    },
    childScaleData() {
      // console.log("child Mounted");
      // console.dir(this.childScaleData);
      if (this.childScaleData) {
        // 修改时的默认数据赋值 逻辑：遍历接口数据 赋值给结构体数据
        let obj = {
          ...this.data,
          klScaleParent: []
        };
        delete obj.klScaleDetail;
        let scoreresults = {
          scoreresultsdatas: []
        };

        this.childScaleData.klScaleDetail.forEach((table, tableIndex) => {
          console.log("?????");
          if (table.textType === 13) {
            // 计算结果
            scoreresults.scoreresultsdatas = table.subMenuList[0].subMenuList;
            scoreresults.scoreresultsdatas.forEach((item) => {
              item.content = JSON.parse(item.content);
            });
            console.log(
              "scoreresults.scoreresultsdatas",
              scoreresults.scoreresultsdatas
            );
          } else if (table.textType === 11) {
            // 选项
            obj.klScaleParent.push({
              constant: table.constant,
              content: table.content,
              factor: table.factor,
              orderNo: table.orderNo,
              remark: table.remark,
              resultType: table.resultType,
              ruleCode: table.ruleCode,
              score: table.score,
              status: table.status,
              textType: table.textType,
              klScaleSaveGroup: []
            });

            table.subMenuList.forEach((issueItem, issueIndex) => {
              const arr = issueItem.subMenuList.map(
                (optionItem, optionIndex) => {
                  return {
                    groupId: issueItem.groupNum,
                    issueId: optionItem.parentId,
                    two_constant: issueItem.constant,
                    two_content: issueItem.content,
                    two_factor: issueItem.factor,
                    two_orderNo: issueItem.orderNo,
                    two_remark: issueItem.remark,
                    two_resultType: issueItem.resultType,
                    two_ruleCode: issueItem.ruleCode,
                    two_score: issueItem.score,
                    two_selectType: issueItem.selectType,
                    two_status: issueItem.status,
                    two_textType: issueItem.textType,
                    content: optionItem.content,
                    orderNo: optionItem.orderNo,
                    pushInfo: optionItem.pushInfo,
                    remark: optionItem.remark,
                    result: optionItem.result,
                    ruleCode: optionItem.ruleCode,
                    score: optionItem.score,
                    status: optionItem.status,
                    textType: optionItem.textType
                  };
                }
              );
              obj.klScaleParent[tableIndex].klScaleSaveGroup.push(...arr);
            });
          } else if (table.textType === 12) {
            // 文本
            obj.klScaleParent.push({
              constant: table.constant,
              content: table.content,
              factor: table.factor,
              orderNo: table.orderNo,
              remark: table.remark,
              resultType: table.resultType,
              ruleCode: table.ruleCode,
              score: table.score,
              status: table.status,
              textType: table.textType,
              klScaleSaveGroup: [
                {
                  two_constant: null,
                  two_content: null,
                  two_factor: null,
                  two_orderNo: null,
                  two_remark: null,
                  two_resultType: null,
                  two_ruleCode: null,
                  two_score: null,
                  two_selectType: null,
                  two_status: null,
                  two_textType: null,
                  content: table.subMenuList[0].content,
                  orderNo: table.subMenuList[0].groupNum,
                  pushInfo: table.subMenuList[0].pushInfo,
                  remark: table.subMenuList[0].remark,
                  result: table.subMenuList[0].result,
                  ruleCode: table.subMenuList[0].ruleCode,
                  score: table.subMenuList[0].score,
                  status: table.subMenuList[0].status,
                  textType: table.subMenuList[0].textType
                }
              ]
            });
          }
        });
        // console.dir(obj);
        // console.dir(scoreresults);

        this.scaleData = obj;
        if (scoreresults.scoreresultsdatas.length)
          this.scoreresults = scoreresults;
      }
    }
  },
  computed: {
    // 判断是否需要得分结果
    ScoreResultsShow() {
      const index = this.scaleData.klScaleParent.findIndex(
        (item) => item.resultType === 1
      );
      if (index === -1) {
        return false;
      }
      return true;
    }
  },
  created() {
    this.editorOption.modules.toolbar.container =
      this.toolbars[this.toolbarMode];
  },
  mounted() {}
};
</script>
