<template>
  <div class="app-container">
    <CustomCard :show-save="type!==4" :show-cancel="true" :label="initTitle" @Confirm="Confrim" @cancel="cancel">
      <CustomForm ref="basicInfo" :value="basicInfo" :disabled="type===4">
        <CustomInput label="relatedCase.caseName" prop="caseName" required/>
        <CustomSelect :data="dict['logic_operation']" :label="$t('relatedCase.relationship')" prop="relationship"
                      required/>
      </CustomForm>

      <Row>
        <ElevatorModelTable :span="24" :sm-span="24" :lg-span="24" :md-span="24" :xs-span="24" :disabled="type===4"
                            ref="relationEnters" :modal-data="relationEnters"
                            @handleConfirm="handleModelTableConfirm"
                            @handleDeleteRow="val=>basicInfo.deleteRelationEnterIds=val"/>
      </Row>


      <Row>
        <Col>
          <RedHeaderLine :label="`1.${$t('relatedCase.relatedCase')}`"/>
          <EditTable ref="relatedLogic" :show-add="type!==4" :show-delete="type!==4" :disabled="type===4"
                     @deleteMore="val=>relatedDeleteMore(val,1)">
            <CustomColumn label="No" type="index" :min-width="20"/>
            <CustomColumn type="selection" :min-width="20"/>
            <RemoteSelectColumn :label="$t('relatedCase.paramsProject')"
                                label-prop="paraName"
                                value-prop="paraName"
                                prop="paraName"
                                set-label-value-prop="paraCode"
                                set-label-prop="paraCode"
                                query-label="query"
                                :query-param="{  language: $i18n.locale,
                                        relatedModel: selectedElevatorModelIds,
                                        modelCount: selectedElevatorModelIds.length,}"
                                :remote-method="getCommmonPara"
                                @clear=" val=> handleRemoteClear(val,1)"
                                @change="val=> handleParamSelect(val,1)"

                                :required="type!==4"/>
            <CustomSelectColumn :label="$t('relatedCase.operation')" prop="operation" :data="relationOptions"
                                :required="type!==4"/>
            <CustomFormItemColumn :label="$t('relatedCase.value')" prop="value" :required="type!==4"/>
          </EditTable>
        </Col>

        <Col>
          <RedHeaderLine :label="`2.${$t('relatedCase.relatedResult')}`"/>
          <EditTable ref="relatedAction" @deleteMore="val=>relatedDeleteMore(val,2)" :show-add="type!==4"
                     :show-delete="type!==4" :disabled="type===4">
            <CustomColumn label="No" :min-width="20" type="index"/>
            <CustomColumn type="selection" :min-width="20"/>
            <RemoteSelectColumn :label="$t('relatedCase.paramsProject')"
                                label-prop="paraName"
                                value-prop="paraName"
                                prop="paraName"
                                set-label-value-prop="paraCode"
                                set-label-prop="paraCode"
                                query-label="query"
                                :query-param="{  language: $i18n.locale,
                                        relatedModel: selectedElevatorModelIds,
                                        modelCount: selectedElevatorModelIds.length,}"
                                :remote-method="getCommmonPara"
                                @clear=" val=> handleRemoteClear(val,2)"
                                @change="val=> handleParamSelect(val,2)"
                                :required="type!==4"/>
            <CustomFormItemColumn multiple :label="$t('relatedCase.optionValue')" @change="handleOptionSelect"
                                  :showFunction="(row)=>{
                                    return  row.computedFlag !='1'&& row.inputType =='02'
                                  }"
                                  @clear="handleOptionClear" prop="selectItem"/>
            <CustomFormItemColumn :label="$t('relatedCase.value')" row-option-prop="valueOptions" prop="value"
                                  :show-function="(row)=>{
                                    return row.computedFlag !='1'
                                  }"/>

            <CustomSwitchColumn :label="$t('relatedCase.computedFlag')" @change="handleComputedChange"
                                prop="computedFlag" active-value="1" in-active-value="0"/>
            <CustomSwitchColumn :label="$t('relatedCase.editable')" prop="editable" />

