<template>
  <!-- 编程类 -->
  <div class="content">
    <div class="header">
      <div>
        <i class="back el-icon-arrow-left" @click="Back()" style="cursor:pointer">
          <span>Back</span>
        </i>
        <span class="title">判分点设置</span>
      </div>
      <div>
        <el-button v-if="!isView" type="primary" size="mini" @click="saveAll">保存</el-button>
      </div>
    </div>

    <!--基本信息-->
    <div>
      <div class="form-con">
        <div class="title">
          <div class="black"></div>
          <div>基本信息</div>
        </div>
        <div class="item">
          <div class="label">判分点名称</div>
          <el-input
              v-model.trim="formData.points.name"
              :readonly="isView"
              @blur="handleBlur"
              placeholder="请输入内容"
              clearable
              style="width: 400px"
          ></el-input>
        </div>
        <div class="item">
          <div class="label">实验要求</div>
          <quill v-model="formData.points.experimentalRequirements" :readonly="isView" :border="true" :minHeight="150" :height="150" style="width: 100%"/>
        </div>
      </div>

      <!--实验代码-->
      <div class="form-con">
        <div class="title">
          <div class="black"></div>
          <div>实验代码</div>
        </div>
        <p style=" text-align: center;">参考答案</p>
        <div>
          <quill v-model="formData.points.experimentCode" :readonly="isView" :border="true" :minHeight="300" :height="300"/>
        </div>
      </div>

      <!--判分规则-->
      <div class="rule-con">
        <div class="title-con">
          <div class="title">
            <div class="black"></div>
            <div>判分规则</div>
          </div>
          <div>
            <el-button v-if="!isView" :disabled="isAddRule" type="primary" size="mini" @click="addRule">新增</el-button>
          </div>
        </div>

        <el-card shadow="hover">
          <el-table
              :data="tableData"
              :stripe="true"
              :cell-style="rowClass"
              header-align="center"
              :header-cell-style="headClass"
          >
            <el-table-column prop="id" type="index" label="序号" width="80"></el-table-column>
            <el-table-column label="编译器中正确答案" align="center">
              <template slot-scope="scope" v-if="scope.row.isSubject">
                <p class="p">字段一致性规则：用户编辑器中至少出现如下语句</p>
                <el-input
                    type="textarea"
                    :rows="3"
                    v-model="scope.row.required"
                    :disabled="isView || scope.row.isDisabled"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label=" " width="150">
              <template slot-scope="scope">
                <el-button
                    circle
                    type="primary"
                    v-if="scope.row.isSubject"
                    :disabled="isView || scope.row.isDisabled"
                    @click="changeResult(scope.row)"
                    style="position: absolute; right: 55px"
                >
                  {{ scope.row.resultOperation === 0 ? '且' : '或' }}
                </el-button>
                <el-button v-else type="primary" circle @click="changeRule(scope.row, scope.$index)">
                  {{ scope.row.ruleOperation === 0 ? "且" : "或" }}
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="终端中正确答案" align="center">
              <template slot-scope="scope" v-if="scope.row.isSubject">
                <p class="p">运行结果一致性规则：用户运行结果需要与下方代码运行结果一致</p>
                <el-input
                    type="textarea"
                    :rows="3"
                    v-model="scope.row.result"
                    :disabled="isView || scope.row.isDisabled"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="300" v-if="!isView">
              <template slot-scope="scope" v-if="scope.row.isSubject">
                <el-button v-show="scope.row.isDisabled" size="mini" type="text" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button v-show="!scope.row.isDisabled" size="mini" type="text" @click="handleSave(scope.row)">保存</el-button>
                <el-button v-show="!scope.row.isDisabled" size="mini" type="text" @click="handleCancel(scope.row, scope.$index)">取消</el-button>
                <el-button v-show="scope.row.isDisabled" size="mini" type="text" @click="handleDelete(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import quill from '@/components/quill'
