<template>
  <div class="components-layout-left leftNav">
    <!-- <el-button
      type="primary"
      size="mini"
      @click="callFile"
      style="margin: 0 0 10px 10px"
      >参照图纸</el-button
    > -->
    <!-- <el-select
      v-model="value"
      placeholder="请选择模板"
      class="select"
      @change="TemplateChange"
    >
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      >
      </el-option>
    </el-select> -->
    <!-- <el-form ref="form" :inline="true">
      <el-form-item label="新增页:">
        <el-input v-model="addname"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="addQuery">确定</el-button>
      </el-form-item>
    </el-form> -->
    <el-tabs
      type="card"
      v-model.trim="activeName"
      class="components-layout-right"
      @tab-click="handleClick"
    >
      <el-tab-pane name="first" label="图纸">
        <el-tree
          ref="treeRef"
          :data="dataTree"
          :props="defaultProps"
          node-key="kid"
          highlight-current
          @node-click="handleNodeClick"
          :current-node-key="currentNodekey"
          :default-checked-keys="treeExpandData"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ data.name }}</span>
            <span>
              <i
                class="el-icon-edit"
                slot="reference"
                @click="popover(data)"
              ></i>

              <!-- 删除 -->
              <i class="el-icon-delete" @click="remove(node, data)"></i>
            </span>
          </span>
        </el-tree>
        <!-- 
           -->
      </el-tab-pane>
      <el-tab-pane name="second" label="基本图元">
        <el-collapse v-model="activeKey" accordion>
          <el-collapse-item title="拖动组件" name="1">
            <template slot="title">
              <span :style="`color:${WordColor}`">电力图元</span>
            </template>

            <ul class="svg-nav-list home">
              <li
                v-for="(item, index) in draggableComponentList"
                :key="index"
                class="test"
              >
                <div class="title">{{ item.title }}</div>
                <img
                  :title="item.title"
                  @contextmenu.prevent="openMenu($event, item)"
                  @mousedown="
                    Mousedown(
                      item.type,
                      item.title,
                      item.default_attr,
                      item.create_type
                    )
                  "
                  :src="item.priview_img"
                  draggable="draggable"
                />
              </li>
              <button
                v-show="visible"
                :style="{ left: left + 'px', top: top + 'px' }"
                id="contextmenu"
                @click="handleDelete"
              >
                删除
                <!-- <li @click="handleDelete">删除</li> -->
                <!-- <li @click="handleDownloadFile">下载</li>
                <li @click="handlePreviewFile">预览</li> -->
              </button>
            </ul>
          </el-collapse-item>
          <el-collapse-item title="绘制组件" name="2">
            <template slot="title">
              <span :style="`color:${WordColor}`">基本绘制图元</span>
            </template>
            <ul class="svg-nav-list home">
              <li
                v-for="(item, index) in drawComponentList"
                :key="index"
                class="test"
                :class="
                  $store.state.webtop.CurrentlySelectedToolBar.Type == item.type
                    ? 'toolbar-selected'
                    : ''
                "
              >
                <div class="title">{{ item.title }}</div>
                <img
                  :title="item.title"
                  @contextmenu.prevent="openMenu($event, item)"
                  @mousedown="
                    Mousedown(
                      item.type,
                      item.title,
                      item.default_attr,
                      item.create_type
                    )
                  "
                  :src="item.priview_img"
                />
              </li>
              <button
                v-show="visible"
                :style="{ left: left + 'px', top: top + 'px' }"
                id="contextmenu"
                @click="handleDelete"
              >
                删除
                <!-- <li @click="handleDelete">删除</li> -->
                <!-- <li @click="handleDownloadFile">下载</li>
                <li @click="handlePreviewFile">预览</li> -->
              </button>
            </ul>
          </el-collapse-item>
          <!-- <el-collapse-item title="图表" name="3">
        <template slot="title">
          <span :style="`color:${WordColor}`">图表</span>
        </template>
        <ul class="svg-nav-list">
          <li v-for="(item, index) in chartComponentList" :key="index">
            <div class="title">{{ item.title }}</div>
            <img
              :title="item.title"
              @mousedown="
                Mousedown(
                  item.type,
                  item.title,
                  item.default_attr,
                  item.create_type
                )
              "
              :src="item.priview_img"
              draggable="draggable"
            />
          </li>
        </ul>
      </el-collapse-item>
      <el-collapse-item title="自定义表格" name="4">
        <template slot="title">
          <span :style="`color:${WordColor}`">自定义表格</span>
        </template>
        <ul class="svg-nav-list">
          <li v-for="(item, index) in formComponentList" :key="index">
            <div class="title">{{ item.title }}</div>
            <img
              :title="item.title"
              @mousedown="
                Mousedown(
                  item.type,
                  item.title,
                  item.default_attr,
                  item.create_type
                )
              "
              :src="item.priview_img"
              draggable="draggable"
            />
          </li>
        </ul>
      </el-collapse-item> -->
        </el-collapse>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      title="修改图纸"
      :visible.sync="dialogMenu"
      :append-to-body="true"
      width="380px"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :inline="true">
        <el-form-item label="图纸名称:">
          <el-input
            v-model="addname"
            placeholder="请输入图纸名称"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="modify">确 定</el-button>
      </span>
    </el-dialog>
    <input
      type="file"
      id="file"
      accept="image/*"
      @change="getPicture($event)"
      v-show="false"
    />
  </div>
