<template>
  <div>
    <crumbs
      :title="title"
      :param="$route.params"
      linkTo="ZskRuleManager"
    ></crumbs>
    <div class="contents">
      <div class="content2">
        <el-form
          ref="form"
          :label-position="labelPosition"
          class="add-new-form"
          label-width="130px"
          :model="form"
          :rules="rules"
        >
          <div class="table_header">
            <el-form-item label="规则名称：" prop="parDescription">
              <el-input v-model.trim="form.parDescription"></el-input>
            </el-form-item>
            <el-form-item label="规则类型：" prop="parRuleType">
              <el-select
                v-model="form.parRuleType"
                placeholder="请选择"
                size="small"
                @change="ruleTypeChange"
              >
                <el-option
                  v-for="item in ruleTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
              <div class="tip-text">
                注：更改规则类型，将会清空已填写的规则内容~
              </div>
            </el-form-item>
            <el-form-item label="规则术语类型：" prop="parLenCode">
              <el-select
                v-model="form.parLenCode"
                placeholder="请选择"
                size="small"
                @change="ruleTermChange"
              >
                <el-option
                  v-for="item in ruleTermTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.code"
                >
                </el-option>
              </el-select>
              <div class="tip-text">
                注：更改规则术语类型，将会清空已填写的规则内容~
              </div>
            </el-form-item>
            <el-form-item
              class="addDepartFormItem"
              label="医学标准术语："
              prop="parConceptId"
            >
              <el-select
                clearable
                filterable
                remote
                :remote-method="searchConcept"
                v-model.trim="form.parConceptId"
              >
                <el-option
                  v-for="item in conceptList"
                  :key="item.conceptId"
                  :label="item.conceptName"
                  :value="item.conceptId"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="showHasSub"
              label="有无子条件："
              prop="parHasSub"
            >
              <el-select
                v-model="form.parHasSub"
                placeholder="请选择"
                size="small"
                @change="hasSubChange"
              >
                <el-option
                  v-for="item in hasSub"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="showMsg"
              label="附加信息："
              prop="parMsg"
              class="parMsg"
              style="flex: 1"
            >
              <el-input
                type="textarea"
                :rows="3"
                placeholder="请输入附加信息"
                v-model.trim="form.parMsg"
              ></el-input>
            </el-form-item>
          </div>

          <el-form-item
            v-if="form.parHasSub === 1"
            prop="remind"
            label-width="0"
            class="discDesc"
          >
            <h4>规则内容</h4>
            <SubRulesGroup
              v-for="(group, i) in subGroups"
              ref="groups"
              :key="i"
              :data="group"
              :baseTypes="baseTypeList"
              :inx="i"
              :maxNum="subRuleMaxNum"
              :firstPlace="firstPlace"
              :isLast="subGroups.length === 1"
              @addGroup="addGroup"
              @delGroup="delGroup"
            ></SubRulesGroup>
          </el-form-item>
          <el-button
            class="disclButn"
            size="small"
            type="primary"
            @click="confirm"
            >保存</el-button
          >
        </el-form>
      </div>
    </div>
  </div>