import {deepCopy} from '@/utils/deepCopy'
export default {
  components: {quill},
  data() {
    return {
      bcId: "", // 编程类判分点id
      isAdd: Boolean(this.$route.query.isAdd), // 添加
      isEdit: Boolean(this.$route.query.isEdit), // 编辑
      isView: Boolean(this.$route.query.isView), // 查看
      isNameRepeat: false, // 名称是否重复
      formData: {
        points: {
          name: "",
          experimentalRequirements: "",
          experimentCode: "",
          isDel: 0,
          isOpen: 0,
          projectId: "",
          systemId: ""
        },
        bcJudgmentRuleList: []
      }, // 表单参数
      tableData: [], // 规则表格数据
      tableDataCopy: [], // 规则表格数据备份
      isAddRule: false, // 是否禁用新增规则按钮
    };
  },
  mounted() {
    console.log('当前地址=', location.host);
    console.log("token=", this.$route.query.token)
    console.log("systemId=", this.$route.query.systemId)

    this.$route.query.token && this.$store.commit('setParam', {
      token: atob(decodeURI(this.$route.query.token)),
      referrer: atob(decodeURI(this.$route.query.referrer))
    });
    if (this.$route.query.bcId) {
      this.bcId = this.$route.query.bcId;
      this.getInfoData(this.$route.query.bcId);
    }
    if (this.$route.query.systemId) {
      this.formData.points.systemId = this.$route.query.systemId;
    }
  },
  methods: {
    Back() { // 返回
      this.$router.back();
    },
    getInfoData(bcId) { // 获取判分点详细信息
      this.$get(`${this.api.queryBcJudgmentPointByBcId}?bcId=${bcId}`).then(res => {
        if (res.status === 200) {
          let {judgmentPoint, judgmentRule} = res;
          this.formData = {
            points: judgmentPoint,
            bcJudgmentRuleList: judgmentRule
          }
          // 重新封装数据
          this.anewPosttingData(judgmentRule)
          // judgmentRule.forEach((item, index) => {
          //   this.tableData.push({
          //     ...item,
          //     isSubject: true,
          //     isDisabled: true,
          //     isSave: true
          //   });
          // })
        } else {
          this.$message.warning(res.message);
        }
      }).catch(err => {
        console.log(err)
      });
    },
    // 重新封装数据
    anewPosttingData(judgmentRule){
      let length = judgmentRule.length;
      let tempArr = [];
      judgmentRule.forEach((item, index) => {
        let obj = {
          ...item,
          isSubject: true,
          isDisabled: true,  // 已禁用
          isSave: true // 已保存
        };
        //题目类型(1选择 2判断 3填空 4问答 5指标结果)
        if (item.type == 1 || item.type == 2) {
          obj.subjectId = Number(item.emptyOne);
          obj.value1 = item.itemId;
        } else if (item.type == 3) {
          obj.subjectId = Number(item.emptyOne);
          obj.value1 = item.emptyTwo;
        } else if (item.type == 4) {
          // 需要提目id
          if (item.emptyOne === "无限制") {
            obj.value1 = item.emptyOne;
            obj.value2 = "";
          } else {
            obj.value1 = item.emptyOne.substring(0, item.emptyOne.indexOf(","));
            obj.value2 = item.emptyOne.substring(item.emptyOne.indexOf(",") + 1, item.emptyOne.length);
          }
          obj.value3 = item.emptyTwo;
        } else if (item.type == 5) {
          obj.subjectId = Number(item.emptyOne);
          obj.value2 = item.emptyTwo[0];
          obj.value3 = item.emptyTwo.substring(1, item.emptyTwo.indexOf("~"));
          obj.value4 = item.emptyTwo.substring(item.emptyTwo.indexOf("~") + 1, item.emptyTwo.length - 1);
          obj.value5 = item.emptyTwo[item.emptyTwo.length - 1];
        }
        tempArr.push(obj);
        if (length > 1 && index !== (length - 1)) {
          tempArr.push({ruleOperation: item.ruleOperation});
        }
        this.tableData = tempArr;
        console.log(this.tableData)
      });
    },
    handleBlur() { // 新增/编辑判分点名称判重
      if (this.formData.points.name) {
        let params = {
          bcId: this.bcId,
          name: this.formData.points.name
        }
        this.$post(this.api.bcQueryNameIsExist, params).then(res => {
          if (res.status === 200) {
            this.isNameRepeat = false;
          } else {
            this.isNameRepeat = true;
          }
        }).catch(err => {
          console.log(err)
        });
      }
    },
    saveAll() { // 保存判分点
      if (this.isNameRepeat) {
        this.$message.warning(`当前判分点名称已存在`);
        return;
      }
      if (!this.formData.points.experimentalRequirements) {
        this.$message.warning(`实验要求不能为空`);
        return;
      }
      if (!this.tableData.length) {
        this.$message.warning(`请添加判分规则`);
        return;
      } else {
        for (let i = 0; i < this.tableData.length; i++) {
          if ((this.tableData[i].isSubject && !this.tableData[i].required) && (this.tableData[i].isSubject && !this.tableData[i].result)) {
            this.$message.warning(`第${i + 1}项，规则与结果至少填写一个`);
            return;
          } else if (this.tableData[i].isSubject && !this.tableData[i].isSave) {
            this.$message.warning(`第${i + 1}项，未保存`);
            return;
          }
        }
      }
      if (this.formData.points.name || this.formData.points.experimentCode){
        let tempArr = [];
        this.tableData.forEach(i => {
          if (i.isSubject) {
            let obj = {
              id: i.id ? i.id : "",
              bcId: i.bcId,
              required: i.required,
              result: i.result,
              resultOperation: i.resultOperation,
              ruleOperation: i.ruleOperation
            };
            tempArr.push(obj)
          }
        });
        this.formData.bcJudgmentRuleList = tempArr;
        if (this.isAdd) { // 新增判分点
          this.$post(this.api.addBcJudgmentPoint, this.formData).then(res => {
            if (res.status === 200) {
              this.$message.success("新增判分点成功");
              this.Back();
            } else {
              this.$message.warning(res.message);
            }
          }).catch(err => {
            console.log(err)
          })
        } else if (this.isEdit) { // 编辑判分点
          this.$post(this.api.updateBcJudgmentPoint, this.formData).then(res => {
            if (res.status === 200) {
              this.$message.success("更新判分点成功");
              this.Back();
            } else {
              this.$message.warning(res.message);
            }
          }).catch(err => {
            console.log(err)
          })
        }
      }else{
        this.$message.warning(`实验代码与判分点名称至少填写一个`);
        // if (!this.formData.points.name) {
        //   this.$message.warning(`判分点名称不能为空`);
        //   return;
        // }
        // if (!this.formData.points.experimentCode) {
        //
        //   return;
        // }
      }
    },
    addRule() { // 新增规则
      if(!this.isAddRule) {
        this.isAddRule = true;
        // this.tableData.length && this.tableData.push({ruleOperation: 0, indexNo: ""});
        if (this.tableData.length > 0) {
          this.tableData.push({
            ruleOperation: 0
          }, {
            indexNo: this.tableData.length + 1,
            isSubject: true,
            isDisabled: false, // 不禁用
            isSave: false, // 未保存
            lcId: this.lcId,
            resultOperation: 0,
            ruleOperation: 0,
            operationIds: "",
            value1: "",
            value2: "",
            value3: "",
            value4: "",
            value5: ""
          });
        } else {
          this.tableData.push({
            indexNo: this.tableData.length + 1,
            isSubject: true,
            isDisabled: false, // 不禁用
            isSave: false, // 未保存
            lcId: this.lcId,
            resultOperation: 0,
            ruleOperation: 0,
            operationIds: "",
            value1: "",
            value2: "",
            value3: "",
            value4: "",
            value5: ""
          });
        }
      }
    },
    changeResult(row) { // （左右）结果运算符(0：且 1：或 默认0)
      row.resultOperation = row.resultOperation === 0 ? 1 : 0;
    },
    changeRule(row, index) { // （上下）规则运算符(0：且 1：或 默认0)
      row.ruleOperation = row.ruleOperation === 0 ? 1 : 0;
      this.tableData[index - 1].ruleOperation = row.ruleOperation;
    },
    handleEdit(row) { // 处理编辑规则
      this.tableDataCopy = deepCopy(this.tableData); // 深拷贝
      row.isDisabled = false;
    },
    handleSave(row) { // 处理保存规则
      if (!row.required && !row.result) {
        this.$message.warning(`规则与结果至少填写一个`);
        return;
      }
      row.isSave = true;
      row.isDisabled = true;
      this.isAddRule = false;
    },
    handleCancel(row, index) { // 处理取消编辑规则
      if (row.isSave) {
        this.$set(this.tableData, index, this.tableDataCopy[index]);
      } else {
        this.tableData.splice(index-1, 2);
        // this.tableData.splice(index, 1);
        this.isAddRule = false;
      }
    },
    handleDelete(index) { // 处理删除规则
      this.$confirm("此操作将永久删除该规则, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      }).then(() => {
        if (index+1 == this.tableData.length){
          this.tableData.splice(index - 1, 2)
        }else{
          this.tableData.splice(index,2);
        }
        this.itemkey = Math.random()
        this.isAddRule = false;
      }).catch(() => {})
    },
    // 表头样式设置
    headClass() {
      return "text-align: center;";
    },
    // 表格样式设置
    rowClass() {
      return "text-align: center;";
    }
  }
};
</script>