</template>
<script>
import html2canvas from "html2canvas";
import { find, add } from "@/api/configuration/configuration.js";
import { audit } from "@/api/configuration/configurationList";

export default {
  props: ["svgInfoData", "treeData", "parameters"],
  data() {
    return {
      WordColor: JSON.parse(window.localStorage.echartsColor).WordColor,
      activeName: "first",
      rightClickItem: "",
      visible: false, // 是否展示右键图纸
      top: 0,
      left: 0,
      deleteData: "",
      addname: "",
      dialogMenu: false,
      options: [
        {
          value: "example",
          label: "模板1",
        },
        {
          value: "template",
          label: "模板2",
        },
      ],
      value: "",
      currentNodekey: "",
      dataTree: [],
      defaultProps: {
        label: "name",
        value: "id",
      },
      list: {},
      activeKey: "1", //当前激活的key
      text: `这里是预留位置.`,
      draggableComponentList: [], //拖动组件
      drawComponentList: [], //绘制类型组件
      chartComponentList: [], //图表类型
      formComponentList: [], //表格类型
      treeExpandData: [], //表格类型
      kid: "",
    };
  },
  watch: {
    svgInfoData: {
      deep: true,
      handler(val) {
        this.draggableComponentList = val.filter(
          (f) => f.panel_class == "draggable"
        );
        this.drawComponentList = val.filter((f) => f.panel_class == "draw");
        this.chartComponentList = val.filter((f) => f.panel_class == "chart");
        this.formComponentList = val.filter((f) => f.panel_class == "table");
      },
    },
    // treeData: {
    //   deep: true,
    //   handler(val) {
    //     this.treeExpandData.push(val[0].id);
    //     this.$refs.treeRef.setCurrentKey(val[0].id);
    //     this.dataTree = JSON.parse(JSON.stringify(val));
    //   },
    // },
    treeData: {
      deep: true,
      handler(val) {
        this.dataTree = JSON.parse(JSON.stringify(val));
        this.dataTree.forEach((item, ind) => {
          item.kid = ind;
        });
        if (this.dataTree.length > 0) {
          // this.currentNodekey = this.dataTree[0].kid;
          this.$nextTick(() => {
            this.handleNodeClick(this.dataTree[0]);
            // this.$refs.treeRef.setCurrentKey(this.currentNodekey); //一定要加这个选中了否则样式没有出来
          });
        }
        // // let id = this.dataTree[0].id;
        // let sendData = JSON.parse(this.dataTree[0].path);
        // // this.treeExpandData.push(id);
        // this.$emit("sendData", sendData);
      },
    },

    visible(value) {
      if (value) {
        document.body.addEventListener("click", this.closeMenu);
      } else {
        document.body.removeEventListener("click", this.closeMenu);
      }
    },
  },
  methods: {
    async position() {
      // this.$refs.treeRef.setCurrentKey(this.dataTree[0].kid);

      await this.handleNodeClick(this.dataTree[0]);
      let _this = this;
      await html2canvas(document.getElementById("canvas"), {
        background: "#fff",
        scale: 1,
      }).then(function (canvas) {
        audit({
          name: _this.parameters.name,
          fileContent: canvas.toDataURL(),
          remark: _this.parameters.remark,
          id: _this.parameters.id,
        }).then((res) => {
          // if ((res.code = "A0000")) {
          //   _this.$message({
          //     type: "success",
          //     message: res.message,
          //   });
          // }
        });
        // imgUrl = canvas.toDataURL();
      });
    },
    /**
     * @description: 点击左侧工具栏触发函数
     * @param {*} type
     * @param {*} title
     * @param {*} default_attr 属性默认值
     * @param {*} create_type 组件创建方式
     * @return {*}
     */
    handleNodeClick(data) {
      // this.$nextTick(() => {
      this.list = data;
      this.$refs.treeRef.setCurrentKey(data.kid); //一定要加这个选中了否则样式没有出来
      // });
      let sendData = JSON.parse(data.path);
      this.$emit("sendData", sendData);
    },
    //新增页确定
    addQuery() {
      if (this.addname.length == 0) {
        return this.$message("请输入新增页名称");
      }
      let adddata = {
        // name: this.addname,
        pid: this.parameters.id,
        kid: this.dataTree.length,
        name: this.addname,
        path: "[]",
      };
      this.dataTree.push(adddata);
      setTimeout(() => {
        this.handleNodeClick(this.dataTree[this.dataTree.length - 1]);
      }, 10);
      this.handleClose();
    },
    // 修改
    modify() {
      this.dataTree.forEach((item) => {
        if (item.kid == this.kid) {
          item.name = this.addname;
        }
      });
      this.handleClose()
    },
    popover(e) {
      this.dialogMenu = true;
      this.kid = JSON.parse(JSON.stringify(e)).kid;
      this.addname = JSON.parse(JSON.stringify(e)).name;
    },
    handleClose() {
      this.dialogMenu = false;
      this.addname = "";
    },
    // 删除
    remove(node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex((d) => d.kid === data.kid);
      children.splice(index, 1);
    },
    // 打开右键图纸
    openMenu(e, item) {
     // console.log(e, item);
     // console.log(this.svgInfoData);
      this.deleteData = item;
      this.visible = true;
      this.top = e.clientY;
      this.left = e.clientX;
      this.rightClickItem = item;
    },
    // 关闭右键图纸
    closeMenu() {
      this.visible = false;
    },

    handleDelete() {
      for (let index = 0; index < this.svgInfoData.length; index++) {
        if (this.deleteData == this.svgInfoData[index]) {
          this.svgInfoData.splice(index, 1);
        }
      }
     // console.log(this.svgInfoData);
      let form = new FormData();
      const blob = new Blob([JSON.stringify(this.svgInfoData)], {
        type: "application/json",
      });
      form.append("multipartFile", blob);
      add(form).then((res) => {
        if (res.code == "A0000") {
          this.$message({
            message: res.message,
            type: "success",
          });
        }
        find().then((res) => {
          let jsonData = JSON.parse(res.data.json);
          this.svgInfoData = jsonData;
        });
      });
    },
    handleDownloadFile() {},
    handlePreviewFile() {},
    handleClick(tab, event) {},
    Mousedown(type, title, default_attr, create_type) {
    //  console.log(default_attr, "11111111111111111111111111");
      let CurrentlySelectedToolBar = {
        Type: type, //选中的工具栏svg类型
        TypeName: title, //选中的工具栏svg类型名称
        Title: title, //选中的工具栏svg标题
        Color: default_attr.color, //选中的工具栏svg颜色
        CreateType: create_type, //选中工具栏的创建方式
        EChartsOption: default_attr.echarts_option,
        List: default_attr.list_data,
        TableHeader: default_attr.tableHeader,
        Display: default_attr.display,
      };
      this.$store.dispatch(
        "webtop/setCurrentlySelectedToolBarAction",
        CurrentlySelectedToolBar
      );
    },
    // 选择模板
    TemplateChange(e) {
     // console.log(e);
      this.$emit("testA", e);
    },

    // 本地上传
    getPicture(e) {
      //预览图片
      let src = window.URL.createObjectURL(e.target.files[0]);
      this.$emit("backgroundSRC", src);

      //将图片文件转化成base64格式图片
      // var reader = new FileReader();
      // reader.onload = (e) => {
      //   //e.target.result  就是从本地读取的图片的base64格式,将它上传给服务器即可
      //   //使用axios的post方法上传即可
      // };
      // reader.readAsDataURL(e.target.files[0]);
    },
    callFile() {
      //点击添加图片按钮，触发type:"file"的input标签
      let fileDom = document.querySelector("#file");
      fileDom.click();
    },
  },
};
</script>
<style lang="scss" scoped>

