<template>
  <div class="app-container">
    <div class="top">
      <div class="account-title">{{ $t(initTitle) }}</div>
      <div class="button-group">
        <el-button v-if="type!==4" type="primary" icon="el-icon-circle-check" @click="Confrim">
          {{ $t('common.confirm') }}</el-button>
        <el-button  @click="cancel" icon="el-icon-remove-outline" size="mini" plain style="width: 93px;">
          {{ $t('common.cancel') }}</el-button>
      </div>
    </div>
    <CustomCard :show-save="type!==4" :show-cancel="true" :label="initTitle" @Confirm="Confrim" @cancel="cancel" :show-header="false">
      <CustomForm ref="basicInfo" :value="basicInfo" :disabled="type===4">
        <CustomInput label="relatedCase.caseName" prop="caseName" :maxlength="100" required/>
        <CustomSelect :data="dict['logic_operation']" :label="$t('relatedCase.relationship')" prop="relationship"
                      required/>
        <CustomSelect :data="dict['run_type']" :label="$t('relatedCase.runType')" prop="runType" :clearable="false"
                      @change="handleRunTypeChange"
                      required/>
        <CustomInputNumber v-if="basicInfo.runType==='1'" :label="$t('relatedCase.runIndex')" prop="runIndex"
                           :max="99999999"
                           :precision="0" 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=" handleDeleteRow"/>
      </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 type="selection" :min-width="20"/>
            <CustomColumn label="No" type="index" :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"
                     :add-row-object="{editable:'0',displayFlag:'0', emptyFlag:'0'}"
                     :show-delete="type!==4" :disabled="type===4">
            <CustomColumn type="selection" :min-width="20"/>
            <CustomColumn label="No" :min-width="20" type="index"/>

            <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'||row.inputType =='04')
                                  }"
                                  @clear="handleOptionClear" prop="selectItem"/>
            <CustomFormItemColumn :label="$t('relatedCase.value')" row-option-prop="valueOptions" prop="value"
                                  @click="handleValueClick"
                                  :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" active-value="1" in-active-value="0"/>
            <CustomSwitchColumn :label="$t('relatedCase.displayFlag')" prop="displayFlag" active-value="1" in-active-value="0"/>
            <CustomSwitchColumn :label="$t('relatedCase.emptyFlag')" prop="emptyFlag" active-value="1" in-active-value="0"/>
          </EditTable>
        </Col>
      </Row>
    </CustomCard>


    <el-drawer ref="rowComputedSetting" :visible.sync="rowComputedSettingShow" size="65%" :wrapperClosable="false">
      <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-tooltip>
                            <template #content>
                              {{funcType.tip}}
                            </template>
                          <el-button icon="el-icon-menu" @click="insertContent(funcType.name, 'func')"
                                     :disabled="type===4">
                            <span style="color: #5DAAFD">{{ funcType.name }}</span>
                          </el-button>
                          </el-tooltip>
                        </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%" card-height="100%">
        <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 type="primary" 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>

    <Dialog ref="testResult" :title="$t('validation.testresult')" @close="closeCheck">
      <CustomForm :value="testFormula">
        <CustomInput :span="12"  v-for="(item ,index) in  usedParamsList" :label="`${item.name}`"
                     :prop="`$_$${item.value}$_$`"
                     :key="index"/>
        <el-form-item :label="$t('validation.testresult')">
          <span>{{ testResult }}</span>
        </el-form-item>
      </CustomForm>

      <template #footer>
        <el-row style="text-align: end">
          <CustomButton icon="el-icon-circle-check" type="primary" :label="$t('common.confirm')"
                        @handleClick="submitCheckFunction"/>
          <CustomButton icon="el-icon-remove-outline" :label="$t('common.cancel')" @handleClick="closeCheck()"/>
        </el-row>

      </template>
    </Dialog>
  </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 {buildRegexFromArray, 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";
import {
  analysisFormula,
  funKeyMap,
  funList,
  funValueMap,
  getContent,
  initReplaceCodeList,
  logicKeyMap,
  logicOperation,
  logicValueMap,
  testSubmitCheckFunction
} from "@/utils/formula";
import CustomInputNumber from "@/components/CustomElement/CustomForm/items/CustomInputNumber.vue";

export default {
  name:'SecondaryPageRelated',
  components: {
    CustomInputNumber,
    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: [],
      cmOptions: {
        // 语言及语法模式
        mode: 'text/javascript',
        // 主题
        theme: "idea",
        // 显示函数
        line: true,
        lineNumbers: false,
        // 软换行
        lineWrapping: true,
        // tab宽度
        tabSize: 4,
      },
      lang: 'javascript',
      formulaStr: "",
      formulaValueStr: "",
      formulaSettingForm: {},
      rowComputedSettingShow: false,
      testFormula: {},
      usedParamsList: [],
      testResult: ""
    };
  },
  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: {
    logicOperation() {
      return logicOperation
    },
    funList() {
      return funList
    },
    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));
      });
    },
    handleRunTypeChange(val){

      if(val.value==='0'){
        this.$set(this.basicInfo,'runIndex',null);

      }


    },

    async Confrim() {
      await this.$refs.basicInfo.validate();
      this.relationEnters = JSON.parse(JSON.stringify(this.$refs.relationEnters.tableData))

      if (isBlank(this.relationEnters) || this.relationEnters.length === 0) {
        this.$modal.msgError(this.$t('validation.atLeastModel'))
        return;
      }
      if (isBlank(this.$refs.relatedLogic.records) || this.$refs.relatedLogic.records.length === 0) {
        this.$message.error(this.$t('relatedCase.atLeastCase'))
        return;
      }
      if (isBlank(this.$refs.relatedAction.records) || this.$refs.relatedAction.records.length === 0) {
        this.$message.error(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.error(this.$t('relatedCase.logicCaseNoRepeat'))
         return;
       }*/
      let relatedActionParamCode = relatedAction.map(item => item.paraCode);
      let relatedActionParamCodeMap = new Set(relatedActionParamCode);
      if (relatedActionParamCode.length !== relatedActionParamCodeMap.size) {
        this.$message.error(this.$t('relatedCase.actionNoRepeat'))
        return;
      }

      //二者不能重复
      for (let item of relatedLogicParamCode) {
        if (relatedActionParamCode.includes(item)) {
          this.$message.error(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].inputType === '04') && row.actionList[i].computedFlag !== "1") {
          if (isBlank(row.actionList[i].selectItem)) {
            let msg = row.actionList[i].paraName + this.$t('common.requiredMsg')
            this.$message.error(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") {
          if (isBlank(row.actionList[i].value)) {
            this.$modal.msgError("请填写公式")
            return
          }

          //如果是计算属性 进行 code替换
          let conditionFormulaAnalysis = row.actionList[i].value
          conditionFormulaAnalysis = analysisFormula(conditionFormulaAnalysis, initReplaceCodeList(this.paramsList));
          // if (matchStr(conditionFormulaAnalysis)) {
          //   // 如果还存在未被替换的参数，则表示 变更梯型后，参数未共有
          //   this.$modal.msgError("请确保参数在梯型中存在！");
          //   return;
          // }

          this.$set(row.actionList[i], 'valueFormulaTxt', conditionFormulaAnalysis);
          this.$set(row.actionList[i], 'value', row.actionList[i].value);
          this.$set(row.actionList[i], 'selectItem', null);
        }
        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', null);
        this.$set(this.$refs.relatedAction.records[index], 'options', [])
        this.$set(this.$refs.relatedAction.records[index], 'value', null);
        this.$set(this.$refs.relatedAction.records[index], 'computedFlag', '0');
      }
    },

    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);
          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], 'inputType', matchItem.inputType);
          this.$set(this.$refs.relatedAction.records[index], 'selectItem', (matchItem.inputType === '02' || matchItem.inputType === '04') ? [] : null);
          this.$set(this.$refs.relatedAction.records[index], 'options', (matchItem.inputType === '02' || matchItem.inputType === '04') ? [] : null)
          this.$set(this.$refs.relatedAction.records[index], 'value', null);
          this.$set(this.$refs.relatedAction.records[index], 'computedFlag', '0');
        }
        if (matchItem.inputType === '02' || matchItem.inputType === '04') {
          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)
    },
    handleValueClick(val) {
      if (this.type === 4) {
        return;
      }
      // 激活弹框
      this.rowComputedSettingShow = true;
      let that = this
      this.$nextTick(() => {
        this.formulaStr = null;
        this.formulaValueStr = null;
        this.editor.setValue("");
        this.editor.clearHistory();

        let formula = val.value;
        this.$set(this.formulaSettingForm, 'index', val.index);
        // 变量CODE替换
        let sortParamsList = initReplaceCodeList(that.paramsList);
        sortParamsList = sortParamsList.map(item => item.name);
        sortParamsList.push("（");
        sortParamsList.push("）");
        sortParamsList.push("，");
        sortParamsList.push(",");
        formula = formula.replace(buildRegexFromArray(sortParamsList), '|$1|');
        let funcValue = Object.keys(funKeyMap);
        let logicValue = Object.keys(logicKeyMap);
        let regex = /[+\-*/]/;
        let rightRegex = /\)+/g;
        let leftRegex = /\(+/g
        let judgeRegex = /[><]/
        let contentArray = formula.split('|');
        for (let item of contentArray) {
          if (funcValue.includes(item) && !regex.test(item)) {
            that.insertContent(item, 'funcInit')
          } else if (logicValue.includes(item)) {
            that.insertContent(item, 'logic');
          } else if (regex.test(item) || judgeRegex.test(item) || leftRegex.test(item) || rightRegex.test(item)
            || item === ","
            || item === "，" || item.includes("\"") || item.includes("==")) {
            that.insertContent(item, null)
          } else {
            if (item != " ") {
              that.insertContent(item, 'variable')
            }
          }
        }
      })


    },


    drawerConfirm() {
      if (isBlank(this.formulaStr)) {
        this.$message.error("请输入公式");
        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;
      this.formulaStr = null;
      this.formulaValueStr = null;
      this.editor.setValue("");
      this.editor.clearHistory();

    },
    drawerCancel() {
      this.rowComputedSettingShow = false;
      this.formulaStr = null;
      this.formulaValueStr = null;
      this.editor.setValue("");
      this.editor.clearHistory();
    },

    codeMirrorChange() {
      //获取 editor 的内容
      this.formulaValueStr = this.formulaStr;
    },
    getContent() {
      getContent(this);
    },
    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', "");
      if (this.editor) {
        this.editor.setValue("");
        this.editor.clearHistory();
      }

    },


    async handleModelTableConfirm(val) {
      this.relationEnters = [...val];
      this.selectedElevatorModelIds = this.relationEnters.map(item => item.elevatorModelId);
      await this.getCommonParams(this.relationEnters);
      this.validateNeedClearRow();
    },
    async handleDeleteRow(val) {
      this.basicInfo.deleteRelationEnterIds = val
      if (this.$refs.relationEnters.tableData.length === 0) {
        this.paramsList = [];
        this.paramsTypeList = ['1',
          '2'
        ]
        this.basicInfo.logicDeleteIds = this.$refs.relatedLogic.records.map(item => item.id);
        this.basicInfo.actionDeleteIds = this.$refs.relatedAction.records.map(item => item.id);
        this.$refs.relatedLogic.records = []
        this.$refs.relatedAction.records = []
      } else {
        await this.getCommonParams(this.$refs.relationEnters.tableData)
        this.validateNeedClearRow();
      }
    },
    async getCommonParams(list) {
      let value = list.map(item => item.elevatorModelId);
      let param = {
        language: this.$i18n.locale,
        relatedModel: value,
        modelCount: value.length,
      }
      let res = await getCommmonPara(param)
      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'
        ]
      }else{
        this.paramsList = [];
        this.paramsTypeList=['1','2']
      }
    },

    validateNeedClearRow() {
      if (this.paramsList === null || this.paramsList.length === 0) {
        //如果没有共有参数 则直接清空
        this.basicInfo.logicDeleteIds = this.$refs.relatedLogic.records.filter(v => isBlank(v.id)).map(item => item.id);
        this.basicInfo.actionDeleteIds = this.$refs.relatedAction.records.filter(v => isBlank(v.id)).map(item => item.id);
        this.$refs.relatedLogic.records = []
        this.$refs.relatedAction.records = []
      } else {
        let paramCodes = this.paramsList.map(item => item.value)
        for (let i = 0; i < this.$refs.relatedLogic.records.length; i++) {
          let item = this.$refs.relatedLogic.records[i];
          if (!paramCodes.includes(item.paraCode)) {
            if (!isBlank(item.id)) {
              if (Array.isArray(this.basicInfo.logicDeleteIds)) {
                this.basicInfo.logicDeleteIds.push(item.id);
              } else {
                this.basicInfo.logicDeleteIds = [item.id];
              }
            }
          }
        }
        for (let i = 0; i < this.$refs.relatedAction.records.length; i++) {
          let item = this.$refs.relatedAction.records[i];
          if (!paramCodes.includes(item.paraCode)) {
            if (!isBlank(item.id)) {
              if (Array.isArray(this.basicInfo.actionDeleteIds)) {
                this.basicInfo.actionDeleteIds.push(item.id);
              } else {
                this.basicInfo.actionDeleteIds = [item.id];
              }
            }
          }

          //无需保证 公式中的参数共有
         /* if (item.computedFlag === '1') {
            let analysedValue = analysisFormula(item.value, initReplaceCodeList(this.paramsList));
            if (!matchStr(analysedValue)) {
              if (!isBlank(item.id)) {
                this.basicInfo.actionDeleteIds.push(item.id);
              }
              this.$refs.relatedAction.records.splice(i, 1);
            }
          }*/
        }
        this.$refs.relatedLogic.records= this.$refs.relatedLogic.records.filter(item => paramCodes.includes(item.paraCode));
        this.$refs.relatedAction.records= this.$refs.relatedAction.records.filter(item =>paramCodes.includes(item.paraCode));
      }
    },


    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) {
              if (item.computedFlag == "1") {
                //如果是计算属性 进行 code替换
                let formula = item.value
                //逻辑符号替换
                Object.keys(logicValueMap).forEach(key => {
                  let value = logicValueMap[key];
                  formula = formula.replaceAll(key, `${value}`);
                })
                //公式code替换
                Object.keys(funValueMap).forEach(key => {
                  let value = funValueMap[key];
                  formula = formula.replaceAll(`$@$${key}$@$`, value,);
                })
                // 变量CODE替换
                let sortParamsList = [...this.paramsList];
                sortParamsList = this.sortByKey(sortParamsList, 'name');
                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;
              }
              if (isBlank(item.value)) {
                item.value = undefined;
              }

            })

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


          })


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

    getParam(str) {
      let matchList = [];
      const regex = /(\$_\$.*?\$_\$)/g;
      const matches = str.match(regex);
      if (matches) {
        matches.forEach(match => {
          matchList.push(match)
        });
      }
      return matchList;
    },
    closeCheck() {
      this.testFormula = {};
      this.testResult = null;
      this.$refs.testResult.visible = false;
    },
    async submitCheckFunction() {
      this.formulaValueStr = this.formulaStr
      return testSubmitCheckFunction(this, this.formulaValueStr, this.paramsList, this.testFormula, this.usedParamsList)
    },
  },
  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>
<style lang="scss" scoped>

  .top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
  }
  .account-title {
    font-family: Arial, Arial;
    font-weight: bold;
    font-size: 18px;
    line-height: 21px;
  }
  .button-group {
    display: flex;
  }
</style>
