<template>
  <div class="box-center">
    <div id="app" style="padding-right: 40%;">
      <div class="biaoti">客户画像关键词配置</div>
      <div class="app-titel" style="margin-top: 20px" v-if="orgType!=3">
        <div
          class="label"
          style="color: #32363d; font-weight: 400; font-size: 16px"
        >
          项目选择：
        </div>
        <div>
          <el-select
            v-model="houseId"
            placeholder="请选择"
            @change="houseChange"
            filterable
          >
            <el-option
              v-for="item in houseList"
              :key="item.id"
              :label="item.propertyName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="addlevl" style="cursor:pointer;" v-if="yyc_add_level1" @click="append1()">
          新增一级
      </div>
      <div style="width: 100%; margin-top: 20px">
        <el-tree ref="tree" :default-expand-all="true" :data="treeList">
          <span class="custom-tree-node" slot-scope="{ node, data }">

            <span v-if="data.level == 1" style="font-size: 18px; color: #32363d" >
              <img class="levelimg1" src="/img/level1.png" alt="" />
              {{ data.name }}
            </span>


            <span v-if="data.level == 2 && data.isInterval == 1" style="font-size: 16px; color: #32363d" >
              <img class="levelimg2" src="/img/level2.png" alt="" />
              {{ data.name }}
            </span>
            <span v-if="data.level == 2 && data.isInterval == 0">
               <img class="levelimg2" src="/img/level2.png" alt="" />
              {{ data.name }}~{{ data.endName }}
            </span>


            <span v-if="data.level == 3" style="font-size: 14px; color: #32363d" >
              <img class="levelimg3" src="/img/level3.png" alt="" />
              {{ data.name }}
            </span>



            <span v-if="data.level == 1" style="display: flex; align-items: center">
              <span class="editorcd" @click.stop="append(node, data)" style="display: flex; align-items: center" >
                <img class="levelimg3" src="/img/add1.png" alt="" />
                <span>添加二级</span>
              </span>
            <span  style="margin-left: 10px" v-if="data.isInterval!=0">
						  <el-button class="editor" type="text" size="mini" @click.stop="() => ddeditor(node, data)">编辑</el-button>
					  </span>
            </span>

            <span v-if="data.level == 2" style="display: flex; align-items: center" >
              <span v-if="data.isInterval == 1" class="editorcd2"  @click.stop="append(node, data)" style="display: flex; align-items: center">
                <img class="levelimg3" src="/img/add2.png" alt="" />
                <span>添加三级</span>
              </span>
              <span style="margin-left: 10px">
                <el-button class="editorcd" type="text" size="mini" @click.stop="ddeditor(node, data)">编辑</el-button>
						  <el-button class="editor" v-if="labelmodelshow" type="text" size="mini" @click="() => moxingEdit(node, data)">编辑模型</el-button>
              </span>
              <span style="margin-left: 10px">
                <el-button class="remove" type="text" size="mini" @click.stop="remove(node, data)" >删除</el-button>
              </span>
            </span>
            <span v-if="data.level == 3" style="display: flex; align-items: center" >
               <span style="margin-left: 10px">
                <el-button class="editorcd" type="text" size="mini" @click.stop="ddeditor(node, data)" >编辑</el-button>
              </span>
              <span style="margin-left: 10px" v-if="labelmodelshow">
                <el-button class="editorcd" type="text" size="mini" @click.stop="moxingEdit(node, data)" >编辑模型</el-button>
              </span>
              <span style="margin-left: 10px">
                <el-button class="remove" type="text" size="mini" @click.stop="remove(node, data)" >删除</el-button>
              </span>
            </span>
          </span>
        </el-tree>
      </div>

      <el-dialog title="新增" :visible.sync="dialogFormVisible" :center="true" width="600px">
        <div
          v-if="amountintervalname == '意向面积'"
          style="display: flex; height: 40px; line-height: 40px"
        >
          <span>面积区间：</span>
          <span style="width: 100px"
            ><el-input type="number" placeholder="面积区间" v-model="addForm.name"></el-input
          ></span>
          <span style="margin-left: 6px">平方</span>
          <span style="margin-left: 12px; margin-right: 12px">~</span>
          <span style="width: 100px"
            ><el-input type="number" placeholder="面积区间" v-model="addForm.endName"></el-input
          ></span>
          <span style="margin-left: 6px">平方</span>
        </div>
        <div
          v-else-if="amountintervalname == '购房预算'"
          style="display: flex; height: 40px; line-height: 40px"
        >
          <span>预算区间：</span>
          <span style="width: 100px"
            ><el-input type="number" placeholder="预算区间" v-model="addForm.name"></el-input
          ></span>
          <span style="margin-left: 6px">万元</span>
          <span style="margin-left: 12px; margin-right: 12px">~</span>
          <span style="width: 100px"
            ><el-input type="number" placeholder="预算区间"  v-model="addForm.endName"></el-input
          ></span>
          <span style="margin-left: 6px">万元</span>
        </div>
        <el-form :model="addForm" v-else>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item
                label="一级大类名称:"
                v-if="level == 0"
                :label-width="formLabelWidth"
              >
                <el-input v-model="addForm.name" placeholder="一级大类名称" maxlength="8" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item
                label="二级名称:"
                v-if="level == 2"
                :label-width="formLabelWidth"
              >
                <el-input v-model="addForm.name" placeholder="二级名称" maxlength="8" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item
                label="三级名称:"
                v-if="level == 3"
                :label-width="formLabelWidth"
              >
                <el-input v-model="addForm.name" placeholder="三级名称" maxlength="8" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="场景描述：" :label-width="formLabelWidth"  v-if="level==2||level==3">
                <el-input
                  type="textarea"
                  maxlength="100"
                  show-word-limit
                  :autosize="{ minRows: 4, maxRows: 8}"
                  placeholder="请输入内容"
                  v-model="addForm.sceneDesc">
                </el-input>
                <div>增加场景描述有利于标签命中，场景越丰富触达越精准；
                例如：意向面积：120平，场景：我想要一个120平的；</div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer" style="border-top:1px solid #eee;padding-top: 20px;display: flex;justify-content: end;">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addSubmit">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 删除确认弹框 -->
      <el-dialog title="提示" :visible.sync="dialogVisible" width="30%" :center="true">
        <span>确定删除该条内容吗</span>
        <span slot="footer" class="dialog-footer" style="border-top:1px solid #eee;padding-top: 20px;display: flex;justify-content: end;">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="checkDelete">确 定</el-button>
        </span>
      </el-dialog>

      <!--?编辑弹框?-->
      <el-dialog title="编辑" :visible.sync="isshowage" :center="true" width="600px">
        <div
          v-if="amountintervalname == '意向面积'"
          style="display: flex; height: 40px; line-height: 40px"
        >
          <span>面积区间：</span>
          <span style="width: 100px"
            ><el-input type="number" placeholder="面积区间" v-model="frosasd.name"></el-input
          ></span>
          <span style="margin-left: 6px">平方</span>
          <span style="margin-left: 12px; margin-right: 12px">~</span>
          <span style="width: 100px"
            ><el-input type="number" placeholder="面积区间" v-model="frosasd.endName"></el-input
          ></span>
          <span style="margin-left: 6px">平方</span>
        </div>
        <div
          v-else-if="amountintervalname == '购房预算'"
          style="display: flex; height: 40px; line-height: 40px"
        >
          <span>预算区间：</span>
          <span style="width: 100px"
            ><el-input type="number" placeholder="预算区间" v-model="frosasd.name"></el-input
          ></span>
          <span style="margin-left: 6px">万元</span>
          <span style="margin-left: 12px; margin-right: 12px">~</span>
          <span style="width: 100px"
            ><el-input type="number" placeholder="预算区间" v-model="frosasd.endName"></el-input
          ></span>
          <span style="margin-left: 6px">万元</span>
        </div>
        <div v-else style="display: flex;align-items: center;height: 40px;">
          <div style="width:90px">
            类名:
          </div>
            <el-input  maxlength="8"
              v-model="frosasd.name"
              placeholder="类名"
              type="text"
            ></el-input>
        </div>
        <div style="display: flex; align-items: center;margin-top:20px" v-if="frosasd.level==2||frosasd.level==3">
          <div style="width:105px">
            场景描述：
          </div>
          <div>
             <el-input
                type="textarea"
                maxlength="100"
                show-word-limit
                :autosize="{ minRows: 4, maxRows: 8}"
                placeholder="请输入内容"
                v-model="frosasd.desc">
              </el-input>
              <div>增加场景描述有利于标签命中，场景越丰富触达越精准；
              例如：意向面积：120平，场景：我想要一个120平的；</div>
          </div>
        </div>
        <div v-if="frosasd.level == 1" style="display: flex;align-items: center;height: 40px;">
            <div style="margin-left: 30px;height: 30px;line-height: 30px;">是否必选：</div>
            <div>
                <el-radio-group v-model="frosasd.mustSelected">
                    <el-radio :label="0">是</el-radio>
                    <el-radio :label="1">否</el-radio>
                </el-radio-group>
            </div>
        </div>
        <div style="display: flex; justify-content: center; margin-top: 40px">
          <button
            style="
              width: 100px;
              height: 40px;
              border-radius: 4px;
              background: #ffffff;
              font-size: 14px;
              border: 1px solid #dcdfe6;
            "
            @click="submicll()"
          >
            取消
          </button>
          <button
            style="
              width: 100px;
              height: 40px;
              border-radius: 4px;
              background: #2671E2;
              font-size: 14px;
              margin-left: 60px;
              color: #ffffff;
              border: none;
            "
            @click="submiadd()"
          >
            提交
          </button>
        </div>
      </el-dialog>


   <el-dialog title="新增一级" :visible.sync="dialogVisible2" :center="true" width="400px">
        <el-form :model="addForm2">
          <el-row :gutter="24">
              <el-form-item
                label="名称:"
              >
                <el-input style="width:300px;" placeholder="名称" v-model="addForm2.name"  maxlength="8"  autocomplete="off"></el-input>
              </el-form-item>
          </el-row>
          <el-row :gutter="24">
              <el-form-item
                label="是否必选:"
              >
              <el-radio-group v-model="addForm2.mustSelected">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer" style="border-top:1px solid #eee;padding-top: 20px;display: flex;justify-content: end;">
          <el-button @click="dialogVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="addclick()">确 定</el-button>
        </span>
    </el-dialog>
    <!--   匹配模型 -->
    <el-dialog
          title="编辑模型"
          @open="openModel"
          :close-on-click-modal="false"
          :visible.sync="moxingVisible"
          >
    <el-dialog
            title="匹配规则"
            :visible.sync="innerVisible"
            append-to-body>
      <div style="max-height: 430px;overflow: auto">
        <p><b>匹配距离</b>：关键字匹配字数距离，主要针对near/after/w-  生效，w- 的字数统计从挖掘话术后，客户的第一句话开始统计；</p>
        <p style="padding-left: 15px">例如：设置为10，面积  after 140</br>
          命中话术："想买一个面积在140平的"</br>
          超出10个字，有关键字不命中话术参考：“房屋面积啊，你们这边有多大的，有没有140平左右的”；</p>
        <p><b>or（或）</b>：多个关键词，匹配上1个就行</p>
        <p style="padding-left: 15px">例如标签：自住</br>
          匹配模型：自己住 or 给自己</br>
          命中话术：我们自己住/给自己买的</p>
        <p><b>and not（非）</b>：排除反面意思</p>
        <p style="padding-left: 15px">例如：北京户口，</br>
          匹配模型：是北京户口 and not 不是北京户口</br>
          命中话术：我是北京户口；</br>
          反面话术：我不是北京户口</p>
        <p><b>near （ 临近）</b>：1个关键词前后一定范围出现过另一个关键词就算命中，有距离限制</p>
        <p style="padding-left: 15px">例如标签：购房预算 140w</br>
          匹配模型：预算  near 140</br>
          命中话术：我的预算是140w或大概140w的购房预算</p>
        <p><b>after（后面）</b>：一段文本出现2个关键词，并且按照先后的顺序即算命中，有距离限制</p>
        <p style="padding-left: 15px">例如标签：意向面积  140平</br>
          匹配模型： 面积  after  140   ，140在面积后面才算生效；</br>
          命中话术：想买一个面积在140平的；</p>
        <p><b>w-（挖掘话术业务）</b>：顾问执行了挖掘话术，客户回答结果，有距离限制，从客户话术文本开始</p>
        <p style="padding-left: 15px">例如标签：北京户口</br>
          匹配模型：（w-是 or w-有） and not  （w-不是 or w-没有）
          命中话术：销售：你有北京户口吗？</br>
          客户：有的；</p>
        <p><b>-n（命中距离）</b>：near/after-n ,单个near/after的匹配距离，n大于0，小于500</p>
        <p style="padding-left: 15px">例如 ：面积  after-10  140</br>
          10个字内，命中话术参考："想买一个面积在140平的"</br>
          超出10个字，有关键字不命中话术参考：“房屋面积啊，你们这边有多大的，有没有140平左右的”；</p>
        <p><b>注意</b>：-n  与 near/after/answer 之间<b>不能有空格</b>；</p></br>
        <p><b>注意</b>：优先匹配关键词可以排在前面；</p>
      </div>

    </el-dialog>
    <el-form ref="form" size="mini" :inline="true" :model="form" label-position="right">
      <el-form-item label="标签名称:">
        <div style="max-width:400px;min-width: 200px;font-weight: bold">{{form.keywordsName}}</div>
      </el-form-item>
      <el-form-item label="场景描述：">
        <div v-if="form.sceneDesc" style="width:500px;border: 1px dashed #ccc;padding:5px  10px;line-height: 25px"> {{form.sceneDesc}}</div>
        <div v-else>暂无描述</div>
      </el-form-item>
      <el-form-item label="after,near,w- 匹配距离:">
        <el-input-number  v-model="form.distance" controls-position="right" :min="0" :max="500"></el-input-number></el-input><span style="color:red;margin-left:10px">*请输入0~500内的整数</span> <el-button type="text" style="margin-left:30px" @click="innerVisible=true">规则说明</el-button>
      </el-form-item>
      <div contentEditable="true"
           @click="myeditorenter($event)"
           @keypress.enter="myeditorenter($event)"
           @blur="saveRange"
           class="editDiv"
           id="huashuModel">
      </div>
      <div v-if="dynamiclist.length">需求挖掘匹配：</div>
      <div class="dynamicbox">
        <div v-for="item in dynamiclist" :key="item" class="itemlist">
          <el-input size="small" disabled style="width: 220px" v-model="item.question"></el-input>
          <div class="item-input" style="pointer-events: none;" v-html="item.editValue"></div>
        </div>
      </div>
      <el-form-item label="插入节点:">
        <el-button size="mini" type="primary" style="margin-left:8px;" v-for="(item,index) in taglist" :key="index" @click="insertTag(item,index)">{{item.label}}</el-button>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
    <el-button @click="moxingVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveFun">保 存</el-button>
  </span>
  </el-dialog>

    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      dynamiclist: [],
      taglist: [
        {
          label: "or (或)",
          value: "or",
        },
        {
          label: "near (临近)",
          value: "near",
        },
        {
          label: "after (后面)",
          value: "after",
        },
        {
          label: "and not (非)",
          value: "and not",
        },
        // {
        //     label: '～ (至)',
        //     value: '～'
        // },
      ],
      moxingVisible: false,
      innerVisible: false,
      form: {
        keywordsName: "",
        id: "",
        keywordsId: "",
        distance: 10,
        sceneDesc: "",
        originalExpression: "",
      },
      formLabelWidth: "120px",
      dialogFormVisible: false,
      dialogVisible: false,
      dialogVisible2: false,
      orgType: localStorage.getItem("orgType"),
      isshowage: false,
      treeList: [], //树形数据
      houseList: [],
      orgCode: "", //公司id
      houseId: "",
      addForm: {
        name: "",
        endName: "",
        sceneDesc: "",
      },
      addForm2: {
        name: "",
        mustSelected: 0,
      },
      level: 0,
      pid: "",
      deleteId: "",
      frosasd: {
        name: "",
        endName: "",
        isInterval: "",
        id: "",
        pid: "",
        orgCode: "",
        sort: "",
        level: "",
        desc: "",
        mustSelected: 1, // 是否必选
      },
      amountintervalname: "",
      isInterval: "",
      orgCodes: "",
    };
  },
  computed: {
    ...mapGetters(["permissions"]),
  },
  created() {
    this.yyc_add_level1 = this.permissions["yyc_add_level1"];
    this.labelmodelshow = this.permissions["labelmodelshow"]; // 编辑模型按钮权限
  },
  mounted() {
    // 获取项目列表
    this.zkhousePage();
  },
  methods: {
    // 基于保存的光标插入内容 --用于失去焦点后再继续插入内容
    insertContent(str) {
      let selection,
        range = window._range; // 当前光标位置对象
      if (!window.getSelection) {
        range.pasteHTML(str);
        range.collapse(false);
        range.select();
      } else {
        selection = window.getSelection
          ? window.getSelection()
          : document.selection;
        range.collapse(false);
        let hasR = range.createContextualFragment(str);
        let hasR_lastChild = hasR.lastChild;
        while (
          hasR_lastChild &&
          hasR_lastChild.nodeName.toLowerCase() == "br" &&
          hasR_lastChild.previousSibling &&
          hasR_lastChild.previousSibling.nodeName.toLowerCase() == "br"
        ) {
          let e = hasR_lastChild;
          hasR_lastChild = hasR_lastChild.previousSibling;
          hasR.removeChild(e);
        }
        range.insertNode(hasR);
        if (hasR_lastChild) {
          range.setEndAfter(hasR_lastChild);
          range.setStartAfter(hasR_lastChild);
        }
        selection.removeAllRanges();
        selection.addRange(range);
      }
    },
    // 失去焦点时保存光标位置
    saveRange: () => {
      let selection = window.getSelection
        ? window.getSelection()
        : document.selection;
      if (!selection.rangeCount) return;
      let range = selection.createRange
        ? selection.createRange()
        : selection.getRangeAt(0);
      window._range = range;
    },
    // 回显模型数据,Dialog 的内容是懒渲染的，即在第一次被打开之前，传入的默认 slot 不会被渲染到 DOM 上,so在 open 事件回调中进行
    openModel() {
      // this.$nextTick(()=>{
      //     let huashuModel = document.getElementById('huashuModel')
      //     huashuModel.innerHTML = this.form.originalExpression
      // })
    },
    //格式化粘贴文本方法
    onPaste(event) {
      var e = event || window.event;
      // 阻止默认粘贴
      e.preventDefault();
      // 粘贴事件有一个clipboardData的属性，提供了对剪贴板的访问
      // clipboardData的getData(fomat) 从剪贴板获取指定格式的数据
      var text =
        (e.originalEvent || e).clipboardData.getData("text/plain") ||
        prompt("在这里输入文本");
      //清除回车
      text = text.replace(/\[\d+\]|\n|\r/gi, "");
      // 插入
      document.execCommand("insertText", false, text);
    },
    myeditorenter(e) {
      e.preventDefault();
    },
    // 插入节点
    insertHtmlAtCaret(html) {
      document.getElementById("huashuModel").focus();
      var sel, range;
      if (window.getSelection) {
        // IE9 and non-IE
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
          range = sel.getRangeAt(0);
          range.deleteContents();
          // Range.createContextualFragment() would be useful here but is
          // non-standard and not supported in all browsers (IE9, for one)
          var el = document.createElement("div");
          el.innerHTML = html;
          var frag = document.createDocumentFragment(),
            node,
            lastNode;
          while ((node = el.firstChild)) {
            lastNode = frag.appendChild(node);
          }
          range.insertNode(frag);
          // Preserve the selection
          if (lastNode) {
            range = range.cloneRange();
            range.setStartAfter(lastNode);
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
          }
        }
      } else if (document.selection && document.selection.type != "Control") {
        // IE < 9
        document.selection.createRange().pasteHTML(html);
      }
    },
    // 点击插入标签
    insertTag(item, index) {
      if (window._range) {
        this.insertContent(
          "<span contentEditable='false' style='color:red'>" +
            item.value +
            "</span><text>&nbsp;</text>"
        );
      } else {
        this.insertHtmlAtCaret(
          "<span contentEditable='false' style='color:red'>" +
            item.value +
            "</span><text>&nbsp;</text>"
        );
      }
    },
    // 处理标签，删除不需要的标签格式
    delMark(str) {
      const hasStr = (str) => {
        let index = str.indexOf("<");
        let index1 = str.indexOf(">");
        if (index > 0 && index1 > 0) {
          let replaceStr = str.substring(index, index1 + 1);
          str = str.replace(replaceStr, "");
          hasStr(str);
        }
      };
      hasStr(str);
    },
    // 处理模型 关键词加#号
    replaceFun(str) {
      let temp = str;
      temp = temp.replace(/<text>\&nbsp\;<\/text>/g, "");
      temp = temp.replace(/\&nbsp\;/g, "");
      temp = temp.replace(/<text>/g, "");
      temp = temp.replace(/<\/text>/g, "");
      temp = temp.replace(
        /<span contenteditable="false" style="color:red">/g,
        " #"
      ); // 后台返回是这样的，变了，需要也处理一下
      temp = temp.replace(
        /<span style="color:red" contenteditable="false">/g,
        " #"
      );
      temp = temp.replace(/<\/span>/g, "#");
      // console.log(temp);
      this.delMark(temp);
      return temp;
    },
    // 模型保存
    saveFun() {
      let text = document.getElementById("huashuModel");
      // console.log(text.innerHTML);
      // console.log(text.innerText);
      let temp = text.innerHTML;
      if (this.form.distance == "") {
        this.$message.error("请输入距离");
        return;
      }
      if (text.innerText == "") {
        this.$message.error("请输入标签模型");
        return;
      }

      axios({
        url: `/autoSR/zk/keymodel/updateKeywordsModel`,
        method: "post",
        data: {
          id: this.form.id,
          houseId: this.houseId,
          level: this.level,
          keywordsId: this.form.keywordsId,
          keywordsName: this.form.keywordsName,
          answerList: [],
          keyType: 2,
          formatExpression: this.replaceFun(temp), // 问题表达式
          original: temp, // html数据
          showFormatExpression: text.innerText,
          distance: this.form.distance, // * 距离
        },
      })
        .then((data) => {
          this.moxingVisible = false;
          if (data.code == 0) {
            this.$message.success(data.data);
            this.getorgCode();
          } else {
            this.$message.error(data.msg);
          }
        })
        .catch((e) => {
          this.moxingVisible = false;
        });
    },
    moxingEdit(node, data) {
      this.level = data.level;
      this.form.keywordsName = data.endName
        ? data.name + "~" + data.endName
        : data.name;
      this.form.keywordsId = data.keywordsId;
      this.form.sceneDesc = data.desc || "";
      // 获取模型数据回显
      axios({
        url: `/autoSR/zk/keymodel/findById`,
        method: "get",
        params: {
          houseId: this.houseId,
          level: this.level,
          keyType: 2,
          keywordsId: data.id,
        },
      })
        .then((res) => {
          // console.log(res)
          this.moxingVisible = true;
          if (res.code == 0) {
            let obj = res.data;
            if (obj != null) {
              this.form.distance = obj.distance || 10;
              this.form.originalExpression = obj.originalExpression;
              this.form.id = obj.id;
              // 回显标签模型数据
              if (obj.answerList && obj.answerList.length) {
                this.dynamiclist = obj.answerList.map((cont) => {
                  return {
                    question: cont.question,
                    editValue: cont.originalExpression,
                  };
                });
                // console.log(this.dynamiclist)
              } else {
                this.dynamiclist = [];
              }
            } else {
              this.form.distance = 10;
              this.form.originalExpression = this.form.keywordsName;
              this.form.id = "";
            }
          } else {
            this.form.distance = 10;
            this.form.originalExpression = this.form.keywordsName;
          }
          this.$nextTick(() => {
            let huashuModel = document.getElementById("huashuModel");
            huashuModel.innerHTML = this.form.originalExpression;
          });
        })
        .catch((e) => {
          this.moxingVisible = true;
        });
    },
    addclick() {
      var orgCode = "";
      if (localStorage.getItem("orgType") == 3) {
        orgCode = localStorage.getItem("orgCode");
      } else {
        orgCode = this.orgCodes;
      }
      if (this.addForm2.name != "") {
        axios({
          url: `/autoSR/zk/keywords/add`,
          method: "post",
          data: {
            pid: 0,
            name: this.addForm2.name,
            mustSelected: this.addForm2.mustSelected,
            level: 1,
            orgCode: orgCode,
            houseId: this.houseId,
          },
        }).then((res) => {
          if (res.code == 0) {
            this.dialogVisible2 = false;
            this.getHouse();
          } else {
            this.$message({
              message: res.msg || "添加失败",
              type: "error",
            });
          }
        });
      } else {
        this.$message({
          message: "内容不能为空",
          type: "warning",
        });
        return;
      }
    },
    append1() {
      this.addForm2.name = "";
      this.dialogVisible2 = true;
    },
    // 获取模板数据
    getHouse() {
      axios({
        url: `/autoSR/zk/keywords/findKeywordsTemplate`,
        method: "get",
        params: {
          houseId: this.houseId,
        },
      }).then((res) => {
        if (res.code == 0) {
          // console.log(res.data);
          this.treeList = res.data;
        }
      });
    },
    // 添加二三级节点入口
    append(node, data) {
      this.amountintervalname = data.name;
      this.addForm.name = "";
      this.addForm.endName = "";
      this.addForm.sceneDesc = "";
      this.pid = data.id;
      this.level = data.level + 1;
      this.orgCode = data.orgCode;
      if (
        this.amountintervalname == "意向面积" ||
        this.amountintervalname == "购房预算"
      ) {
        this.isInterval = 0;
      } else {
        this.isInterval = 1;
      }
      this.dialogFormVisible = true;
    },
    houseChange() {
      this.houseList.map((item) => {
        if (item.id == this.houseId) {
          this.orgCodes = item.orgCode;
        }
      });
      console.log(this.orgCodes);
      this.getHouse();
    },
    // 添加节点确认按钮
    addSubmit() {
      if (this.addForm.name != "") {
        if (
          this.amountintervalname == "意向面积" ||
          this.amountintervalname == "购房预算"
        ) {
          if (Number(this.addForm.name) > Number(this.addForm.endName)) {
            this.$message({
              message: "第一个值必须小于第二个值，请检查！",
              type: "warning",
            });
            return;
          } else {
            this.dialogFormVisible = false;
            this.addNode();
          }
        } else {
          this.dialogFormVisible = false;
          this.addNode();
        }
      } else {
        this.$message({
          message: "内容不能为空",
          type: "warning",
        });
        return;
      }
    },
    // 新增的节点保存
    addNode() {
      axios({
        url: `/autoSR/zk/keywords/add`,
        method: "post",
        data: {
          pid: this.pid,
          name: this.addForm.name,
          endName: this.addForm.endName,
          level: this.level,
          orgCode: this.orgCode,
          isInterval: this.isInterval,
          houseId: this.houseId,
          desc: this.addForm.sceneDesc,
        },
      }).then((res) => {
        if (res.code == 0) {
          if (this.level == 2) {
            // 二级
            let newChild = {
              id: res.data,
              pid: this.pid,
              name: this.addForm.name,
              endName: this.addForm.endName,
              orgCode: this.orgCode,
              level: this.level,
              isInterval: this.isInterval,
              children: [],
            };
            this.treeList.forEach((item, index) => {
              if (item.id == this.pid) {
                item.children.push(newChild);
              }
            });
          } else {
            let newChilds = {
              id: res.data,
              pid: this.pid,
              name: this.addForm.name,
              orgCode: this.orgCode,
              level: this.level,
              isInterval: 1,
              endName: "",
            };
            this.treeList.forEach((item, index) => {
              item.children.forEach((ite, inde) => {
                if (ite.id == this.pid) {
                  ite.children.push(newChilds);
                }
              });
            });
          }
          this.zkhousePage();
        }
      });
    },
    //删除节点
    remove(node, data) {
      // console.log(data, "123");
      this.deleteId = data.id;
      if (data.level == 3) {
        this.dialogVisible = true;
      } else {
        if (data.children.length == 0) {
          this.dialogVisible = true;
        } else {
          this.$message({
            message: "请先清空子级",
            type: "warning",
          });
        }
      }
    },
    // 确认删除自定义的节点
    checkDelete() {
      axios({
        url: `/autoSR/zk/keywords/delete`,
        method: "get",
        params: {
          id: this.deleteId,
          houseId: this.houseId,
        },
      }).then((res) => {
        if (res.code == 0) {
          this.treeList.forEach((item, index) => {
            item.children.forEach((ite, inde) => {
              if (ite.id == this.deleteId) {
                this.treeList[index].children.splice(inde, 1);
              } else {
                ite.children.forEach((it, ine) => {
                  if (it.id == this.deleteId) {
                    this.treeList[index].children[inde].children.splice(ine, 1);
                  }
                });
              }
            });
          });
          this.dialogVisible = false;
          this.$message.success("删除成功");
        }
      });
    },
    //编辑
    ddeditor(node, data) {
      console.log(data, "adjklsajdlk");
      this.frosasd = {
        name: "",
        endName: "",
        isInterval: "",
        id: "",
        pid: "",
        orgCode: "",
        sort: "",
        level: "",
        desc: "",
        mustSelected: 1,
      };
      if (data.isInterval == 0) {
        this.frosasd.isInterval = 0;
        this.frosasd.endName = data.endName;
        this.treeList.forEach((item, index) => {
          if (data.pid == item.id) {
            this.amountintervalname = item.name;
          }
        });
      } else {
        this.amountintervalname = "";
        this.frosasd.endName = "";
        this.frosasd.isInterval = 1;
      }
      if (data.level == 1) {
          this.frosasd.mustSelected = data.mustSelected;
      }
      this.frosasd.id = data.id;
      this.frosasd.name = data.name;
      this.frosasd.pid = data.pid;
      this.frosasd.orgCode = data.orgCode;
      this.frosasd.sort = data.sort;
      this.frosasd.level = data.level;
      this.frosasd.desc = data.desc;
      this.isshowage = true;
    },
    //取消编辑
    submicll() {
      this.isshowage = false;
    },
    //编辑提交
    submiadd() {
      if (this.frosasd.isInterval == 0) {
        if (Number(this.frosasd.name) > Number(this.frosasd.endName)) {
          this.$message({
            message: "第一个值必须小于第二个值，请检查！",
            type: "warning",
          });
          return;
        } else {
          this.infosubmiadd();
        }
      } else {
        this.infosubmiadd();
      }
    },
    zkhousePage() {
      this.$api.api
        .findHouseByUser({
          orgType: localStorage.getItem("orgType"),
        })
        .then((res) => {
          // console.log(res)
          this.houseList = res.data;
          if (localStorage.getItem("orgType") == 3) {
            this.houseId = localStorage.getItem("houseId");
          } else {
            this.houseId = res.data[0].id;
            this.orgCodes = res.data[0].orgCode;
          }
          // this.houseId = res.data[0].id;
          // 列表获取
          this.getHouse();
        });
    },
    infosubmiadd() {
      var that = this;
      axios({
        url: `/autoSR/zk/keywords/update`,
        method: "post",
        data: { ...this.frosasd, houseId: this.houseId },
      }).then((res) => {
        if (res.code == 0) {
          this.getHouse();
          that.isshowage = false;
          that.treeList.forEach((item, index) => {
            item.children.forEach((asd, indexesd) => {
              if (asd.id == that.frosasd.id) {
                that.treeList[index].children[indexesd].name =
                  that.frosasd.name;
                that.treeList[index].children[indexesd].endName =
                  that.frosasd.endName;
                that.treeList[index].children[indexesd].id = res.data;
                that.isshowage = false;
                that.$message({
                  message: "修改成功",
                  type: "success",
                });
                return;
              } else {
                asd.children.forEach((zxc, indexzxc) => {
                  if (zxc.id == that.frosasd.id) {
                    that.treeList[index].children[indexesd].children[
                      indexzxc
                    ].name = that.frosasd.name;
                    that.treeList[index].children[indexesd].children[
                      indexzxc
                    ].id = res.data;
                    that.isshowage = false;
                    that.$message({
                      message: "修改成功",
                      type: "success",
                    });
                    return;
                  }
                });
              }
            });
          });
        } else {
          this.$message({
            message: "修改失败",
            type: "error",
          });
        }
      });
    },
  },
};
</script>