</template>
<script type="text/javascript">
import api from "@api/knowledgeLib.js";
import SubRulesGroup from "./SubRulesGroup";
import ComTable from "./table";
export default {
  name: "AddRule",
  data() {
    return {
      labelPosition: "left",
      isFirst: true,
      isCopy: false,
      dict: "", //规则内容固定的类型
      msgDict: "", //显示附加信息的类型
      title: "规则维护-添加规则",
      ruleTermTypeList: [],
      ruleTypeList: [],
      conceptList: [],
      baseTypeList: [],
      conceptName: "",
      subRuleMaxNum: null, //规则内容中规则的限制个数
      firstPlace: null,
      subGroups: [
        [
          {
            subDescription: "",
            parRuleType: "",
            subConceptId: "",
            subType: "",
            subMaxOperator: "",
            subMaxUnit: "",
            subMaxValue: "",
            subMinOperator: "",
            subMinUnit: "",
            subMinValue: "",
            subEqValue: "",
            subLenCode: "",
            dataType: ""
          }
        ]
      ],
      form: {
        parDescription: "",
        parRuleType: "",
        parConceptId: "",
        parlibName: "",
        parLenName: "",
        parHasSub: undefined,
        parLenCode: "",
        parMsg: "",
        klRuleInfoSaveSub: []
      },
      parId: null,
      rules: {
        parDescription: [
          { required: true, message: "请输入规则名称", trigger: ["blur"] },
          {
            validator: (rule, value, callback) => {
              if (value.length > 100) {
                callback(new Error("规则名称不能超过100字"));
              } else {
                callback();
              }
            },
            trigger: "change"
          }
        ],
        parRuleType: [
          { required: true, message: "请选择规则类型", trigger: ["change"] }
        ],
        parLenCode: [
          { required: true, message: "请选择规则术语类型", trigger: ["change"] }
        ],
        parConceptId: [
          { required: true, message: "请输入医学标准术语", trigger: ["blur"] }
        ],
        parHasSub: [
          { required: true, message: "请选择有无子条件", trigger: ["change"] }
        ],
        parMsg: [
          { required: true, message: "请输入附加信息", trigger: ["change"] },
          {
            validator: (rule, value, callback) => {
              if (value.length > 100) {
                callback(new Error("附加信息不能超过100字"));
              } else {
                callback();
              }
            },
            trigger: "change"
          }
        ]
      },
      hasSub: [
        { name: "有", id: 1 },
        { name: "无", id: 0 }
      ]
    };
  },
  updated() {
    console.log(JSON.stringify(this.subGroups));
  },
  created() {
    this.getTypeList();
    this.setDict();
    const param = this.$route.params;
    let info = param.data;
    if (info) {
      this.parId = info.parId;
      this.isCopy = param.copy;
      this.title = "规则维护-" + (this.isCopy ? "复制" : "修改") + "规则";
      this.form = Object.assign({}, this.form, info);
      this.conceptList = [
        { conceptName: this.form.parlibName, conceptId: this.form.parConceptId }
      ];
      this.subGroups = this.formatGroupDatas(info.klRuleByIdSub);
    }
  },
  watch: {
    "form.parRuleType": function (val) {
      const obj = this.ruleTypeList.find((it) => it.id === val);
      this.ruleTermTypeList = obj.subMenuList;
    },
    "form.parLenCode": function (val) {
      if (!val) {
        this.baseTypeList = [];
        return;
      }
      const obj = this.ruleTermTypeList.find((it) => it.code === val);
      this.baseTypeList = obj.subMenuList;
      this.subRuleMaxNum = obj.number;
    },
    "form.parConceptId": function (val) {
      if (val && this.checkFirstPlace && this.conceptList) {
        this.firstPlace = this.conceptList.find((it) => it.conceptId === val);
        this.firstPlace["checkedType"] = this.ruleTermCodeStr;
      } else if (!val) {
        this.setInitGroupData();
        this.firstPlace = null;
      } else {
        this.firstPlace = null;
      }
    }
  },
  components: {
    SubRulesGroup,
    ComTable
  },
  computed: {
    ruleTermCodeStr: function () {
      return this.form.parRuleType + "-" + this.form.parLenCode;
    },
    checkFirstPlace: function () {
      return this.dict.indexOf(this.ruleTermCodeStr) > -1;
    },
    showMsg: function () {
      return (
        this.ruleTermCodeStr.length > 1 &&
        this.msgDict.indexOf(this.ruleTermCodeStr) > -1
      );
    },
    showHasSub: function () {
      return this.subDict.indexOf(this.ruleTermCodeStr) > -1;
    }
  },
  methods: {
    hasSubChange(val) {
      if (val) {
        this.subGroups = [
          [
            {
              subDescription: "",
              parRuleType: "",
              subConceptId: "",
              subType: "",
              subMaxOperator: "",
              subMaxUnit: "",
              subMaxValue: "",
              subMinOperator: "",
              subMinUnit: "",
              subMinValue: "",
              subEqValue: "",
              subLenCode: "",
              dataType: ""
            }
          ]
        ];
      }
    },
    setDict() {
      this.dict = localStorage.getItem("zskDicts");
      this.msgDict = localStorage.getItem("zskMsgDict");
      this.subDict = localStorage.getItem("zskSubDict");
    },
    showConfirmDialog(msg, resolve) {
      this.$alert(msg, "提示", {
        confirmButtonText: "确定",
        type: "warning"
      })
        .then(() => {
          resolve();
        })
        .catch(() => {});
    },
    formatGroupDatas(data) {
      let arr = [];
      data.map((it) => {
        if (!arr[it.groupType]) {
          arr[it.groupType] = [];
        }
        if (it.subMaxOperator || it.subMinOperator) {
          it.dataType = "1";
        } else if (it.subEqValue) {
          it.dataType = "2";
        }
        arr[it.groupType].push(it);
      });
      arr = arr.filter((it) => {
        if (it) return it;
      });
      return arr;
    },
    searchConcept(val) {
      const param = {
        excludedConceptIds: [this.form.parRuleType],
        libType: this.form.parLenCode,
        name: val
      };
      api
        .searchConcept(param)
        .then((res) => {
          if (res.data.code == "0") {
            const data = res.data.data;
            this.conceptList = data;
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    ruleTypeChange(val) {
      //规则类型选中
      this.form.parRuleType = val;
      this.form.parLenCode = "";
      this.form.parMsg = "";
      const obj = this.ruleTypeList.find((it) => it.id === val); //console.log(val)
      this.ruleTermTypeList = obj.subMenuList;
      this.setInitGroupData();
    },
    ruleTermChange(val) {
      //规则术语类型选中
      this.form.parLenCode = val;
      this.form.parMsg = "";
      const obj = this.ruleTermTypeList.find((it) => it.code === val);
      this.form.parLenName = obj.name;
      this.baseTypeList = obj.subMenuList;
      this.subRuleMaxNum = obj.number;
      this.setInitGroupData();
      this.form.parHasSub = obj.subMenuList.length ? 1 : 0;
    },
    getTypeList() {
      const typeListData = JSON.parse(localStorage.getItem("zskTypesList"));
      this.ruleTypeList = typeListData;
    },
    setInitGroupData() {
      this.subGroups = [
        [
          {
            subDescription: "",
            parRuleType: "",
            subConceptId: "",
            subType: "",
            subMaxOperator: "",
            subMaxUnit: "",
            subMaxValue: "",
            subMinOperator: "",
            subMinUnit: "",
            subMinValue: "",
            subEqValue: "",
            subLenCode: "",
            dataType: ""
          }
        ]
      ];
      this.form.parConceptId = ""; //医学标准术语清空
      this.conceptList = []; //下拉列表清空
    },
    addGroup() {
      let temp = {
        subDescription: "",
        subConceptId: "",
        subType: "",
        subLenCode: "",
        dataType: "",
        subMaxOperator: "",
        subMaxUnit: "",
        subMaxValue: "",
        subMinOperator: "",
        subMinUnit: "",
        subMinValue: "",
        subEqValue: ""
      };
      if (this.checkFirstPlace) {
        const obj = this.subGroups[0][0];
        temp = {
          subDescription: obj.subConceptName,
          subConceptId: obj.subConceptId,
          subConceptName: obj.subConceptName,
          subLenCode: this.form.parLenCode,
          subLenName: this.form.parLenName,
          subLibName: this.form.parlibName,
          subType: obj.subType,
          dataType: "",
          subMaxOperator: "",
          subMaxUnit: "",
          subMaxValue: "",
          subMinOperator: "",
          subMinUnit: "",
          subMinValue: "",
          subEqValue: ""
        };
      }
      this.subGroups.push([temp]);
    },
    delGroup(i) {
      //this.subGroups.splice(i,1);
      this.$set(this.subGroups, i, null);
    },
    saveRule(params) {
      api.saveRule(params).then((res) => {
        if (res.data.code == 0) {
          this.$message({
            message: "操作成功",
            type: "success"
          });
          this.$router.push({
            name: "ZskRuleManager",
            params: Object.assign({}, this.$route.params, { currentPage: 1 })
          });
        } else {
          this.$message({
            message: res.data.msg,
            type: "warning"
          });
        }
      });
    },
    formatGroups() {
      let obj = [];
      this.subGroups.map((item, i) => {
        item &&
          item.map((it) => {
            obj.push({ ...it, groupType: i + 1 });
          });
      });
      return obj;
    },
    validateForms(callBack) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const groupsRef = this.$refs["groups"];
          if (!groupsRef || groupsRef.length === 0) {
            callBack();
            return;
          }
          let groupRef = null,
            goOn = true;
          for (let i = 0; i < groupsRef.length; i++) {
            groupRef = groupsRef[i].$refs["group"];
            for (let j = 0; j < groupRef.length; j++) {
              groupRef[j].$refs["groupData"].validate((valid) => {
                if (!valid) {
                  goOn = false;
                }
              });
            }
          }
          if (goOn) {
            callBack();
          }
        } else {
          return false;
        }
      });
    },
    confirm() {
      const _this = this;
      this.validateForms(function () {
        delete _this.form.klRuleByIdSub;
        _this.form.klRuleInfoSaveSub = _this.form.parHasSub
          ? _this.formatGroups()
          : undefined;
        let params = _this.form;
        if (_this.parId) {
          //修改/复制
          params = Object.assign({}, _this.form, {
            parId: _this.isCopy ? undefined : _this.parId,
            parStatus: _this.isCopy ? 1 : _this.form.parStatus
          });
        }
        console.log(params);
        _this.saveRule(params);
      });
    }
  }
};
</script>
<style lang="less" scoped>
@import "../../less/admin.less";
.content2 {
  background-color: #dee2ea;
  // padding: 20px 20px 30px;
  //   padding: 20px 20px 50px;
  color: #545455;
  min-width: 980px;
  position: relative;
  .tip-text {
    color: #f56c6c;
    font-size: 12px;
    margin-left: -80px;
  }
  .conceptItem {
    padding: 0 10px;
    cursor: pointer;
    height: 32px;
    line-height: 32px;
    &:hover {
      background: #ebedf1;
    }
  }
  .discDesc {
    margin-bottom: 20px;
  }
  .disclButn {
    position: absolute;
    right: 80px;
    bottom: 10px;
  }
}
.add-new-form {
  .el-form-item__label {
    text-align: right;
  }
  .addDepartFormItem {
    position: relative;
  }
  .itemList {
    position: absolute;
    // display: none;
    background: #fff;
    width: 188px;
    max-height: 160px;
    border: 1px solid #dcdfe6;
    left: 0;
    top: 37px;
    z-index: 2;
    overflow-y: auto;
  }
  .indexList {
    left: 42px;
    top: 78px;
  }
  .el-input__prefix,
  .el-input__suffix {
    /*top:-2px;*/
    right: 3px;
  }
  .el-input--suffix .el-input__inner {
    padding-right: 22px;
  }
  .el-input,
  .el-input__inner {
    width: 190px;
    line-height: 32px;
    height: 32px;
  }
  .el-input__icon {
    line-height: 32px;
  }
}
.table_header {
  background: #fff;
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
}
</style>