<style lang="scss" scoped>
.content {
  position: relative;
  top: 10px;
  padding: 0 10px;
  background-color: #ffffff;

  .header {
    border-bottom: 1px dashed #ccc;
    height: 45px;
    line-height: 45px;
    font-size: 14px;
    font-weight: 600;
    padding: 0 10px;
    display: flex;
    justify-content: space-between;

    .back {
      line-height: 3;
      padding-left: 10px;

      span {
        font-size: 14px;
        font-weight: 600;
        padding-left: 5px;
      }
    }

    .title {
      font-weight: bold;
      margin-left: 20px;
    }
  }

  // 表单容器
  .form-con {
    padding-bottom: 24px;
    border-bottom: 1px dashed #ccc;

    .title {
      padding: 10px 0;
      //border-bottom: 1px dashed #ccc;
      display: flex;

      .black {
        width: 8px;
        height: 18px;
        background-color: #333;
        margin-right: 10px;
      }
    }

    .item {
      display: flex;
      margin-top: 24px;

      .label {
        width: 200px;
        text-align: right;
        padding-right: 20px;
        line-height: 35px;
      }
    }
  }

  // 规则容器
  .rule-con {
    padding-bottom: 60px;

    .title-con {
      height: 60px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .title {
        display: flex;

        .black {
          width: 8px;
          height: 18px;
          background-color: #333;
          margin-right: 10px;
        }
      }
    }

  }
}

