<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%; overflow-y: scroll; 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>
        <div
        style="padding-top: 0;padding-bottom: 0;"          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
           
            :CustomEdit="true"
            :otherInfo="{
              httpType: 'raw',
              resultValueName: 'certificateList'
            }"
            :defaultForm="{
                tel:'',
                title:'',
              labelId: addForm.id
            }"
            axiosType="raw"
            getAssociatedGoodsListKey="id"
            :isNoPaging="true"
           
            :isShowPagination="true"
            getAssociatedGoodsListValue="result"
            :tableColumnList="tableColumnList"
            :currentId="addForm.id ? addForm.id : ''"
            currentType="bookMarketId"
            :dataList="associatedGoodsList"
            :urlList="urlList"
            @delete="dataFormDelete"
            @edit="handleDataFormEdit"
            :isEdit="isEdit"
            ref="commonShop"
            :style="`height: calc(100vh - 340px); `"
          >
            <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.tel"
                  clearable
                >
                </el-input>
              </el-form-item>
              <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>
            </template>
            <template slot="tableItem" slot-scope="slotProps">
              <el-table-column
                label="序号"
                width="50"
                align="center"
                prop="certificateNo"
              >
                <template slot-scope="scope">
              {{ (pageIndex - 1) * pageSize + scope.$index + 1 }}
            </template>
              </el-table-column> <el-table-column
                width="180"
                prop="toSociologySort"
                header-align="center"
                align="center"
                label="用户信息"
              >
                <template slot-scope="scope">
                  <div>
                    <span
                      >姓名：{{
                        scope.row.user.name ? scope.row.user.name : "-"
                      }}</span
                    >
                  </div>
                  <div v-if="scope.row.user.tel">
                    <span>手机号：{{ scope.row.user.tel }}</span>
                  </div>
                  <div v-else-if="scope.row.user.email">
                    <span>邮箱：{{ scope.row.user.email }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="湖分"
                width="120"
                align="center"
                prop="certificateNo"
              >
              
              </el-table-column>
              <el-table-column
                label="描述"
               
                align="center"
                prop="certificateNo"
              >
              
              </el-table-column>
             
            

            
              <el-table-column
                prop="createTime"
                header-align="center"
                align="center"
                width="140"
                label="创建日期"
              >
              </el-table-column>
            </template>
          </commonShop>

          <!-- <div
                style="  border: 1px dashed #bababa;"
                v-if="currentNode && currentNode.data.isLast == 1"
              ></div> -->
        </div>
        <div class="submitButton submitButtonBox">
          <el-button
            type="primary"
            @click="dataFormSubmit('addForm')"
            size="small"
            style="float: right;margin-right: 20px;"
            >确定</el-button
          >
          <!-- </div> -->
        </div>
    </div>

    <!-- <el-form
        :inline="true"
        :model="dataForm"
        @keyup.enter.native="getDataList()"
      >
     
        
      </el-form> -->
    <addCertificate v-if="currentNode.data&&currentNode.data.id"
      ref="addCertificate"
      :data="addCertificateForm"
      :labelId="currentNode.data.id"
      pageType="label"
      @refresh="refresh"
    ></addCertificate>
    <commonShopTable
      title="课程"
      CustomOperationText="选择"
      :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>
  </div>
</template>

<script>
import previewimage from "@/views/components/preview-image.vue";
import { quillEditor } from "vue-quill-editor";
import global from "../../common/common.vue"; //引入共用组间
import debounce from "lodash/debounce"; //导入lodash中的debounce
import AddOrUpdate from "@/views/components/commonBookTags/bookTagsForm.vue";
import addCertificate from "./addPoints.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 "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗，斜体，下划线，删除线
  ["blockquote", "code-block"], //引用，代码块
  [{ header: 1 }, { header: 2 }], // 几级标题
  [{ list: "ordered" }, { list: "bullet" }], // 有序列表，无序列表
  [{ script: "sub" }, { script: "super" }], // 下角标，上角标
  [{ indent: "-1" }, { indent: "+1" }], // 缩进
  [{ direction: "rtl" }], // 文字输入方向
  [{ size: ["small", false, "large", "huge"] }], // 字体大小
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
  [{ color: [] }, { background: [] }], // 颜色选择
  [
    {
      font: [
        "SimSun",
        "SimHei",
        "Microsoft-YaHei",
        "KaiTi",
        "FangSong",
        "Arial"
      ]
    }
  ], // 字体
  [{ align: [] }], // 居中
  ["clean"], // 清除样式,
  ["link", "image"] // 上传图片、上传视频
];
// import dialogComponent from './seckillprodrelation'
export default {
  data() {
    return {
      disabled: false,
      restaurants: [],

      options: [],
      state: "",
      timeout: null,
      addCertificateForm: {},
      baseUrl: global.baseUrl,
      isEdit: false,
      checkAll: false,
      isIndeterminate: true,
      dialogVisible: false,
      urlList: {
        treeList: "/master/userCertificate/userCertificateLabelList",
        delete: "/master/userCertificate/delUserCertificateLabel",
        deleteShop: "/master/userCertificate/delCertificate",
        saveShop: "/master/userCertificate/editCertificate",
        add: "/master/userCertificate/saveUserCertificateLabel",
        edit: "/master/userCertificate/editUserCertificateLabel",
        hasBindProductList:
          "/master/userCertificate/userCertificateList",
        CanBindProductList: "/master/courseMedical/getCourseListCanMedical",
        editCourse: "/master/courseMedical/updateCourseToMedicalSort"
      },
      activeName: "first",
      addForm: {},
      audioFileList: [],
      isFresh: false,
      dataRule: {
        name: [
          {
            required: true,
            message: "标签名称不能为空"
            // trigger: "change",
          }
        ]
      },
      fimages: "",
      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"
        }
      ],
      // 富文本编辑器配置
      editorOption: {
        modules: {
          history: {
            delay: 1000,
            maxStack: 50,
            userOnly: false
          },
          toolbar: {
            container: toolbarOptions,
            handlers: {
              image: function(value) {
                // if (value) {
                // 调用element的图片上传组件
                document.querySelector(".avatar-uploader11 input").click();
                // } else {
                //   this.quill.format("image", false);
                // }
              }
            }
          }
        },
        placeholder: "请输入简介说明"
      }
    };
  },
  components: {
    AddOrUpdate,
    addCertificate,
    commonShop,
    commonTree,
    commonShopTable,
    quillEditor,
    previewimage
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  activated() {
    this.isEdit = false;
    this.getDataList();
  },
  methods: {
    refresh(){
      this.$nextTick(()=>{
 this.$refs.commonShop.getAssociatedGoodsList()
      })
     
    },
    getCate(id) {
      this.linshiids = [];

      this.$http({
        url: this.$http.adornUrl("/master/userManage/catalogueListByCourse"),
        method: "post",
        data: this.$http.adornData({
          courseId: id
        })
      })
        .then(({ data }) => {
          if (data && data.code === 0) {
            console.log("data", "data++++++++++++++++++++");
            this.addCertificateForm.cate = data.list;
            // this.addCertificateForm.cate
          } else {
            this.addCertificateForm.cate = [];
            this.linshiids = [];
          }
        })
        .catch(e => {
          console.log("数据报错");
        });
    },

    handleDataFormEdit(data) {
      console.log("data at line 472:", data);

      // this.$nextTick(() => {
      //   this.$refs.addCertificate.init("edit", {
      //     certificateNo:data.certificateNo,
      //     id:data.id,
      //     userId:data.userId,
      //     userKey:data.user.tel||data.user.email,
      //     userName:data.user.name,
      //     courseId:data.courseId,
      //     courseName:data.title,
      //     labelId:data.labelId,
      //     images:data.certificateUrl,
      //   },);
      // });

      // this.selectChange(data.id)
    },

    onprogress() {
      this.$message("上传中，请勿关闭或进行其他操作");
    },
    audioHandleRemove(file, fileList) {
      console.log(file, fileList);
      this.audioFileList = [];
      this.addForm.media = "";
    },
    audioUploadSuccess(res, file) {
      this.audioFileList = [];
      this.audioFileList.push(file);
      this.$message.success("上传成功");
      console.log(this.audioFileList, res, "上传成功");
      this.addForm.media = res.url;
    },
    // 失去焦点事件
    onEditorBlur(quill) {
      //  console.log('editor blur!', quill)
    },
    // 获得焦点事件
    onEditorFocus(quill) {
      //console.log('editor focus!', quill)
    },
    // 准备富文本编辑器
    onEditorReady(quill) {
      // console.log('editor ready!', quill)
    },
    contentUploadSuccess888(res, file) {
      console.log(res);
    },
    contentUploadSuccess(res, file) {
      // console.log(res)
      let quill = this.$refs.myQuillEditor.quill;
      // 如果上传成功
      if (res) {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, "image", res.url);
        // 调整光标到最后
        quill.setSelection(length + 1);
      } else {
        // 提示信息，需引入Message
        this.$message.error("图片插入失败！");
      }
    },
    UpNumber(e) {
      e.target.value = e.target.value.replace(/[^\d]/g, "");
    },
    dataFormEdit() {
      this.checkAll = false;
      this.isEdit = !this.isEdit;
    },
    handleCheckAllChange(val) {
      this.$nextTick(() => {
        this.$refs.commonShop.handleCheckAllChange(val);
      });
    },
    clearCourse() {
      this.addCertificateForm.courseId = "";
      this.addCertificateForm.courseName = "";
      this.addCertificateForm.courseImg = "";
    },
    handleSubmitShopTable: debounce(async function(ids, data) {
      console.log("ids at line 492:", ids, data);
      this.addCertificateForm = {
        courseId: ids,
        courseName: data.title,
        courseImg: data.image
      };
      if (this.$refs.commonShopTable) {
        this.$refs.commonShopTable.close();
      }
      // await this.$http
      //     .request({
      //         url: this.$http.adornUrl(`${this.urlList.saveShop}`),
      //         method: "POST",
      //         data: {
      //             courseId: ids,
      //             medicalId: 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.restaurants = [];

      this.$refs.addCertificate.init("add", {});
      this.$forceUpdate();
      //   this.dialogVisible = true;
      // this.isEdit = false;
      // this.$nextTick(() => {
      //   this.$refs.commonShopTable.dataForm.marketId = this.addForm.id;
      //   this.$refs.commonShopTable.open(this.addForm.id);
      // });
    },
    selectCourse() {
      // this.dialogVisible = true;
      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;
      if (this.addForm.isLast == 0) {
        this.activeName = "first";
      }
      //   this.fimages = this.addForm.icon;
      //   this.audioFileList = [];
      //   if (this.addForm.mediaType == 2 && this.addForm.media != "") {
      //     this.audioFileList.push({
      //       url: this.addForm.media,
      //       name: "audio--"
      //     });
      //   }

      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();
          }
        }
      });
    },
    delImg() {
      this.fimages = "";
      this.addForm.icon = "";
    },
    handlePicSuccess(res, file) {
      this.fimages = res.url;
      //   this.addForm.icon = res.url;
      this.$message.success("上传成功");
      //  console.log(res, "上传");
    },
    handlePicSuccess11() {
      console.log("上传音频---");
    },
    handlePicSuccess111() {
      console.log("上传音频");
    },

    //新增修改
    dataFormSubmit: debounce(async function(formName) {
      //    return false
      if (this.addForm.title == "" || !this.addForm.title) {
        this.$message.error("请输入标签名称");
        return false;
      }

      if (!this.addForm.content) {
        this.addForm.content = "";
      }
      console.log(this.addForm, "this.addForm-----------");
      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.labelId);
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                  }
                });
                // this.$refs.commonShopTable.getAssociatedGoodsList();
                // if (data.Medical.icon && data.Medical.icon != "") {
                //   this.fimages = data.Medical.icon;
                // }

                // this.addForm = data.Medical;
                // this.audioFileList = [];
                // if (this.addForm.mediaType == 2 && this.addForm.media != "") {
                //   this.audioFileList.push({
                //     url: this.addForm.media,
                //     name: "audio"
                //   });
                // }
                ///    this.currentNode = { data: { ...data.Medical } };
              });
            } 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].id;

          // //    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: {
                id: 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,
            icon: "",
            content: "",
            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: "",
        icon: ""
      };
      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.labelList;
          // 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>