.home {
  // display: flex;
  // justify-content: space-around;
  // width: 100%;
  // height: 600px;
  // .test{
  // width: 80px;
  // height: 60px;
  // background-color pink;
  //   text-align:center;
  //   font-size:32px;
  //   color: green;
  // }
  #contextmenu {
    position: fixed;
    // background: #fff;
    z-index: 99999;
    margin: 7px;
    // list-style-type: none;
    // padding: 5px 0;
    // border-radius: 4px;
    font-size: 16px;
    font-weight: 400;
    // color: #333;
    // box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);
  }
  // #contextmenu .contextmenu {
  //   margin: 0;
  //   padding: 7px 16px;
  //   cursor: pointer;
  // }
  // #contextmenu .contextmenu:hover {
  //   background: #eee;
  // }
}
.components-layout-left .ant-input-search-icon {
  font-size: 20px !important;
  color: #1890ff !important;
}
.components-layout-left .ant-collapse,
.components-layout-left .ant-collapse-content,
.components-layout-left .ant-collapse > .ant-collapse-item {
  border-color: #eee !important;
}
.components-layout-left .ant-collapse-content > .ant-collapse-content-box {
  padding: 16px 0;
}
.ant-input-affix-wrapper {
  height: 45px;
  line-height: 45px;
  border: none;
}
.svg-nav-list {
  display: flex;
  padding: 0;
  margin: 0;
  list-style: none;
  flex-wrap: wrap;

  li {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    width: calc(33.33% - 30px);
    padding: 0;
    margin: 0 15px 15px 15px;
    cursor: pointer;
    border-radius: 50%;
    box-shadow: 1px 1px 5px #ddd;

    &:hover {
      box-shadow: 1px 1px 10px #ccc;
    }

    img {
      display: block;
      width: 100%;
    }

    .title {
      position: absolute;
      right: 0;
      bottom: 0;
      left: 0;
      display: none;
      height: 20px;
      font-size: 12px;
      line-height: 20px;
      color: #fff;
      text-align: center;
      background: rgba(0, 0, 0, 0.4);
    }
  }

  &.two-item {
    li {
      width: calc(50% - 30px);
      height: 100px;
      margin-bottom: 25px;
      border-radius: 10px;

      img {
        width: auto;
        height: 100%;
      }
    }
  }
}
.toolbar-selected {
  outline: 1px solid #0cf;
}
.leftNav {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  z-index: 1;
  width: 260px !important;
  max-width: unset !important;
  min-width: unset !important;
  overflow: auto;
}
::v-deep .el-collapse-item__header {
  padding-left: 10px;
  font-size: 16px;
  // color:;
  background-color: transparent !important;
}
.select {
  width: 100%;
  padding: 0 10px 10px 10px;
}
::v-deep .el-collapse-item__wrap {
  padding: 10px 0 0 0;
  background-color: transparent !important;
}
::v-deep .el-tree-node:focus > .el-tree-node__content {
  background-color: rgba(0, 48, 120, 0.5) !important;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
