<style lang="less" scoped>
.AddNewRuleTable {
  width: 100%;
  background: #fff;
  margin-top: 10px;
  padding: 20px;
  box-sizing: border-box;
  /deep/ .el-table .el-input--mini .el-input__inner,
  .el-select {
    width: 100%;
    font-size: 12px;
  }
  .btn_box {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: space-around;
    .btn_div {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    img {
      width: 16px;
      height: 16px;
      cursor: pointer;
    }
  }
  .inp_box {
    // width: 100px;
    height: 100%;
    margin: 0 auto;
  }
  /deep/ .el-form-item__error {
    // position: absolute;
    top: 28px;
  }
  .type_content {
    /deep/ .el-form-item--mini.el-form-item,
    .el-form-item--small.el-form-item {
      margin: 0;
      width: 100%;
    }
    display: flex;
    .type_content_item1 {
      /deep/ .el-form-item__content {
        padding-bottom: 8px;
      }
      .row_box {
        .el-col {
          /deep/ .el-form-item__content {
            position: static;
          }
          /deep/ .el-form-item__error {
            position: absolute;
            width: 260px;
            left: 72px;
            white-space: normal;
          }
        }
      }
    }
    /deep/ .el-input.is-disabled .el-input__inner {
      color: #888;
    }
  }
  .custom_table_header {
    vertical-align: middle;
    &::before {
      content: "*";
      color: red;
      font-size: 12px;
      margin-right: 4px;
    }
  }
  // ::v-deep .el-table tbody tr:hover > td {
  //   // background-color: transparent;
  // }
  /deep/ .el-table th {
    background: transparent;
  }
  /deep/ .el-form-item__content {
    padding-bottom: 14px;
  }
  .table_cell_cls {
    vertical-align: top;
  }
  // /deep/ .el-table__body .el-table__row.hover-row td {
  //   // background-color: transparent;
  // }
  /deep/ .el-form-item__label {
    font-size: 12px;
  }
  h4 {
    font-size: 14px;
    font-weight: 400;
  }
  // /deep/ .el-table__body tr.current-row>td{
  //   background: #fff;
  // }
  /deep/ .el-table .cell {
    // overflow: initial;
  }
}
</style>

<template>
  <!-- :prop="`klRuleByIdSub[${scope.$index}].subDescription`" -->
  <div class="AddNewRuleTable">
    <h4 style="margin-bottom: 24px">规则内容：</h4>
    <!-- 隔行换色  :row-style="rowStyle" -->
    <el-table
      border
      :data="klRuleByIdSub"
      size="mini"
      style="min-height: 200px"
      height="calc(100vh - 383px)"
      :header-row-style="{ background: '#E3EAF4' }"
      :cell-style="cellStyle"
      :span-method="ObjectSpanMethod"
      ref="table"
      row-key="groupChildId"
    >
      <el-table-column width="80px" label="组" prop="groupType" fixed="left">
        <template slot-scope="scope">
          <div class="btn_box">
            <div class="btn_div">
              <img
                @click="addGroup(scope)"
                src="../../images/add-new-rule-sub.png"
                alt=""
              />
            </div>
            <div class="btn_div" v-if="!isLastDate(scope.row.groupId)">
              <img
                @click="$emit('delGroup', scope.row.groupId)"
                src="../../images/add-new-rule-del.png"
                alt=""
              />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        width="80px"
        v-if="maxNum && maxNum > 1"
        fixed="left"
        label="基础规则"
        prop="groupType"
      >
        <template slot-scope="scope">
          <div class="btn_box">
            <div class="btn_div" v-if="!isMax(scope.row.groupId)">
              <img
                @click="addChildGroup(scope)"
                src="../../images/add-new-rule-sub.png"
                alt=""
              />
            </div>
            <div
              class="btn_div"
              v-if="klRuleByIdSub.length > 1 && !scope.row.disabled"
            >
              <img
                @click="$emit('delGroupChild', scope.row.groupChildId)"
                src="../../images/add-new-rule-del.png"
                alt=""
              />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column width="170px" prop="subDescription" label="基础规则名称">
        <template slot="header" slot-scope="scope">
          <div class="custom_table_header">基础规则名称</div>
        </template>
        <template slot-scope="scope">
          <el-form-item
            class="inp_box"
            :prop="`klRuleByIdSub[${scope.$index}].subDescription`"
            :rules="rules.subDescription"
          >
            <el-input
              type="text"
              :disabled="scope.row.disabled"
              v-model="scope.row.subDescription"
              clearable
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column width="170px" prop="subType" label="基础规则类型">
        <template slot="header" slot-scope="scope">
          <div class="custom_table_header">基础规则类型</div>
        </template>
        <template slot-scope="scope">
          <el-form-item
            class="inp_box"
            :prop="`klRuleByIdSub[${scope.$index}].subType`"
            :rules="rules.subType"
          >
            <el-select
              v-model="scope.row.subType"
              :disabled="scope.row.disabled"
              placeholder="请选择"
              @change="subTypeChange($event, scope.$index)"
              :ref="`klRuleByIdSub[${scope.$index}].subType`"
            >
              <el-option
                v-for="item in scope.row.baseTypes"
                :key="item.id"
                :label="item.name"
                :value="item.type"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column width="170px" prop="subLenCode" label="基础规则术语类型">
        <template slot="header" slot-scope="scope">
          <div class="custom_table_header">基础规则术语类型</div>
        </template>
        <template slot-scope="scope">
          <el-form-item
            class="inp_box"
            :prop="`klRuleByIdSub[${scope.$index}].subLenCode`"
            :rules="rules.subLenCode"
          >
            <el-select
              :disabled="scope.row.disabled"
              v-model="scope.row.subLenCode"
              placeholder="请选择"
              :ref="`klRuleByIdSub[${scope.$index}].subLenCode`"
              @change="subCodeChange($event, scope.$index)"
            >
              <el-option
                v-for="item in scope.row.baseTermTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.code"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column width="170px" label="医学标准术语" prop="subConceptId">
        <template slot="header" slot-scope="scope">
          <div class="custom_table_header">医学标准术语</div>
        </template>
        <template slot-scope="scope">
          <el-form-item
            class="inp_box"
            :prop="`klRuleByIdSub[${scope.$index}].subConceptId`"
            :rules="rules.subConceptId"
          >
            <el-select
              clearable
              remote
              filterable
              :disabled="scope.row.disabled"
              @focus="subConceptIdfocus(scope.$index)"
              :remote-method="searchConcept"
              v-model.trim="scope.row.subConceptId"
              :ref="`klRuleByIdSub[${scope.$index}].subConceptId`"
            >
              <el-option
                v-for="item in scope.row.conceptList"
                :key="item.conceptId"
                :label="item.conceptName"
                :value="item.conceptId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="规则具体内容" min-width="900px" prop="">
        <template slot-scope="scope">
          <div class="type_content">
            <el-form-item
              style="width: 100px; margin-right: 20px"
              :prop="`klRuleByIdSub[${scope.$index}].dataType`"
              :rules="rules.dataType"
              v-if="scope.row.subType === 2 && showDataType(scope.$index)"
            >
              <el-select
                v-model="scope.row.dataType"
                placeholder="选择类型"
                @change="dataTypeChange($event, scope.$index)"
                :ref="`klRuleByIdSub[${scope.$index}].dataType`"
              >
                <el-option label="数值类型" value="1"> </el-option>
                <el-option label="文本类型" value="2"> </el-option>
              </el-select>
            </el-form-item>
            <!-- v-if="klRuleByIdSub[scope.$index].dataType === '1'" -->
            <el-form-item
              class="type_content_item type_content_item1"
              style="flex: 2; margin: 0 10px"
              label="最大值："
              v-if="scope.row.dataType === '1'"
            >
              <!-- <div> -->
              <el-row :gutter="10" class="row_box">
                <el-col :span="6">
                  <el-form-item
                    :prop="`klRuleByIdSub[${scope.$index}].subMaxOperator`"
                    :rules="[
                      {
                        validator: (rule, value, callback) => {
                          subMaxOperator(scope, rule, value, callback);
                        },
                        trigger: ['blur']
                      }
                    ]"
                  >
                    <el-select
                      v-model="scope.row.subMaxOperator"
                      placeholder="请选择"
                      clearable
                      :ref="`klRuleByIdSub[${scope.$index}].subMaxOperator`"
                    >
                      <el-option
                        v-for="item in operMaxList"
                        :key="item.key"
                        :label="item.name"
                        :value="item.key"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item
                    :prop="`klRuleByIdSub[${scope.$index}].subMaxValue`"
                    :rules="[
                      {
                        validator: (rule, value, callback) => {
                          subMaxValue(scope, rule, value, callback);
                        },
                        trigger: ['blur']
                      }
                    ]"
                  >
                    <el-input
                      type="text"
                      v-model="scope.row.subMaxValue"
                      placeholder="填写数值"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item
                    :prop="`klRuleByIdSub[${scope.$index}].subMaxUnit`"
                    :rules="rules.subMaxUnit"
                  >
                    <el-input
                      type="text"
                      v-model.trim="scope.row.subMaxUnit"
                      placeholder="填写单位"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- </div> -->
            </el-form-item>
            <el-form-item
              class="type_content_item type_content_item1"
              style="flex: 2"
              label="最小值："
              v-if="scope.row.dataType === '1'"
            >
              <el-row :gutter="10" class="row_box">
                <el-col :span="6">
                  <el-form-item
                    :prop="`klRuleByIdSub[${scope.$index}].subMinOperator`"
                    :rules="[
                      {
                        validator: (rule, value, callback) => {
                          subMinOperatorRule(scope, rule, value, callback);
                        },
                        trigger: ['blur']
                      }
                    ]"
                  >
                    <el-select
                      v-model="scope.row.subMinOperator"
                      placeholder="请选择"
                      clearable
                      :ref="`klRuleByIdSub[${scope.$index}].subMinOperator`"
                    >
                      <el-option
                        v-for="item in operMinList"
                        :key="item.name"
                        :label="item.name"
                        :value="item.name"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item
                    :prop="`klRuleByIdSub[${scope.$index}].subMinValue`"
                    :rules="[
                      {
                        validator: (rule, value, callback) => {
                          subMinValueRule(scope, rule, value, callback);
                        },
                        trigger: ['blur']
                      }
                    ]"
                  >
                    <el-input
                      type="text"
                      v-model="scope.row.subMinValue"
                      placeholder="填写数值"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item
                    :prop="`klRuleByIdSub[${scope.$index}].subMinUnit`"
                    :rules="rules.subMinUnit"
                  >
                    <el-input
                      type="text"
                      v-model.trim="scope.row.subMinUnit"
                      placeholder="填写单位"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>
            <!-- v-if="klRuleByIdSub[scope.$index].subType !== 6 && klRuleByIdSub[scope.$index].dataType === '2'" -->
            <el-form-item
              class="type_content_item"
              style="flex: 2"
              v-show="scope.row.subType !== 6 && scope.row.dataType === '2'"
              label="医学内容："
              label-width="100px"
              :prop="`klRuleByIdSub[${scope.$index}].subEqValue`"
              :rules="[
                {
                  required: true,
                  message: '请输入' + textName(scope.$index),
                  trigger: 'blur'
                },
                {
                  validator: (rule, value, callback) => {
                    subEqValue(scope, rule, value, callback);
                  },
                  trigger: 'blur'
                }
              ]"
            >
              <el-input
                type="textarea"
                rows="1"
                placeholder="请输入医学内容"
                v-model.trim="scope.row.subEqValue"
              ></el-input>
            </el-form-item>
            <!-- v-if="groupData.subType === 6" -->
            <el-form-item
              class="type_content_item"
              label="正则表达式："
              label-width="120px"
              style="flex: 2"
              v-show="scope.row.subType === 6"
              :prop="`klRuleByIdSub[${scope.$index}].subEqValue1`"
              :rules="[
                {
                  required: true,
                  message: '请输入' + textName(scope.$index),
                  trigger: 'blur'
                },
                {
                  validator: (rule, value, callback) => {
                    subEqValue(scope, rule, value, callback);
                  },
                  trigger: 'blur'
                }
              ]"
            >
              <el-input
                type="textarea"
                rows="1"
                placeholder="请输入正则表达式"
                v-model.trim="scope.row.subEqValue"
              ></el-input>
            </el-form-item>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import api from "@api/knowledgeLib.js";
