<template>
  <div class="mod-config">
    <commonTree
      source="tags"
      axiosType="raw"
      axiosResultKey="market"
      @changeCurrentNode="changeCurrentNode"
      ref="commonTree"
      :dataList="treeDataList"
      @getCommonShopDataList="getCommonShopDataList"
      @handleClickNodes="handleClickNodes"
      :urlList="urlList"
    ></commonTree>
    <div
      v-if="isFresh"
      v-loading="!isFresh"
      style="width: calc(100% - 360px); height: 100%; float: right;  border: 1px solid #bababa; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); border-radius: 10px;position: relative;"
    >
      <div class="border_box info_box">
        <div class="title_box">
          <div class="title"><span class="line"></span>基本标签信息</div>
        </div>

        <div class="addFormBox">
          <el-form :model="addForm" ref="addForm" label-width="80px">
            <el-form-item label="标签名称" prop="title" class="form_item">
              <el-input
                placeholder="请输入标签名称"
                style="width: 100%"
                v-model="addForm.title"
                clearable
              >
              </el-input>
            </el-form-item>
            <el-form-item label="排序" prop="sort" class="form_item">
              <el-input-number
                placeholder="请输入标签排序"
                style="width: 100%"
                v-model="addForm.sort"
                :min="0"
                clearable
                @keyup.native="UpNumber"
                @keydown.native="UpNumber"
              >
              </el-input-number>
            </el-form-item>
            <el-form-item
              label="是否为最终级"
              prop="isLast"
              label-width="120px"
              class="form_item"
            >
              <el-switch
                v-model="addForm.isLast"
                active-color="#13ce66"
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
                @change="handleChangeIsLast"
              >
              </el-switch>
            </el-form-item>
          </el-form>
        </div>
        <div
          style="  border: 1px dashed #bababa;"
          v-if="currentNode && currentNode.data.isLast == 1"
        ></div>
      </div>
      <div
        class="border_box tree_content_box"
        v-if="currentNode && currentNode.data.isLast == 1"
      >
        <div class="title_box" style="margin-bottom: 10px; height: 40px">
          <div class="title">
            <span class="line"></span>已关联课程列表
            <el-button
              plain
              type="primary"
              style="margin-left: 20px"
              @click="openTable('addForm')"
              size="mini"
              >新增</el-button
            >

            <!-- <div style="" class="button_box"> -->
            <!-- <el-button plain type="danger" @click="handleCheckAllChange(true)" size="mini">清空</el-button> -->

            <!-- </div> -->
          </div>
        </div>
        <!-- :isNoSearch="true" -->
        <commonShop
          :isNoSearch="true"
          :otherInfo="{
            httpType: 'raw',
            httpDataValueName: 'list'
          }"
          :defaultForm="{
            marketId: addForm.id
          }"
          axiosType="raw"
          getAssociatedGoodsListKey="marketId"
          :isNoPaging="true"
          getAssociatedGoodsListValue="result"
          :tableColumnList="tableColumnList"
          :currentId="addForm.id ? addForm.id : ''"
          currentType="bookMarketId"
          :dataList="associatedGoodsList"
          :urlList="urlList"
          @delete="dataFormDelete"
          :isEdit="isEdit"
          ref="commonShop"
          :style="`height: calc(100% - 50px); `"
        >
          <template slot="searchFormItem" slot-scope="slotProps">
            <!-- <el-form-item
              label="课程名称"
              prop="title"
              class="form_item"
              style="width: 240px;"
            >
              <el-input
                size="small"
                placeholder="请输入课程名称"
                style="width: 100%"
                v-model="slotProps.dataForm.title"
                clearable
              >
              </el-input>
            </el-form-item> -->
            <!-- <el-form-item label="商品类型" prop="goodsType" class="form_item">
            <el-select
              size="small"
              v-model="slotProps.dataForm.goodsType"
              placeholder="请选择"
              style="width: 100%;"
              clearable
            >
              <el-option
              style="padding:0 10px;box-sizing: border-box;"
                v-for="item in goodsTypeList"
                :key="item.dictType"
                :label="item.dictValue"
                :value="item.dictType"
              >
              </el-option>
            </el-select>
          </el-form-item> -->
          </template>
          <template slot="tableItem" slot-scope="slotProps">
            <el-table-column
              label="课程ID"
              width="70"
              align="center"
              prop="courseEntity.id"
            >
              <!-- <template slot-scope="scope">
            {{ (pageIndex - 1) * pageSize + scope.$index + 1 }}
          </template> -->
            </el-table-column>
            <el-table-column
              prop="courseEntity.title"
              header-align="center"
              align="center"
              label="课程名称"
            >
            </el-table-column>

            <el-table-column
              header-align="center"
              align="center"
              label="课程图"
              width="140"
            >
              <template slot-scope="scope">
                <img
                  v-if="scope.row.courseEntity.image != ''"
                  :src="scope.row.courseEntity.image"
                  width="25"
                  height="35"
                  class="tableImg"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="sort"
              header-align="center"
              align="center"
              width="100"
              label="排序"
            >
            </el-table-column>
          </template>
          <template slot="operation" slot-scope="slotProps">
            <el-button
              type="text"
              @click="dataFormEdit(slotProps.row)"
              size="mini"
              >修改排序</el-button
            >
          </template>
        </commonShop>

        <div class="submitButton submitButtonBox">
          <!-- <el-button size="small" @click.stop="dataFormEdit()">
            取消
          </el-button> -->
          <el-button
            type="primary"
            @click="dataFormSubmit('addForm')"
            size="small"
            >确定</el-button
          >
          <!-- </div> -->
        </div>
      </div>
      <div
        class="submitButton submitButtonBox"
        style="position: absolute;bottom: 13px;right: 15px;"
        v-if="!isEdit"
      >
        <!-- <el-button size="small" @click.stop="dataFormEdit()">
            取消
          </el-button> -->
        <el-button
          type="primary"
          @click="dataFormSubmit('addForm')"
          size="small"
          >确定</el-button
        >
        <!-- </div> -->
      </div>
    </div>

    <!-- <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()"
    >
   
      
    </el-form> -->
    <commonShopTable
      title="课程"
      :otherInfo="{
        httpType: 'raw',
        httpDataValueName: 'records',
        httpDataTotalName: 'total'
      }"
      :defaultForm="{
        keywords: '',
        id: addForm.id
      }"
      :urlList="urlList"
      :tableColumnList="tableColumnList"
      marketIdKey="marketId"
      ref="commonShopTable"
      :currentId="addForm.id"
      currentType="bookMarketId"
      @submit="handleSubmitShopTable"
    >
      <template slot="searchFormItem" slot-scope="slotProps">
        <el-form-item label="课程名称" prop="keywords" class="form_item">
          <el-input
            size="small"
            placeholder="请输入课程名称"
            style="width: 100%"
            v-model="slotProps.dataForm.keywords"
            clearable
          >
          </el-input>
        </el-form-item>
        <!-- <el-form-item label="商品类型" prop="goodsType" class="form_item">
              <el-select size="small" v-model="dataForm.goodsType" placeholder="请选择" style="width: 100%" clearable>
                <el-option v-for="item in goodsTypeList" :key="item.dictType" :label="item.dictValue"
                  :value="item.dictType">
                </el-option>
              </el-select>
            </el-form-item> -->
      </template>

      <template slot="tableItem" slot-scope="slotProps">
        <el-table-column label="课程ID" width="70" align="center" prop="id">
          <!-- <template slot-scope="scope">
            {{ (pageIndex - 1) * pageSize + scope.$index + 1 }}
          </template> -->
        </el-table-column>
        <el-table-column
          prop="title"
          header-align="center"
          align="center"
          label="课程名称"
        >
        </el-table-column>

        <el-table-column
          header-align="center"
          align="center"
          label="课程图"
          width="120"
        >
          <template slot-scope="scope">
            <img
              v-if="scope.row.image != ''"
              :src="scope.row.image"
              width="25"
              height="35"
              class="tableImg"
            />
          </template>
        </el-table-column>
      </template>
    </commonShopTable>
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getDataList"
    ></add-or-update>
    <el-dialog
      :append-to-body="true"
      :modal-append-to-body="false"
      title="修改排序"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <div class="addFormBox selectTimeBox">
        <el-form ref="addForm" :model="dataForm" label-width="80px">
          <slot name="searchFormItem" :dataForm="dataForm"></slot>

          <el-form-item
            label="课程名称:"
            class="form_item"
            style="width: 100% !important"
          >
            <p class="input_item">
              {{ dataForm.title }}
            </p>
            <!-- selectCourse -->
            <!-- <el-input
              v-model="selectCourse.courseCatalogueTitle"
              readonly
            ></el-input> -->
          </el-form-item>
          <el-form-item
            label="排序:"
            class="form_item"
            style="width: 100% !important"
          >
            <el-input :min="0" v-model="dataForm.sort" type="number"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleSubmitDataForm"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import debounce from "lodash/debounce"; //导入lodash中的debounce
