
<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: 30px solid #dee2ea;
    .table_top_box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 37px;
      .table_top_box_left {
        display: flex;
        /deep/.el-input--mini .el-input__inner {
          width: 200px;
        }
        .num_box {
          margin-left: 50px;
          display: flex;
          /deep/ .el-input__inner {
            width: 40px;
            text-align: center;
          }
        }
      }
    }
    .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: 5px;
  }
  .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: 0 10px;
  }
}
.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;
}
</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">
              <el-input 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="1">直接结果</el-radio>
                  <el-radio :label="2">记分结果</el-radio>
                </el-radio-group>
              </el-form-item>
              <div class="hint_msg">
                注：结果类型修改后已填的所在标题下的内容将会清空
              </div>
            </div>
            <div
              class="num_box"
              v-if="table.resultType === 2 && table.textType === 11"
            >
              <el-form-item label="系数：" label-width="60px">
                <el-input v-model.trim="table.factor" />
              </el-form-item>
              <el-form-item
                label="常数："
                label-width="60px"
                style="margin-left: 10px"
              >
                <el-input v-model.trim="table.constant" />
              </el-form-item>
            </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"
        />
        <div class="rich_text" v-if="table.textType === 12">
          <el-form-item
            label="概述："
            prop="content"
            label-width="100px"
            ref="editor"
          >
            <quillEditor
              v-model="table.klScaleSaveGroup[0].content"
              :options="editorOption"
              class="ql-editor"
              ref="quillEditor"
            ></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>
      <ScoreResultsTable
        :list="scoreresultsdatas"
        @CHANEG_SCORE_RESULT="CHANEG_SCORE_RESULT"
      />
    </el-form>
  </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: "",
  issueId: "",
  two_constant: "",
  two_content: "",
  two_factor: "",
  two_orderNo: 0,
  two_remark: "",
  two_resultType: 0,
  two_ruleCode: "",
  two_score: 0,
  two_selectType: 1,
  two_status: 0,
  two_textType: 0,
  content: "",
  orderNo: 0,
  pushInfo: "",
  remark: "",
  result: "",
  ruleCode: "",
  score: 0,
  status: 0,
  textType: 11
};
const defaultTable = {
  constant: 0,
  content: "",
  factor: 0,
  klScaleSaveGroup: [
    {
      ...defaultDate
    }
  ],
  orderNo: 0,
  remark: "string",
  resultType: 1,
  ruleCode: "string",
  score: 0,
  status: 0,
  textType: 11
};
export default {
  components: { ScaleTable, quillEditor, ScoreResultsTable },
  data() {
    return {
      rules: rules,
      moveTopHover: false,
      moveBottomHover: false,
      scaleData: {
        conceptId: 0,
        klScaleParent: [
          // 表格层
          {
            constant: 0,
            content: "",
            factor: 0,
            klScaleSaveGroup: [
              // 问题层+结果层（包括分组）
              {
                groupId: 0,
                issueId: 0,
                two_constant: "",
                two_content: "",
                two_factor: "",
                two_orderNo: 0,
                two_remark: "",
                two_resultType: 0,
                two_ruleCode: "",
                two_score: 0,
                two_selectType: 1,
                two_status: 0,
                two_textType: 0,
                content: "",
                orderNo: 0,
                pushInfo: "",
                remark: "",
                result: "",
                ruleCode: "",
                score: 0,
                status: 0,
                textType: 0
              }
            ],
            orderNo: 0,
            remark: "string",
            resultType: 1,
            ruleCode: "string",
            score: 0,
            status: 0,
            textType: 11
          }
        ],
        modifier: "string"
      },
      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,
      ScoreResultsData: {
        //得分结果提交格式
        constant: null,
        content: "得分结果",
        factor: "",
        klScaleSaveGroup: {
          groupNum: 0,
          klScaleSub: [
            {
              constant: 0,
              content: "得分范围",
              factor: 0,
              klScaleDetail: [
                {
                  content: "string",
                  orderNo: 0,
                  pushInfo: "string",
                  remark: "string",
                  result: "string",
                  ruleCode: "string",
                  score: 0,
                  status: 0,
                  textType: 0
                }
              ],
              orderNo: 0,
              remark: "string",
              resultType: 0,
              ruleCode: "string",
              score: 0,
              selectType: 0,
              status: 0,
              textType: 0
            }
          ]
        }
      },
      scoreresultsdatas: [
        // todo me: 最后处理数据记得将orderNo设不唯一的值
        {
          content: {
            max: null,
            min: null
          },
          orderNo: null,
          pushInfo: "",
          remark: null,
          result: "",
          ruleCode: null,
          score: null,
          status: null,
          textType: null
        }
      ]
    };
  },
  methods: {
    /**
     * 增/删/得分结果表格
     * @param  type : 1：add  0:remove
     * @param  index :当前行索引
     */
    CHANEG_SCORE_RESULT(type, index) {
      console.log(type, index);
      if (type === 1) {
        this.scoreresultsdatas.splice(index + 1, 0, {
          content: {
            max: null,
            min: null
          },
          orderNo: null,
          pushInfo: "",
          remark: null,
          result: "",
          ruleCode: null,
          score: null,
          status: null,
          textType: null
        });
      } else {
        this.$delete(this.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;
          // 将新的组插入到当前组后边
          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) {
      console.log(this.scaleData.klScaleParent[tableIndex].klScaleSaveGroup);
      this.$set(this.scaleData.klScaleParent[tableIndex], "klScaleSaveGroup", [
        { ...defaultDate }
      ]);
    }
  },
  watch: {
    scaleData: {
      handler() {
        console.log("监听");
      },
      deep: true
    }
  },
  created() {
    this.editorOption.modules.toolbar.container =
      this.toolbars[this.toolbarMode];
  }
};
</script>