<!--            :required="type!==4"-->
          </EditTable>
        </Col>
      </Row>
    </CustomCard>


    <el-drawer ref="rowComputedSetting" :visible.sync="rowComputedSettingShow">
      <CustomCard :show-header="false" style="margin-top: 1%">
        <Row>
          <Col>
            <div class="picker">
              <Row style="width: 100%">
                <Col>
                  <el-tabs @tab-click="handleTabClick">
                    <el-tab-pane v-for="(item ,index) in paramsTypeList" :key="index"
                                 :label="initTypeNames(item)">
                      <Row style="margin-bottom: 1%" :gutter="20">
                        <Col v-for="(commonParam) in commonParamsList" :span="8" class="paramButton"
                             v-if="index===0">
                          <el-button icon="el-icon-menu" @click="insertContent(commonParam.paramName, 'variable')"
                                     :disabled="type===4">
                            <span style="color: #5DAAFD">{{ commonParam.paramName }}</span>
                          </el-button>
                        </Col>

                        <Col v-for="(paramType,paramIndex) in paramsGroupByTypeList" :span="8" class="paramButton"
                             v-if="item!=='2'&& item !=='1'">
                          <el-button icon="el-icon-menu" @click="insertContent(paramType.name, 'variable')"
                                     :disabled="type===4">
                            <span style="color: #5DAAFD">{{ paramType.name }}</span>
                          </el-button>
                        </Col>
                        <Col v-for="(funcType,funcIndex) in funList" :span="6" class="paramButton" v-if="item==='2'">
                          <el-button icon="el-icon-menu" @click="insertContent(funcType.name, 'func')"
                                     :disabled="type===4">
                            <span style="color: #5DAAFD">{{ funcType.name }}</span>
                          </el-button>
                        </Col>
                        <Col v-for="(logicType,logicIndex) in logicOperation" :span="6" class="paramButton"
                             v-if="item==='2'">
                          <el-button icon="el-icon-menu" @click="insertContent(logicType.name, 'logic')"
                                     :disabled="type===4">
                            <span style="color: #5DAAFD">{{ logicType.name }}</span>
                          </el-button>
                        </Col>


                      </Row>
                    </el-tab-pane>

                  </el-tabs>
                </Col>

              </Row>
            </div>
          </Col>
        </Row>
      </CustomCard>

      <CustomCard :show-header="false" style="margin-top: 1%">
        <div class="code-edit">
          <ButtonTitle :label="$t('validation.formulaSetting')"
                       :customStyle="{background: '#F9FBFD',padding:'0 15px 0 15px',width:'100%',margin:'0 !important'}">
            <CustomButton label="validation.test" type="primary" @handleClick="getContent"/>
          </ButtonTitle>

          <CodeEdit
            ref="codeEditor"
            v-model="formulaStr"
            :options="cmOptions"
            @input="codeMirrorChange"
          ></CodeEdit>
        </div>
      </CustomCard>

      <Row style="position: fixed;bottom: 1%;right: 1%;">
        <Col>
          <CustomButton icon="el-icon-circle-check" label="common.confirm" @handleClick="drawerConfirm"/>
          <CustomButton icon="el-icon-remove-outline" label="common.cancel" @handleClick="drawerCancel"/>
        </Col>
      </Row>
    </el-drawer>


  </div>
</template>

<script>