import AddOrUpdate from "@/views/components/commonBookTags/bookTagsForm.vue";
import commonShop from "@/views/components/commonBookTags/shopproduct.vue";
import commonShopTable from "@/views/components/commonBookTags/shopproductTable.vue";
import commonTree from "@/views/components/commonBookTags/tags.vue";
// import dialogComponent from './seckillprodrelation'
export default {
  data() {
    return {
      dialogVisible: false,
      isEdit: false,
      checkAll: false,
      isIndeterminate: true,
      urlList: {
        treeList: "/master/courseMedicineMarket/marketTree",
        delete: "/master/courseMedicineMarket/delMarket",
        deleteShop:
          "/master/courseMedicineMarket/unbindCourseAndMedicineMarket",
        saveShop: "/master/courseMedicineMarket/bindCourseAndMedicineMarket",
        add: "/master/courseMedicineMarket/addSociologyMarket",
        edit: "/master/courseMedicineMarket/editSociologyMarket",
        hasBindProductList: "/master/courseMedicineMarket/getCourseByMarketId",
        CanBindProductList: "/master/courseMedicineMarket/getNotToMarketList",
        editSort: "/master/courseMedicineMarket/editMarketSort"
      },
      addForm: {},
      isFresh: false,
      dataRule: {
        name: [
          {
            required: true,
            message: "标签名称不能为空"
            // trigger: "change",
          }
        ]
      },
      currentNode: {},
      treeDataList: [],
      associatedGoodsList: [], //已关联商品列表

      isact: "", //当前hover的节点
      isactTitle: "", //记录修改节点名称
      curNode: undefined, //当前选中节点
      isUpdateGroup: false, //是否在修改模板组
      filterText: "",
      indexRecord: [], //记录节点轨迹
      isBreak: false, //是否结束循环
      defaultProps: {
        children: "children",
        label: "title"
      },
      dataForm: {
        key: ""
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      tableColumnList: [
        { label: "商品ID", width: 70, align: "center", prop: "productId" },
        {
          label: "商品名称",
          align: "center",
          prop: "product.productName",
          headerAlign: "center"
        },
        {
          label: "价格",
          align: "center",
          prop: "product.price",
          headerAlign: "center"
        },
        {
          label: "活动价",
          width: 120,
          align: "center",
          prop: "product.activityPrice",
          headerAlign: "center"
        },
        {
          label: "库存",
          width: 120,
          align: "center",
          prop: "product.productStock",
          headerAlign: "center"
        },
        {
          label: "商品图",
          width: 120,
          align: "center",
          prop: "product.productImages",
          headerAlign: "center",
          slot: "productImages"
        }
      ]
    };
  },
  components: {
    AddOrUpdate,
    commonShop,
    commonTree,
    commonShopTable
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  activated() {
    this.isEdit = false;
    this.getDataList();
  },
  methods: {
    handleClose() {
      this.dataForm = {};
      this.dialogVisible = false;
    },
    handleSubmitDataForm: debounce(async function() {
      var that = this;
      this.$http
        .request({
          url: this.$http.adornUrl(`${this.urlList.editSort}`),
          method: "POST",
          data: {
            marketId: this.dataForm.marketId,
            courseId: this.dataForm.courseId,

            sort: Number(this.dataForm.sort)
          },
          header: {
            //默认 无 说明：请求头
            "Content-Type": "application/json"
          }
        })

        .then(async ({ data }) => {
          if (data && data.code === 0) {
            this.$message.success(data.msg);

            if (this.$refs.commonShop) {
              this.$refs.commonShop.getAssociatedGoodsList({
                courseId: this.addForm.id
              });
            }
          } else {
            this.$message.error(data.msg);
          }
          that.dialogVisible = false;
        });

      that.$forceUpdate();
    }, 200),
    UpNumber(e) {
      e.target.value = e.target.value.replace(/[^\d]/g, "");
    },
    dataFormEdit(row) {
      this.dataForm = {
    
        marketId: row.medicineMarketId,
            courseId: row.courseId,
        sort: row.sort,
        title: row.courseEntity.title
      };
      this.dialogVisible = true;
    },
    handleCheckAllChange(val) {
      this.$nextTick(() => {
        this.$refs.commonShop.handleCheckAllChange(val);
      });
    },
    handleSubmitShopTable: debounce(async function(ids) {
      await this.$http
        .request({
          url: this.$http.adornUrl(`${this.urlList.saveShop}`),
          method: "POST",
          data: {
            courseId: ids,
            marketId: this.addForm.id
          },
          header: {
            //默认 无 说明：请求头
            "Content-Type": "application/json"
          }
        })
        .then(async ({ data }) => {
          if (data && data.code === 0) {
            this.$message.success(data.msg);

            if (this.$refs.commonShop) {
              // this.$refs.commonShop.getAssociatedGoodsList.dataForm={
              //   ...this.$refs.commonShop.getAssociatedGoodsList.dataForm,
              //   id:this.addForm.id ? this.addForm.id : null
              // }

              this.$refs.commonShop.getAssociatedGoodsList();
            }
            if (this.$refs.commonShopTable) {
              this.$refs.commonShopTable.close();
            }
          } else {
            this.$message.error(data.msg);
          }
        });
    }, 200),
    openTable() {
      this.isEdit = false;
      this.$nextTick(() => {
        this.$refs.commonShopTable.dataForm.marketId = this.addForm.id;
        this.$refs.commonShopTable.open(this.addForm.id);
      });
    },
    handleChangeIsLast(e) {
      console.log("🚀 ~ handleChangeIsLast ~ e:", e);
      this.$nextTick(() => {
        if (e == 1) {
          if (this.$refs.commonShop) {
            // this.$refs.commonShop.getAssociatedGoodsList.dataForm={
            //   ...this.$refs.commonShop.getAssociatedGoodsList.dataForm,
            //   id:this.addForm.id ? this.addForm.id : null
            // }
            this.$refs.commonShop.getAssociatedGoodsList();
          }
        }
      });
    },

    async getCommonShopDataList(type, id, form) {
      this.isFresh = false;
      this.isEdit = false;
      this.isFresh = true;
      console.log("🚀 ~ getCommonShopDataList ~ type, id:", type, id);
      this.currentNode = { data: { ...form } };
      this.addForm = form;

      await this.getDataList();
      // this.$refs.commonTree.setCurrentNodeShow();
      this.$nextTick(() => {
        // this.$refs.commonShop.clear();
        // this.$refs.commonShop.bookMarketId = null;
        if (form.isLast == 1) {
          if (this.$refs.commonShop) {
            // this.$refs.commonShop.getAssociatedGoodsList.dataForm={
            //   ...this.$refs.commonShop.getAssociatedGoodsList.dataForm,
            //   id:this.addForm.id ? this.addForm.id : null
            // }
            this.$refs.commonShop.getAssociatedGoodsList();
          }
        }
      });
    },

    //新增修改
    dataFormSubmit: debounce(async function(formName) {
      //    return false
      if (this.addForm.title == "" || !this.addForm.title) {
        this.$message.error("请输入标签名称");
        return false;
      }
      await this.$refs[formName].validate(async valid => {
        if (valid) {
          await this.$http({
            url: this.$http.adornUrl(
              this.addForm.id ? this.urlList.edit : this.urlList.add
            ),
            method: "post",
            data: this.$http.adornData({
              ...this.addForm
            })
          }).then(async ({ data }) => {
            if (data && data.code === 0) {
              // var status = await this.correlationShop(data.result.id);
              await this.getDataList();

              this.$nextTick(async () => {
                this.$refs.commonTree.setCurrentNodeShow(data.market.id);

                this.addForm = data.market;
                this.currentNode = { data: { ...data.market } };
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                  }
                });
              });
            } else {
              this.$message.error(data.msg);
              setTimeout(() => {
                this.addForm = { ...this.currentNode.data };
              }, 500);

              // console.log('this.addForm at line 550:', this.addForm)
              // console.log('this.addForm at line 550:', this.currentNode)
            }
          });
        }
      });
    }, 200),
    //新增修改
    dataFormDelete: debounce(async function(row, deleteType) {
      console.log("row at line 515:", row);
      this.$confirm(
        `确定要删除${deleteType != "all" ? "该" : "所有"}关联课程嘛?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(async () => {
          // var lableIds = row[0].bookLabelId;
          var productIds = row[0].courseId;

          // //    return false
          // var selectShopArr = this.$refs.commonShop.selectShopArr;
          // console.log(selectShopArr, "1111");

          // if (selectShopArr.length == 0) {
          //   this.$message.error("请选择已关联的商品");
          //   return false;
          // }
          this.$refs.commonShop.dataListLoading = true;
          await this.$http
            .request({
              url: this.$http.adornUrl(`${this.urlList.deleteShop}`),
              method: "POST",
              data: {
                courseId: productIds,
                marketId: this.addForm.id
              },
              header: {
                //默认 无 说明：请求头
                "Content-Type": "application/json"
              }
            })
            .then(async ({ data }) => {
              if (data && data.code === 0) {
                this.$message.success("删除成功");
              } else {
                this.$message.error(data.msg);
              }
              this.$nextTick(() => {
                // this.$refs.commonShop.selectShopArr = [];
                if (this.$refs.commonShop) {
                  //     this.$refs.commonShop.getAssociatedGoodsList.dataForm={
                  //   ...this.$refs.commonShop.getAssociatedGoodsList.dataForm,
                  //   id:this.addForm.id ? this.addForm.id : null
                  // }
                  this.$refs.commonShop.getAssociatedGoodsList();
                }
              });
            });
        })
        .catch(() => {});
    }, 200),
    setCheckedKeys() {
      this.$refs.tree.setCheckedKeys([0]);
    },
    changeCurrentNode(val) {
      this.changeCurrentNode = val;
      this.$forceUpdate();
    },
    handlereset() {
      this.currentNode = null;
      this.isFresh = false;
      this.isFresh = true;
    },
    handleClickNodes(node, data, type) {
      this.isEdit = false;
      this.addForm = {};
      // console.log(this.$refs.tree.handleClickNodes(), "当前选中节点");
      console.log(node, data, "当前选中节点");
      this.currentNode = node ? node : {};
      this.isFresh = false;
      this.isFresh = true;

      var form = {};
      switch (type) {
        case "add":
          form = { ...data };
          break;
        case "edit":
          form = { ...node.data };
          break;
        case "addChildren":
          form = {
            children: [],
            delFlag: 0,
            isLast: 0,
            pid: data.id,
            sort: 0,
            title: ""
          };
          break;
      }
      this.addForm = { ...form };

      this.$nextTick(() => {
        this.$refs.commonShop.clear();
        // this.$refs.commonShop.bookMarketId = null;
        this.$refs.commonShop.getDataList(type == "edit" ? form.id : "");
      });
    },
    addOrUpdateHandle() {
      var addform = {
        children: [],
        delFlag: 0,
        isLast: 0,
        pid: 0,
        sort: 0,
        title: ""
      };
      this.handleClickNodes({ data: addform }, addform, "add");
      // if (!this.currentNode) {
      //   this.$message.error("请先选择分类");
      //   return;
      // }
    },

    filterNode(value, data) {
      if (!value) return true;
      return data.title.indexOf(value) !== -1;
    },

    // renderContent(h, { node, data, store }) {
    //   return;
    //   `<span
    //       style="flex: 1; display: flex; align-items: center; justify-content: space-between; padding-right: 8px;"
    //       on-mouseenter={() => this.mouseenteract(data)}
    //       on-mouseleave={() => this.mouseleaveact(data)}
    //     >
    //       <span>
    //         <span>{node.label}</span>
    //       </span>
    //       {this.isact == data ? (
    //         <span>
    //           {this.isact.typeName == "模板组" ? (
    //             <el-button
    //               class="m-r-10"
    //               type="text"
    //               icon="el-icon-edit"
    //               on-click={() => this.handleUpdateGroup(node, data)}
    //             ></el-button>
    //           ) : (
    //             <span></span>
    //           )}
    //           <el-button
    //             type="text"
    //             icon="el-icon-delete"
    //             on-click={(e) => this.handleDelete(node, data, e)}
    //           ></el-button>
    //         </span>
    //       ) : (
    //         <span></span>
    //       )}
    //     </span>`;
    // },
    updateRenderContent(h, { node, data, store }) {
      return `
        <span style="flex: 1; display: flex; align-items: center; justify-content: space-between; padding-right: 8px;">
          <span>
            {this.isact == data ? (
              <input
                type="text"
                onChange={this.handleChangeTitle.bind(this)}
                value={node.label}
              />
            ) : (
              <span>{node.label}</span>
            )}
          </span>
          {this.isact == data ? (
            <span>
              {this.isact.typeName == "模板组" ? (
                <span>
                  <el-button
                    class="m-r-10"
                    type="text"
                    icon="el-icon-check"
                    on-click={() => this.updateGroup(node, data)}
                  ></el-button>
                  <el-button
                    class="m-r-10"
                    type="text"
                    icon="el-icon-close"
                    on-click={(e) => this.cancelUpdate(node, data, e)}
                  ></el-button>
                </span>
              ) : (
                <span></span>
              )}
            </span>
          ) : (
            <span></span>
          )}
        </span>`;
    },
    //获取鼠标进入节点的数据
    mouseenteract(da) {
      this.isact = da;
    },
    mouseleaveact(da) {
      this.isact = "";
    },
    handleNodeClick(pdata) {
      this.curNode = pdata;
      document
        .getElementsByClassName("el-tree-node__content")[0]
        .setAttribute("class", "el-tree-node__content");
    },
    handleDelete(node, data, e) {
      e.stopPropagation();
      //存在则添加到子级
      const parent = node.parent;
      const children = parent.data.nodes || parent.data;
      //若parent.data是对象，操作的是子级；如果是数组，操作的是最外层
      if (Array.isArray(parent.data)) {
        const parentIndex = parent.data.findIndex(d => d.id === data.id);
        parent.data.splice(parentIndex, 1);
      } else {
        const childIndex = children.findIndex(d => d.id === data.id);
        children.splice(childIndex, 1);
      }
      this.curNode = undefined;
    },
    //新增组
    handleAddGroup() {
      /**
       *  如果模版深度最多两层，取消该部分注释
       * //最多只有两层组 不可能添加在dept2的组上 curNode存在 并且  深度超过1
         if (this.curNode != undefined && this.curNode.depth != 1) { 
         this.$message.warning("不能添加超过两层");  
         return; 
       }
       */

      //如果isUpdateGroup 已经是true了 说明重复点击了
      if (this.isUpdateGroup) {
        return;
      }

      let id = ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
        (
          c ^
          (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
        ).toString(16)
      );
      let newChild = {
        parentId: "", //如果有这个id 是插入第二层 否则是第一层 可有可无
        text: "", //必须有 this.templateContent.tempName
        nodes: [],
        id: id,
        typeName: "模板组",
        temporaryData: "1" //用来区分临时数据
      };
      /* 如果模版深度最多两层，以下条件改成该部分注释
        this.curNode && this.curNode.depth == 1 
      */
      this.indexRecord = [];
      if (this.curNode) {
        if (!this.curNode.nodes) {
          this.$message.warning("模板不可添加");
          return;
        }
        newChild.parentId = this.curNode.id;
        /* 如果模版深度最多两层，以下条件改成该部分注释
          const index = this.treeDataList.findIndex(
            item => item.id == this.curNode.id
          );
          this.treeDataList[index].nodes.push(newChild);
        */
        //找到tree中的index轨迹
        this.getTemplateTreeNode(this.curNode.id, this.treeDataList, 0);
        //按照index轨迹插入节点
        this.insertNode(
          newChild,
          this.treeDataList,
          this.indexRecord,
          this.indexRecord.length
        );
        this.isBreak = false;
      } else if (this.curNode == undefined) {
        //没有选中的时候 添加到最外层
        newChild.depth = 1;
        this.treeDataList.push(newChild);
      }
      //调用出updateRender的input
      this.isact = newChild;
      this.isUpdateGroup = true;
    },
    //递归遍历获得选中node
    getTemplateTreeNode(target, list, dept) {
      //空数组直接返回
      if (list.length == 0) return;
      let dataLen = list.length;
      for (let i = 0; i < dataLen; i++) {
        //如果不匹配
        if (target != list[i].id) {
          //存在nodes 遍历nodes里的节点
          if (list[i].nodes) {
            this.indexRecord[dept] = i;
            let recordDept = dept + 1;
            this.getTemplateTreeNode(target, list[i].nodes, recordDept);
          } else {
            //不存在nodes 继续遍历
            continue;
          }
        } else {
          //匹配，则修改下标数组
          this.indexRecord[dept] = i;
          this.isBreak = true;
          break;
        }
        //删除不匹配的轨迹 如果已经break了说明已经找到正确的节点，就不用再删了
        if (!this.isBreak) {
          this.indexRecord.pop();
        }
      }
    },
    //插入节点
    insertNode(insertChild, tree, indexArr, len) {
      let index = indexArr.length - len;
      if (len == 0) {
        tree.push(insertChild);
      } else {
        this.insertNode(
          insertChild,
          tree[indexArr[index]].nodes,
          indexArr,
          len - 1
        );
      }
    },
    //修改组
    handleUpdateGroup() {
      this.isUpdateGroup = true;
    },
    //修改组名时获取title
    handleChangeTitle(e) {
      let value = e.target.value;
      this.isactTitle = value;
    },
    updateGroup(node, data) {
      //先handleChangeTitle获取title 再调用
      setTimeout(() => {
        if (this.isactTitle.trim() == "") {
          this.$message.warning("名称不能为空");
          return;
        }
        //修改数据组
        this.isUpdateGroup = false;
        const parent = node.parent;
        const children = parent.data.nodes || parent.data;
        const index = children.findIndex(d => d.id === data.id);
        let temp = data;
        temp.text = this.isactTitle;
        children.splice(index, 1, temp);
      }, 500);
    },
    cancelUpdate(node, data, e) {
      this.$message.info("已取消");
      this.isUpdateGroup = false;
      //如果是插入操作 需要移除数据
      if (this.isact.temporaryData) {
        this.handleDelete(node, data, e);
      }
    },
    // 获取数据列表

    async getDataList() {
      this.dataListLoading = true;
      await this.$http({
        url: this.$http.adornUrl(this.urlList.treeList),
        method: "get"
        // params: this.$http.adornParams({
        //   'page': this.pageIndex,
        //   'limit': this.pageSize,
        //   'key': this.dataForm.key
        // })
      }).then(({ data }) => {
        console.log("🚀 ~ getDataList ~ data:", data);
        if (data && data.code === 0) {
          this.treeDataList = data.result;
          // this.totalPage = data.page.totalCount
        } else {
          this.treeDataList = [];
          // this.totalPage = 0
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    }
    // // 新增 / 修改
    // addOrUpdateHandle(row) {
    //   this.addOrUpdateVisible = true;
    //   this.$nextTick(() => {
    //     this.$refs.addOrUpdate.init(row);
    //   });
    // },
  }
};
</script>
<style lang="less" scoped>
.tree_box {
  width: 350px !important;
  height: 100%;
  float: left;
  border: 1px solid #bababa;
  border-radius: 10px;
  padding: 15px;
  box-sizing: border-box;
  // background: #fafafa;
}

.border_box {
  height: 100px;
  margin-bottom: 10px;

  .title_box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;

    .button_box {
      // width: 200px;
      float: right;
    }
  }

  .title {
    width: 300px;
    min-width: 200px;

    float: left;
    display: flex;
    align-items: center;
    font-weight: 600;
    font-size: 16px;

    // color: #17b3a3;
    .line {
      width: 4px;
      height: 20px;
      margin-right: 8px;
      background: #17b3a3;
    }
  }
}

.border_box {
  width: 100%;
  float: right;
  background: #fffefe;

  border-radius: 10px;
  padding: 15px 15px;
  box-sizing: border-box;
}

.tree_content_box {
  height: calc(100% - 110px) !important;
  .shopFormBox {
    width: auto !important;
  }
}

.mod-config {
  width: 100%;
  height: 82vh;
  overflow: hidden;
}

.el-tree-node__content {
  .el-button {
    display: none;
  }
}

.el-tree-node__content:hover {
  .el-button {
    display: inline;
  }
}

.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: #eaebed;
  color: #4796ec;
  font-weight: bold;
}

.el-tree {
  height: 350px;
  overflow-y: auto !important;

  .el-tree-node__content span {
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

// .el-card {
//   background: none !important;
// }
p {
  margin: 0;
  margin-bottom: 10px;
}

.submitButtonBox {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.submitButton {
  float: right;
}

// .el-tree-node__content .el-button {
//   // width: 120px !important;

//   display: block !important;
// }
// ::v-deep .el-tree .el-tree-node__content span:nth-child(2) {
//   width: 120px;
//   display: flex !important;
//   align-items: center !important;
//   justify-content: space-between !important;
// }
// /deep/.el-table__row--level-1 {
//   display: block !important;
// }

.addFormBox {
  overflow: hidden;

  .form_item {
    width: 33%;
    float: left;
  }
}

.custom-tree-container {
  height: calc(100% - 100px);

  .filter-tree {
    height: 100%;
  }
}

.info_bg {
  background: #e0dede;
  height: 28px;
  line-height: 28px;
  padding-left: 10px;
  // padding: 8px 5px;
  box-sizing: border-box;
  // margin-top: -10px;
  border-radius: 4px;
  font-size: 14px;
  width: calc(100% - 120px);
  float: left;
}

.shopFormBox {
  min-width: auto !important;
}
</style>