// 滚动条的宽度
/deep/ ::-webkit-scrollbar {
  width: 6px; // 横向滚动条
  height: 6px; // 纵向滚动条 必写
}

// 滚动条的滑块
/deep/ ::-webkit-scrollbar-thumb {
  background-color: #9278ff;
  border-radius: 3px;
  -webkit-box-shadow: inset 0 0 5px #dddddd;
}

/deep/ ::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  -webkit-box-shadow: inset 0 0 5px #dddddd;
  border-radius: 0;
  background: #dddddd;
}
.tree-con{
  height: 230px;
  position: relative;
  .mask{
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    bottom: 0;
    right: 10px;
    cursor:not-allowed;
    z-index: 99999;
  }
}

@mixin block {
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.block {
  @include block;
  height: 230px;
  background-color: #fff;
  overflow: auto;
  .line {
    display: flex;
    align-items: center;
    margin: 10px 0;

    .label {
      width: 100px;
      margin-right: 10px;
      text-align: right;
      font-size: 12px;

      &.mini {
        width: auto;
      }
    }

    .action {
      flex: 1;
      text-align: left;

      /deep/ .el-input {
        width: 100%;
      }

      &.steps {
        @include block;
        display: inline-flex;
        flex-direction: column;
        height: 150px;
        font-size: 12px;
        overflow: auto;

        .radio-wrap {
          display: flex;
          flex-direction: column;

          .child {
            display: flex;
            flex-direction: column;
            margin-left: 15px;
          }

          /deep/ .el-radio {
            margin: 3px 0;
          }
        }
      }

      .inputs {
        display: flex;
        align-items: center;

        /deep/ .el-input {
          width: 100px;
          margin: 0 5px;

          &:first-child {
            margin-left: 0;
          }
        }
      }

      &.a-line {
        display: inline-flex;
      }

      .mini-textarea,
      /deep/ .mini-textarea .el-textarea__inner {
        width: 100%;
      }
    }
  }
}
</style>