import CustomCard from "../../../components/CustomElement/CustomCard.vue";
import CustomForm from "../../../components/CustomElement/CustomForm/CustomForm.vue";
import CustomInput from "../../../components/CustomElement/CustomForm/items/CustomInput.vue";
import CustomTable from "../../../components/CustomElement/CustomTable/CustomTable.vue";
import Col from "../../../components/CustomElement/layout/Col.vue";
import Row from "../../../components/CustomElement/layout/Row.vue";
import EditTable from "../../../components/CustomElement/CustomTable/EditTable.vue";
import CustomSelectColumn from "../../../components/CustomElement/CustomTable/CustomSelectColumn.vue";
import CustomColumn from "../../../components/CustomElement/CustomTable/CustomColumn.vue";
import FirstLevelHeader from "../../../components/element/firstLevelHeader.vue";
import CustomSwitchColumn from "../../../components/CustomElement/CustomTable/CustomSwitchColumn.vue";
import HeaderLine from "../../../components/element/HeaderLine.vue";
import RedHeaderLine from "../../../components/element/RedHeaderLine.vue";
import ElevatorModelTable from "../../components/ElevatorModelTable.vue";
import {getCommmonPara} from "../../../api/business/crm/parabar/parabar";
import CustomFormItemColumn from "../../../components/CustomElement/CustomTable/CustomFormItemColumn.vue";
import {isBlank} from "../../../utils/common";
import {getSelectItemListByParaId} from "../../../api/business/crm/paralibrary/selectItem";
import RemoteSelectColumn from "../../../components/CustomElement/CustomTable/RemoteSelectColumn.vue";
import CustomSelect from "../../../components/CustomElement/CustomForm/items/CustomSelect.vue";
import {mapGetters} from "vuex";
import {getInfoCase, saveOrUpdateCase} from "../../../api/business/crm/paraRelatedCase/relatedCase";
import {getCommonParamList} from "../../../api/business/crm/paraValidation/paraValidation";
import CustomButton from "../../../components/CustomElement/CustomButton.vue";
import ButtonTitle from "../../../components/CustomElement/ButtonTitle.vue";

import "codemirror/lib/codemirror.css";
import "codemirror/theme/idea.css";
import {codemirror as CodeEdit} from "vue-codemirror" ;
import yid from "yid";