<style scoped="scoped" lang="scss" >
/deep/.el-tree-node__content {
  overflow: hidden;
}
.editDiv {
  width: 100%;
  min-height: 60px;
  max-height: 120px;
  overflow: auto;
  margin-bottom: 10px;
  padding: 15px;
  outline: none;
  border: 1px solid #409eff;
  border-radius: 10px;
}
.box-center {
  width: 100%;
  padding: 15px 15px 20px;
  min-width: 1000px;
}
#app {
  width: 100%;
  min-height: 100vh;
  background: #ffffff;
  box-shadow: 0px 0px 12px 0px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  padding-left: 15px;
  padding-bottom: 60px;
}
.addlevl {
  width: 100px;
  border: 1px solid #2671e2;
  color: #2671e2;
  text-align: center;
  line-height: 30rpx;
  border-radius: 4px;
  margin-top: 10px;
  margin-left: 18px;
}
.biaoti {
  font-size: 20px;
  font-family: PingFangSC-Semibold, PingFang SC;
  font-weight: 600;
  color: #32363d;
  line-height: 20px;
  padding-top: 25px;
}
.primary {
  width: 108px;
  height: 42px;
  background: #2671e2;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 183px;
}
.remove {
  color: red;
}
.editorcd {
  color: #2671e2;
}
.editorcd2 {
  color: #e6a12f;
}
.levelimg1 {
  width: 18px;
  height: 18px;
}
.levelimg2 {
  width: 16px;
  height: 16px;
}
.levelimg3 {
  width: 14px;
  height: 14px;
}
.app-titel {
  width: 100%;
  display: flex;
  align-items: center;
  .label {
    font-size: 14px;
    font-weight: 400;
    color: #32363d;
    line-height: 14px;
    margin-left: 15px;
  }
  .toptimeqhuan {
    height: 30px;
    background: #ffffff;
    display: flex;
    align-items: center;
  }
  .toptimeqhuan div {
    padding-left: 20px;
    padding-right: 20px;
    text-align: center;
    line-height: 30px;
    font-size: 14px;
    margin-right: 15px;
    border-radius: 4px;
    border: 1px solid #e0e0e0;
  }
}
/deep/ .el-dialog--center {
  border-radius: 8px;
  .el-dialog__title {
    font-weight: bold;
  }
}
/deep/ .el-button--primary {
  background: #2671e2 !important;
  border: 1px solid #2671e2 !important;
}
/deep/ .el-button--text {
  color: #2671e2;
}

.itemlist {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0;
}
.item-input {
  width: 100%;
  padding: 4px 10px;
  outline: none;
  border: 1px solid #409eff;
  border-radius: 4px;
  overflow: auto;
  line-height: 24px;
  min-height: 24px;
  max-height: 100px;
  margin: 0 10px;
}
</style>