import { tableRules } from "./rules";
export default {
  name: "AddNewRuleTable",
  data() {
    return {
      numTypes: "",
      subConceptIdIndex: "",
      operMaxList: [
        { name: "<=", key: "<=" },
        { name: "<", key: "<" }
      ],
      operMinList: [
        { name: ">", key: ">" },
        { name: ">=", key: ">=" }
      ],
      rules: tableRules
    };
  },
  methods: {
    addGroup(scope) {
      this.$emit("addGroup", null, { groupId: scope.row.groupId });
      this.$refs.table.bodyWrapper.scrollLeft = 0;
    },
    addChildGroup(scope) {
      this.$emit("addGroup", scope.row.groupId, { index: scope.$index });
      this.$refs.table.bodyWrapper.scrollLeft = 0;
    },
    // table 隔行换色
    // rowStyle({ row }) {
    //   if (row.rowIndex % 2 == 0) {
    //     return {
    //       background: "#DFF7EF"
    //     };
    //   }
    // },
    // cellStyle
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (column.label == "组" || column.label == "基础规则") return {};
      return { "vertical-align": "top", "padding-top": "14px" };
    },
    // 最大值 选择rule
    subMaxOperator(scope, rule, value, callback) {
      const { subMaxValue, subMinOperator, subMinValue } = scope.row;
      const val = value + subMinOperator + subMinValue + subMaxValue;
      if (!val || (!value && subMaxValue !== "")) {
        callback(new Error("最大值和最小值至少完整填写一个，单位不必填"));
      } else {
        callback();
      }
    },
    // 最大值 数值rule
    subMaxValue(scope, rule, value, callback) {
      const { subMaxOperator, subMinOperator, subMinValue } = scope.row;
      const val = value + subMaxOperator + subMinValue + subMinOperator;
      const isNum = /^(\-|\+)?\d+(\.\d+)?$/.test(value);
      if (!val || (value == "" && subMaxOperator)) {
        callback(new Error("最大值和最小值至少完整填写一个，单位不必填"));
      } else if (value !== "" && !isNum) {
        callback(new Error("只能输入数字"));
      } else {
        callback();
      }
    },
    // 最小值 选择rule
    subMinOperatorRule(scope, rule, value, callback) {
      const { subMaxValue, subMaxOperator, subMinValue } = scope.row;
      const val = value + subMaxOperator + subMinValue + subMaxValue;
      if (!val || (!value && subMinValue !== "")) {
        callback(new Error("最大值和最小值至少完整填写一个，单位不必填"));
      } else {
        callback();
      }
    },
    // 最小值 数值rule
    subMinValueRule(scope, rule, value, callback) {
      const { subMaxValue, subMinOperator, subMaxOperator } = scope.row;
      const val = value + subMaxOperator + subMaxValue + subMinOperator;
      const isNum = /^(\-|\+)?\d+(\.\d+)?$/.test(value);
      if (!val || (value == "" && subMinOperator)) {
        callback(new Error("最大值和最小值至少完整填写一个，单位不必填"));
      } else if (value !== "" && !isNum) {
        callback(new Error("只能输入数字"));
      } else {
        callback();
      }
    },
    // 医学内容rule
    subEqValue(scope, rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入" + this.textName(scope.$index)));
      } else if (value.length > 200) {
        callback(new Error(this.textName(scope.$index) + "不能超过200字"));
      } else {
        callback();
      }
    },
    // 判断是否为最后一条规则
    isLastDate(id) {
      const tableLength = this.klRuleByIdSub.filter(
        (item) => item.groupId !== id
      ).length;
      return tableLength === 0;
    },
    // 是否超出最大规则数
    isMax(id) {
      const typeNum = this.klRuleByIdSub.filter((item) => item.groupId === id)
        .length;
      return typeNum >= this.maxNum;
    },
    // 基础规则类型选择
    subTypeChange(e, index) {
      this.$emit("subTypeChange", e, index);
    },
    // 规则术语类型
    subCodeChange(val, index) {
      //基础规则术语类型修改
      if ((this.numTypes + ",").indexOf(val + ",") > -1) {
        this.klRuleByIdSub[index].dataType = "1";
      } else {
        this.klRuleByIdSub[index].dataType = "";
      }
      this.clearConcept(index);
      this.clearNumText(index);
    },
    clearConcept(index) {
      this.klRuleByIdSub[index].subConceptId = "";
      this.klRuleByIdSub[index].conceptList = [];
    },
    clearNumText(index) {
      let obj = JSON.parse(JSON.stringify(this.klRuleByIdSub));


      obj[index].subMaxOperator = "";
      obj[index].subMaxValue = "";
      obj[index].subMaxUnit = "";
      obj[index].subMinOperator = "";
      obj[index].subMinValue = "";
      obj[index].subMinUnit = "";
      obj[index].subEqValue = "";
      // this.$set(obj[index], "subEqValue", "");
      obj[index].subEqOperator = "";
      // this.klRuleByIdSub = obj;
      this.$emit('editKlRuleByIdSub',obj)
    },
    //医学标准术语change
    subConceptIdfocus(index) {
      this.subConceptIdIndex = "";
      this.subConceptIdIndex = index;
    },
    // 医学标准术语
    searchConcept(val) {
      const param = {
        excludedConceptIds: [
          this.klRuleByIdSub[this.subConceptIdIndex].subType
        ],
        libType: this.klRuleByIdSub[this.subConceptIdIndex].subLenCode,
        name: val
      };
      api
        .searchConcept(param)
        .then((res) => {
          if (res.data.code == "0") {
            const data = res.data.data;
            this.$emit("setFormData", this.subConceptIdIndex, data);
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    dataTypeChange(val, index) {
      console.log(val,index);
      this.klRuleByIdSub[index].subEqOperator = val === "2" ? "=" : "";
      this.clearNumText(index);
      // TODO 新增的内容追踪不到
      //delete this.klRuleByIdSub[index].dataType; //触发更新
      this.$set(this.klRuleByIdSub[index], "dataType", val);
    },
    // 处理要合并相同行的列
    getSpanArr(data) {
      this.spanArr = [];
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          // 如果是第一条记录（即索引是0的时候），向数组中加入１
          /** *
           * 例子：
           * name:1
           * name:1
           * name:2
           * name:2
           * 最终结果：spanArr = [2,0,2,0]
           */
          this.spanArr.push(1);
          this.pos = 0;
        } else {
          if (data[i].groupId === data[i - 1].groupId) {
            // 如果remark相等就累加，并且push 0
            this.spanArr[this.pos] += 1;
            this.spanArr.push(0);
          } else {
            // 不相等push 1,并且pos 要换成当前下标
            this.spanArr.push(1);
            this.pos = i;
          }
        }
      }
    },
    // 合并单元格
    ObjectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex == 0) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    },
    showDataType(index) {
      return (
        (this.numTypes + ",").indexOf(
          this.klRuleByIdSub[index].subLenCode + ","
        ) === -1
      );
    },
    textName(index) {
      return this.klRuleByIdSub[index].subType !== 6 &&
        this.klRuleByIdSub[index].dataType === "2"
        ? "医学内容"
        : "正则表达式";
    }
  },
  components: {},
  created() {
    this.numTypes = localStorage.getItem("zskNumDict");
    this.getSpanArr(this.klRuleByIdSub);
  },
  beforeUpdate() {
    this.getSpanArr(this.klRuleByIdSub);
  },
  mounted() {},
  // beforeUpdate() {
  //   this.getSpanArr(this.klRuleByIdSub);
  //   console.log("boxxxxxxx", this.box);
  //   // if (this.box) {
  //   //   this.box.removeEventListener("scroll");
  //   // }
  //   // console.log(box);
  //   // if (!this.box) {
  //     this.box = document.querySelector(".el-table__body-wrapper");
  //   // }

  //   let that = this;
  //   this.box.addEventListener("scroll", function (e) {
  //     console.log(that.klRuleByIdSub.length);
  //     console.log('subType',that.$refs[`klRuleByIdSub[1].subType`]);
  //     that.klRuleByIdSub.forEach((ite, index) => {
  //       // console.log(
  //       //   that.$refs[`klRuleByIdSub[${index}].subType`],
  //       //   that.$refs[`klRuleByIdSub[${index}].subLenCode`],
  //       //   that.$refs[`klRuleByIdSub[${index}].subConceptId`],
  //       //   that.$refs[`klRuleByIdSub[${index}].subMaxOperator`],
  //       //   that.$refs[`klRuleByIdSub[${index}].subMinOperator`],
  //       //   that.$refs[`klRuleByIdSub[${index}].subMinOperator`]
  //       // );
  //       that.$refs[`klRuleByIdSub[${index}].subType`] &&
  //         that.$refs[`klRuleByIdSub[${index}].subType`].blur();
  //       that.$refs[`klRuleByIdSub[${index}].subLenCode`] &&
  //         that.$refs[`klRuleByIdSub[${index}].subLenCode`].blur();
  //       that.$refs[`klRuleByIdSub[${index}].subConceptId`] &&
  //         that.$refs[`klRuleByIdSub[${index}].subConceptId`].blur();
  //       that.$refs[`klRuleByIdSub[${index}].dataType`] &&
  //         that.$refs[`klRuleByIdSub[${index}].dataType`].blur();
  //       that.$refs[`klRuleByIdSub[${index}].subMaxOperator`] &&
  //         that.$refs[`klRuleByIdSub[${index}].subMaxOperator`].blur();
  //       that.$refs[`klRuleByIdSub[${index}].subMinOperator`] &&
  //         that.$refs[`klRuleByIdSub[${index}].subMinOperator`].blur();
  //       that.$refs[`klRuleByIdSub[${index}]subMinOperator`] &&
  //         that.$refs[`klRuleByIdSub[${index}]subMinOperator`].blur();
  //     });
  //   });
  // },
  updated() {},
  props: {
    klRuleByIdSub: {
      type: Array,
      required: true
    },
    maxNum: {
      default: null
    }
  }
};
</script>