export default {
  components: {
    CodeEdit,
    ButtonTitle, CustomButton,
    CustomSelect,
    RemoteSelectColumn,
    CustomFormItemColumn,
    ElevatorModelTable,
    RedHeaderLine,
    HeaderLine,
    CustomSwitchColumn,
    FirstLevelHeader,
    CustomColumn, CustomSelectColumn, EditTable, Row, Col, CustomTable, CustomInput, CustomForm, CustomCard
  },
  data() {
    return {
      basicInfo: {},
      type: null,
      relationEnters: [],
      paramsList: [],
      selectedElevatorModelIds: [],
      relationOptions: [
        {
          label: '=',
          value: '00',
        },
        {
          label: '>',
          value: '01',
        },
        {
          label: '<',
          value: '02',
        },

        {
          label: '>=',
          value: '03',
        }, {
          label: '<=',
          value: '04',
        },
        {
          label: this.$t('relatedCase.include'),
          value: '05',
        },
        {
          label: this.$t('relatedCase.noInclude'),
          value: '06',
        },
      ],
      paramsTypeList: [],
      commonParamsList: [],
      paramsGroupByTypeList: [],
      logicOperation: [
        {
          name: 'AND',
          value: '&&'
        },
        {
          name: 'OR',
          value: '||'
        }
      ],
      funList: [
        {
          name: 'SUM',
          value: 'SUM_FUNC'
        },
        {
          name: 'IF',
          value: 'IF_FUNC'

        },
        {
          name: 'IFS',
          value: 'IFS_FUNC'
        },
        {
          name: 'MAX',
          value: 'MAX_FUNC'
        },
        {
          name: 'MIN',
          value: 'MIN_FUNC'
        },
        {
          name: 'FIND',
          value: 'FIND_FUNC'
        }
      ],
      funKeyMap: {
        'SUM': 'SUM_FUNC',
        'IF': 'IF_FUNC',
        'MAX': 'MAX_FUNC',
        'MIN': 'MIN_FUNC',
        'FIND': 'FIND_FUNC',
        'IFS': 'IFS_FUNC'
      },
      logicKeyMap: {
        'AND': '&&',
        'OR': '||'
      },
      logicValueMap: {
        '&&': 'AND',
        '||': 'OR'
      },

      funValueMap: {
        'SUM_FUNC': 'SUM',
        'IF_FUNC': 'IF',
        'MAX_FUNC': 'MAX',
        'MIN_FUNC': 'MIN',
        'FIND_FUNC': 'FIND',
        'IFS_FUNC': 'IFS'
      },
      cmOptions: {
        // 语言及语法模式
        mode: 'text/javascript',
        // 主题
        theme: "idea",
        // 显示函数
        line: true,
        lineNumbers: false,
        // 软换行
        lineWrapping: true,
        // tab宽度
        tabSize: 4,
      },
      lang: 'javascript',
      formulaStr: "",
      formulaValueStr: "",
      formulaSettingForm: {},
      rowComputedSettingShow: false,
    };
  },
  computed: {
    ...mapGetters(["dict"]),
    initTitle() {
      switch (this.type) {
        case 1:
          return "relatedCase.addMenu";
        case 2:
          return "relatedCase.editMenu";
        case 4:
          return "relatedCase.viewMenu";
      }
    },
    editor() {
      return this.$refs.codeEditor.codemirror;
    },
  },
  watch: {
    relationEnters: {
      handler(val, oldVal) {
        if (val) {
          this.getCommonParams(val);
        }

      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    yid,
    sortByKey(array, key) {
      return array.sort(function (a, b) {
        var x = !isBlank(key) ? a[key] : a;
        var y = !isBlank(key) ? b[key] : b;
        return ((x > y) ? -1 : ((x < y) ? 1 : 0));
      });
    },

    async Confrim() {
      await this.$refs.basicInfo.validate();
      if (isBlank(this.relationEnters) || this.relationEnters.length === 0) {
        this.$message.warning(this.$t('validation.atLeastModel'))
        return;
      }
      if (isBlank(this.$refs.relatedLogic.records) || this.$refs.relatedLogic.records.length === 0) {
        this.$message.warning(this.$t('relatedCase.atLeastCase'))
        return;
      }
      if (isBlank(this.$refs.relatedAction.records) || this.$refs.relatedAction.records.length === 0) {
        this.$message.warning(this.$t('relatedCase.atLeastResult'))
        return;
      }
      let relatedLogic = JSON.parse(JSON.stringify(this.$refs.relatedLogic.records));
      let relatedAction = JSON.parse(JSON.stringify(this.$refs.relatedAction.records));

      await this.$refs.relatedLogic.validateTable();
      await this.$refs.relatedAction.validateTable();


      //内部不可重复
      let relatedLogicParamCode = relatedLogic.map(item => item.paraCode);
      let relatedLogicParamCodeMap = new Set(relatedLogicParamCode);
      if (relatedLogicParamCode.length !== relatedLogicParamCodeMap.size) {
        this.$message.warning(this.$t('relatedCase.logicCaseNoRepeat'))
        return;
      }
      let relatedActionParamCode = relatedAction.map(item => item.paraCode);
      let relatedActionParamCodeMap = new Set(relatedActionParamCode);
      if (relatedActionParamCode.length !== relatedActionParamCodeMap.size) {
        this.$message.warning(this.$t('relatedCase.actionNoRepeat'))
        return;
      }

      //二者不能重复
      for (let item of relatedLogicParamCode) {
        if (relatedActionParamCode.includes(item)) {
          this.$message.warning(this.$t('relatedCase.bothNoRepeat'))
          return;
        }
      }


      let row = {
        ...this.basicInfo,
        operationFlag: this.type,
        relationEnters: this.relationEnters,
        logicList: JSON.parse(JSON.stringify(relatedLogic)),
        actionList: JSON.parse(JSON.stringify(relatedAction))
      }
      for (let i = 0; i < row.actionList.length; i++) {
        if (row.actionList[i].inputType === '02'&&row.actionList[i].computedFlag!=="1") {
          if (isBlank(row.actionList[i].selectItem)) {
            let msg = row.actionList[i].paraName + this.$t('common.requiredMsg')
            this.$message.warning(msg);
            return;
          }
          let joinStr = row.actionList[i].selectItem.join(";")
          this.$set(row.actionList[i], 'selectItem', joinStr);
        } else {
          this.$set(row.actionList[i], 'selectItem', null);
        }
        if(row.actionList[i].computedFlag==="1"){
          //如果是计算属性 进行 code替换
          let formula = row.actionList[i].value
          //逻辑符号替换
          Object.keys(this.logicKeyMap).forEach(key => {
            let value = this.logicKeyMap[key];
            formula = formula.replaceAll(key, `${value}`);
          })
          //公式code替换
          Object.keys(this.funKeyMap).forEach(key => {
            let value = this.funKeyMap[key];
            formula = formula.replaceAll(key, `$@$${value}$@$`);
          })

          // 变量CODE替换
          let sortParamsList = [...this.paramsList];
          sortParamsList = this.sortByKey(sortParamsList, 'name');
          sortParamsList.forEach(item => {
            // 通过初始item 完全 匹配，并进行替换
            formula = formula.replaceAll(item.name, '$_$' + item.value + '$_$');
          })
          this.$set(row.actionList[i], 'value', formula);
        }
        if(typeof row.actionList[i].value == 'array'){
          row.actionList[i].value == ""
        }
      }

      saveOrUpdateCase(row).then(res => {
        if (res && res.code === 200) {
          let msg = this.type === 1 ? this.$t('common.addSuccess') : this.$t('common.editSuccess');
          this.$message.success(msg);
          this.$tab.closeOpenPage('/para/paramRelatedCase')
        }
      })


    },
    cancel() {
      this.$tab.closeOpenPage('/para/paramRelatedCase')
    },

    relatedDeleteMore(val, type) {
      if (type === 1) {
        this.basicInfo.logicDeleteIds = val.deleteItemIds
      } else {
        this.basicInfo.actionDeleteIds = val.deleteItemIds
      }

    },
    getCommmonPara,
    handleRemoteClear(val, type) {
      let {index} = val;
      if (type === 1) {
        this.$set(this.$refs.relatedLogic.records[index], 'selectItem', []);
        this.$set(this.$refs.relatedLogic.records[index], 'options', [])
        this.$set(this.$refs.relatedLogic.records[index], 'value', null);
        this.$set(this.$refs.relatedLogic.records[index], 'operation', null);
      } else {
        this.$set(this.$refs.relatedAction.records[index], 'selectItem', []);
        this.$set(this.$refs.relatedAction.records[index], 'options', [])
        this.$set(this.$refs.relatedAction.records[index], 'value', null);
      }


    },

    handleParamSelect(val, type) {
      let matchItem = val.val;
      let {index} = val.row;
      if (isBlank(matchItem)) {
      } else {
        if (type === 1) {
          this.$set(this.$refs.relatedLogic.records[index], 'inputType', matchItem.inputType);
        } else {
          this.$set(this.$refs.relatedAction.records[index], 'inputType', matchItem.inputType);
          this.$set(this.$refs.relatedAction.records[index], 'selectItem', []);
          this.$set(this.$refs.relatedAction.records[index], 'options', [])
          this.$set(this.$refs.relatedAction.records[index], 'value', null);
        }
        if (matchItem.inputType === '02') {
          getSelectItemListByParaId(matchItem.paraId).then(res => {
            if (res && res.code === 200) {
              if (type === 1) {
                this.$set(this.$refs.relatedLogic.records[index], 'options', res.data)
              } else {
                this.$set(this.$refs.relatedAction.records[index], 'options', res.data)
              }
            }
          })
        }
      }
    },
    initTypeNames(val) {
      if (typeof val === 'string') {
        let search = this.dict['para_category'].find(item => {
          return item.value == val
        });
        if (search) {
          return search.label;
        } else if (val === '1') {
          return this.$t('validation.commonParameters')
        } else {
          return this.$t('validation.Logical')
        }
      }
    },
    handleTabClick(val) {
      if (val.index === '0') {
      } else if (val.index === this.paramsTypeList.length - 1) {
      } else {
        let search = this.dict['para_category'].find(item => item.label === val.label);
        if (search) {
          this.activeParamType = search.value;
          this.paramsGroupByTypeList = this.paramsList.filter(item => item.type === this.activeParamType);
        }
      }
    },
    /**
     * editor 中的对内容进行处理
     * @param label
     * @param type variable | func，variable为表单变量，需标记，func 为函数，也需要做标记
     */
    insertContent(label, type) {
      const from = this.editor.getCursor();
      if (type === 'variable') {
        this.editor.replaceSelection(label);
        const to = this.editor.getCursor();
        this.markText(from, to, label, 'cm-field');
      } else if (type === 'func') {
        this.editor.replaceSelection(`${label}()`);
        const to = this.editor.getCursor();
        this.markText(from, {line: to.line, ch: to.ch - 2}, label, 'cm-func');
        this.editor.setCursor({line: to.line, ch: to.ch - 1});
      } else if (type === 'funcInit') {
        this.editor.replaceSelection(`${label}`);
        const to = this.editor.getCursor();
        this.markText(from, {line: to.line, ch: to.ch}, label, 'cm-func');
      } else if (type === 'logic') {
        this.editor.replaceSelection(label);
        const to = this.editor.getCursor();
        this.markText(from, to, label, 'cm-logic');
      } else if (typeof label === 'string') {
        this.editor.replaceSelection(label);
      }
      this.editor.focus();
    },
    handleComputedChange(val) {
      let {row, index} = val;
      if (val.val === "1") {
        // 激活弹框
        this.rowComputedSettingShow = true;
        this.formulaSettingForm = {...row};
      } else {

      }
      this.$set(this.$refs.relatedAction.records[index],'selectItem',null)
      this.$set(this.$refs.relatedAction.records[index],'value',null)
    },
    drawerConfirm() {
      if(isBlank(this.formulaStr)){
        this.$message.warning("请输入公式");
        return;
      }
      let {index}= this.formulaSettingForm;
      this.$set(this.$refs.relatedAction.records[index],'value',this.formulaStr);
      let operationFlag=isBlank(this.$refs.relatedAction.records[index].id)?1:2;
      this.$set(this.$refs.relatedAction.records[index],'operationFlag',operationFlag);
      this.rowComputedSettingShow = false;


    },
    drawerCancel() {
      this.rowComputedSettingShow = false;
      this.formulaStr = null;
      this.formulaValueStr = null;
    },

    codeMirrorChange() {
      //获取 editor 的内容
      this.formulaValueStr = this.formulaStr;
    },
    getContent() {
      if (isBlank(this.formulaValueStr)) {
        return;
      }

      this.usedParamsList = [];
      let formula = this.formulaValueStr;
      // 变量CODE替换
      let sortParamsList = [...this.paramsList];
      sortParamsList = this.sortByKey(sortParamsList, 'name');
      sortParamsList.forEach(item => {
        // 通过初始item 完全 匹配，并进行替换
        formula = formula.replaceAll(item.name, '$_$' + item.value + '$_$');
      })
      this.formulaValueStr = formula;

      let usedParamsList = this.getParam(formula);
      const valueSet = new Set(usedParamsList)
      usedParamsList = Array.from(valueSet);
      for (let value of usedParamsList) {
        let item = sortParamsList.find(item => item.value === value.replaceAll('$_$', ''));
        if (item) {
          this.usedParamsList.push({
            name: item.name,
            value: item.value,
            key: item.value
          })
        }
      }
      this.$refs.testResult.open(true);
    },
    markText(from, to, label, className) {
      if (className === void 0) {
        className = "cm-func";
      }
      let text = document.createElement("span");
      text.className = className;
      text.innerText = label;
      this.editor.markText(from, to, {
        atomic: true,
        replacedWith: text,
      });
    },


    handleOptionSelect(value) {
      let {val, row} = value;
      this.$set(this.$refs.relatedAction.records[row.index], 'valueOptions', val);

    },
    handleOptionClear(row) {
      this.$set(this.$refs.relatedAction.records[row.index], 'valueOptions', []);
      this.$set(this.$refs.relatedAction.records[row.index], 'value', []);
    },

    handleModelTableConfirm(val) {
      this.relationEnters = [...val];
      this.selectedElevatorModelIds = this.relationEnters.map(item => item.elevatorModelId);
    },
    getCommonParams(list) {
      let value = list.map(item => item.elevatorModelId);
      let param = {
        language: this.$i18n.locale,
        relatedModel: value,
        modelCount: value.length,
      }
      getCommmonPara(param).then(res => {
        if (res) {
          this.paramsList = res.map(item => {
            return {
              name: item.paraName,
              value: item.paraCode,
              type: item.paraCategory,
              inputType: item.inputType,
              key: item.paraId
            };
          });
          this.paramsTypeList = this.paramsList.map(item => item.type);
          let map = new Set(this.paramsTypeList);
          this.paramsTypeList = Array.from(map);
          this.paramsTypeList = ['1',
            ...this.paramsTypeList,
            '2'
          ]
        }
      })
    },



    initData(id) {
      getInfoCase(id).then(async res => {
        if (res && res.data) {
          this.basicInfo = {...res.data};
          this.relationEnters = [...this.basicInfo.relationEnters];
          //查询参数
          let value = this.relationEnters.map(item => item.elevatorModelId);
          let param = {
            language: this.$i18n.locale,
            relatedModel: value,
            modelCount: value.length,
          }
          getCommmonPara(param).then(res => {
            if (res) {
              this.paramsList = res.map(item => {
                return {
                  name: item.paraName,
                  value: item.paraCode,
                  type: item.paraCategory,
                  inputType: item.inputType,
                  key: item.paraId
                };
              });
              this.paramsTypeList = this.paramsList.map(item => item.type);
              let map = new Set(this.paramsTypeList);
              this.paramsTypeList = Array.from(map);
              this.paramsTypeList = ['1',
                ...this.paramsTypeList,
                '2'
              ]
            }
            //解析 变量名
            for (let item of this.basicInfo.actionList) {
              console.log(item.computedFlag)
              if (item.computedFlag == "1") {
                //如果是计算属性 进行 code替换
                let formula = item.value
                //逻辑符号替换
                Object.keys(this.logicValueMap).forEach(key => {
                  let value = this.logicValueMap[key];
                  formula = formula.replaceAll(key, `${value}`);
                })
                //公式code替换
                Object.keys(this.funValueMap).forEach(key => {
                  let value = this.funValueMap[key];
                  formula = formula.replaceAll(`$@$${key}$@$`, value,);
                })


                // 变量CODE替换
                let sortParamsList = [...this.paramsList];
                sortParamsList = this.sortByKey(sortParamsList, 'name');
                console.log(sortParamsList,"sortParamsList")
                sortParamsList.forEach(para => {
                  // 通过初始item 完全 匹配，并进行替换
                  formula = formula.replaceAll('$_$' + para.value + '$_$', para.name);
                })
                this.$set(item, 'value', formula);
              }
            }
            this.$refs.relatedAction.records = [...this.basicInfo.actionList];
            this.$refs.relatedAction.records.forEach(item => {
              if(!isBlank(item.selectItem)){
                item.selectItem = item.selectItem.split(";");
                let options = []
                item.selectItem.forEach(selectItem => {
                  item.options.some(option => {
                    if (option['value'] === selectItem) {
                      options.push(option)
                    }
                  })
                })
                item.valueOptions = options;
              }

            })
          })
          this.$refs.relatedLogic.records = [...this.basicInfo.logicList];

          this.selectedElevatorModelIds = this.relationEnters.map(item => item.elevatorModelId);
        }
      })
    },

  },
  created() {

  },
  mounted() {
    this.type = parseInt(this.$route.query.type);
    if (this.type !== 1) {
      this.initData(this.$route.query.id)
    }
    if (this.type !== '4') {
      getCommonParamList().then(res => {
        this.commonParamsList = res.data;
      })
    }

  },


}


</script>

<style scoped>
.paramButton {
  padding-top: 10px;
  display: flex;

  .el-button {
    color: #E4F1FF;
    width: 100%;
  }

  .el-icon-menu {
    color: #5DAAFD;
  }

}

.picker {

  text-align: left;

  .code-edit {
    height: 240px;
    border-radius: 6px;
    border: 1px solid #e8e9eb;
  }
}

.top-title {
  background-color: #fafafa;
  height: 30px;
  vertical-align: center;
  line-height: 30px;
  padding-left: 10px;
  border-radius: 4px 4px 0 0;
  border-bottom: none;
}

/deep/ .CodeMirror {
  height: 200px !important;
  /*表单变量样式*/

  .cm-field {
    background: #007bff;
    padding: 3px 5px;
    border-radius: 3px;
    color: #fff;
    margin: 0 1px;
  }

  /*函数样式*/

  .cm-func {
    font-weight: bold;
    color: #ae4597;
    line-height: 14px;
    margin: 0 1px;
    padding: 0 2px;
  }

  .cm-logic {
    font-weight: bold;
    color: #00afff;
    line-height: 14px;
    margin: 0 1px;
    padding: 0 2px;
  }

  .CodeMirror-scroll {
    height: 200px !important;
  }
}
</style>