.delImgBtn {
  cursor: pointer;
  display: inline-block;
  margin-left: 10px;
}

.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  border-color: #409eff;
  font-size: 28px;
  color: #8c939d;
  width: 70px;
  height: 70px;
  line-height: 70px;
  text-align: center;
}

.avatar {
  width: 70px;
  border: 1px dashed #409eff;
  // border-color: #409eff;
  height: 70px;
  display: block;
}

.tree_box {
  width: 350px !important;
  height: 100%;
  float: left;
  border: 1px solid #bababa;
  border-radius: 10px;
  padding: 15px;
  box-sizing: border-box;
  // background: #fafafa;
}

.flexBox {
  display: flex;
}

.subBox {
  border: 1px solid #d6d6d6;
  border-radius: 10px;
  overflow: hidden;
  width: 49%;
  padding: 10px;
}

.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;
margin-top: 4px;
  border-radius: 10px;
  padding: 15px 15px;
  box-sizing: border-box;
}

.tree_content_box {
  height: calc(100% - 180px) !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;
  }
}

.dataType {
  margin: 20px 0;
  justify-content: center;
}

.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;
  text-align: center;
  margin: 15px auto;
}

// .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;
    margin-bottom: 0;
  }
}

.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;
}

.ql-container {
  min-height: 200px;
}

/deep/ .quill-editor {
  min-height: 200px !important;
}
.loading-spinner {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 24px;
}
</style>
