<template>
  <div class="vdr_tree">
    <vue-draggable-resizable
      class="vdrtree"
      style="z-index: 2;"
      :parent="true"
      :w="400"
      :h="600"
      :minw="150"
      :minh="250"
      :active="true"
      :drag-cancel="'.cancel'"
      :handles="['br']"
      @deactivated="onDeactivated"
      :resizable="false"
      :x="31"
      :y="35"
    >
      <div class="div_tree">
        <div class="tree_top">
          <span>{{isEdit}}</span>
          <img class="top_img" @click="hide" src="@/assets/shanchu.png">
        </div>
        <div class="cancel">
          <el-input
            class="tree_input"
            placeholder="输入关键字查询"
            v-model="filterText"
            maxlength="20"
            suffix-icon="el-icon-search"
            clearable
          ></el-input>
          <img class="cancel_img" v-if="editT" @click="edit" src="@/assets/bianji.png">
          <img class="cancel_img" v-else @click="editStop" src="@/assets/tuichubianji.png">
        </div>
        <div
          style="height:480px;"
          v-loading="loading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
        >
          <el-scrollbar style="height:100%" ref='myScrollbar'>
            <div class="filter-tree">
              <el-tree
                v-if="editT"
                show-checkbox
                default-expand-all
                :highlight-current="true"
                :expand-on-click-node="true"
                :default-checked-keys="treeCheckedArr"
                @node-click="nodeClick"
                @check="checkSelect"
                @node-contextmenu="getRigInfo"
                node-key="rownum"
                :data="list"
                :props="defaultProps"
                :filter-node-method="filterNode"
                ref="tree"
              >
                <span slot-scope="{ node, data }">
                  <img alt="" v-if="data.type == 'MODEL'" src="@/assets/goujian.png">
                  <img alt="" v-else src="@/assets/wenjianjia.png">
                  <span class="tree-node__label">{{ node.label }}</span>
                </span>
              </el-tree>
              <el-tree
               v-else
              :data="list"
              :default-expand-all="true"
              :highlight-current="true"
              @node-click="checkSelects"
              @node-contextmenu="getRigInfo"
              :expand-on-click-node="false"
              class="filter-tree"
              :props="defaultProps"
              :filter-node-method="filterNodes"
              ref="trees"
            >
            <span slot-scope="{ node, data }">
                  <img alt="" v-if="data.type == 'MODEL'" src="@/assets/goujian.png">
                  <img alt="" v-else src="@/assets/wenjianjia.png">
                  <span class="tree-node__label">{{ node.label }}</span>
                </span>
              <!-- <span slot-scope="{ node, data }">
                <el-radio v-model="radioTree" :label="data.rownum">
                  <span class="tree-node__label">{{ node.label }}</span>
                </el-radio>
              </span> -->
            </el-tree>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </vue-draggable-resizable>
    <div
      class="right_menu"
      v-show="isShowTreeMenu"
      :style="{'left':onContextmenuTarget.x,'top':onContextmenuTarget.y}"
      ref="treeRight"
    >
      <div style="height:100%;width:100%;">
        <button
          class="right_button"
          @click="treeFolder"
          :class="(type == 'PROJECT' || type == 'STAGING' || type == 'MODEL') ? 'disabled':''"
          :disabled="type == 'PROJECT' || type == 'STAGING' || type == 'MODEL'"
        >添加同级文件夹</button>
        <button
          class="right_button" @click="treeNode"
          :class="(type == 'ROOM' || type == 'PROJECT' || type == 'MODEL') ? 'disabled':''"
          :disabled="type == 'ROOM' || type == 'PROJECT' || type == 'MODEL'"
        >添加子文件夹</button>
        <button
          class="right_button"
          @click="treeDelete"
          :class="(createBy == 'SAP'||createBy == 'JX' || type == 'PROJECT' ||
          dels == false || type == 'ROOM') ? 'disabled':''" :disabled="createBy == 'SAP'||createBy == 'JX'
          || type == 'PROJECT' || dels == false || type == 'ROOM'"
        >删除</button>
        <button
          class="right_button"
          @click="treeRename"
          :class="(createBy == 'SAP'||createBy == 'JX' || type == 'PROJECT' || type == 'ROOM'
            || type == 'MODEL') ? 'disabled':''" :disabled="createBy == 'SAP'||createBy == 'JX'
            || type == 'PROJECT' || type == 'ROOM' || type == 'MODEL'"
        >重命名</button>
      </div>
    </div>
    <!--新增事件节点分类弹窗-->
    <el-dialog
      :title="add"
      width="25%"
      :close-on-click-modal="false"
      class="add-event-dialog"
      :visible.sync="addEventdialogVisible"
    >
      <el-form ref="form" :model="form" :rules="addEventNodeRules">
        <el-form-item label="文件夹名称" prop="name" label-width="100px">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addEventFormCancleBtn">取 消</el-button>
        <el-button type="primary" @click="addEventFormSubmitBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'tree',
  data() {
    return {
      alike: false,
      radioTree: '',
      loading: false,
      add: '',
      name: '',
      id: '',
      innerNo: '',
      type: '',
      sourceId: '',
      sourceType: '',
      createBy: '',
      projectNoType: [],
      projectNo: sessionStorage.getItem('projectNo'),
      projectId: sessionStorage.getItem('projectId'),
      projectName: '',
      stagingNo: '',
      buildNo: '',
      buildName: '',
      floorName: '',
      floorNo: '',
      dels: false,
      addEventNodeRules: {
        name: [
          { required: true, message: '请输入文件夹名称', trigger: 'blur' },
          { max: 20, message: '长度在20个字符内', trigger: 'blur' }
        ]
      },
      addEventdialogVisible: false,
      form: {
        name: ''
      },
      editT: true,
      onContextmenuTarget: {
        x: 0,
        y: 0
      },
      isEdit: '结构树',
      isShowTreeMenu: false,
      treeCheckedArr: [],
      list: [],
      filterText: '',
      defaultProps: {
        children: 'list',
        label: 'name'
      },
      curModelList: '',
      firstList: [],
      secondList: []
    };
  },
  watch: {
    filterText(val) {
      // 输入框搜索过滤
      if (val && val.length > 0) {
        if (this.editT) {
          this.$refs.tree.filter(val);
        } else {
          this.$refs.trees.filter(val);
        }
      } else {
        this.search();
      }
    }
  },
  methods: {
    onDeactivated() { },
    checkSelects(data) {
      // 树形控件被点击
      this.isShowTreeMenu = false;
      this.radioTree = data.rownum;
    },
    filterNode(value, data) {
      // 搜索返回正确值
      if (!value) {
        return true;
      }
      if (data.name) {
        return data.name.indexOf(value) !== -1;
      }
    },
    filterNodes(value, data) {
      // 搜索返回正确值
      if (!value) {
        return true;
      }
      if (data.name) {
        return data.name.indexOf(value) !== -1;
      }
    },
    checkSelect(data, nodes) {
      console.log(1111111111111111111111111111111111111111111111111111111111, data, nodes);
      // 勾选复选框函数
      this.treeCheckedArr = [];
      if (nodes.checkedNodes.length < 1) {
        console.log('555555555555555555555555');
        this.delModelNeedInnerNo = '';
        this.treeCheckedArr = [];
        this.$store.commit('SET_VIEW_ID', null);
        sessionStorage.setItem('treeCheckedArr', []);
        // sessionStorage.setItem('modelNo', {});
      } else {
        nodes.checkedNodes.forEach(item => {
          if (item.rownum) {
            this.treeCheckedArr.push(item.rownum);
          }
        });
        sessionStorage.setItem('treeCheckedArr', JSON.stringify(this.treeCheckedArr));
        if (data.type === 'MODEL') {
          const viewId = data.innerNo || '';
          this.$store.commit('SET_VIEW_ID', viewId);
        }
      }
      if (data.type && data.type === 'MODEL') {
        let projectNoType = '';
        if (nodes && nodes.halfCheckedNodes.length > 0) {
          const leng = nodes.halfCheckedNodes.length - 1;
          const len = nodes.checkedNodes.length - 1;
          const cn = nodes.checkedNodes;
          if (cn[0].type !== cn[len].type && cn[len].type === data.type) {
            projectNoType = nodes.checkedNodes[0].type;
          } else {
            projectNoType = nodes.halfCheckedNodes[leng].type;
          }
          this.$store.commit('SET_PROJECT_ID_TYPE', projectNoType);
        } else {
          this.$store.commit('SET_PROJECT_ID_TYPE', '');
          this.$store.commit('SET_VIEW_ID', '');
          // sessionStorage.setItem('treeCheckedArr', []);
          // sessionStorage.setItem('modelNo', {});
        }
      }
      // else if (data.type && data.type !== 'MODEL') {
      //   const projectNoType = {};
      //   const modelList = [];
      //   if (nodes && nodes.checkedNodes.length > 0) {
      //     nodes.checkedNodes.forEach(item => {
      //       if (item.type === 'MODEL') {
      //         modelList.push(item);
      //       }
      //     });
      //     const les = modelList.length - 1;
      //     projectNoType.treeType = modelList[les].type;
      //     projectNoType.projectNo = modelList[les].projectNo;
      //     projectNoType.stagingNo = modelList[les].stagingNo;
      //     projectNoType.innerNo = modelList[les].innerNo;
      //     this.$store.commit('SET_PROJECT_ID_TYPE', projectNoType);
      //     this.$store.commit('SET_VIEW_ID', projectNoType.innerNo);
      //   } else {
      //     this.$store.commit('SET_PROJECT_ID_TYPE', {});
      //     this.$store.commit('SET_VIEW_ID', '');
      //   }
      // }
      this.$store.commit('SET_CUR_MODEL_ID', data.filePath);
      let modelId = [];
      nodes.halfCheckedNodes.forEach(item => {
        if (item.filePath) {
          modelId.push(item.filePath);
        }
      });
      nodes.checkedNodes.forEach(item => {
        if (item.filePath) {
          modelId.push(item.filePath);
        }
      });
      this.secondList = this.arrFilter(this.firstList, modelId);
      this.curModelList = `${modelId}&${this.secondList}`;
      // console.log('===========go', this.curModelList);

      modelId = modelId.join(',');
      this.$store.commit('SET_MODEL_ID', this.curModelList);
    },
    arrFilter(firstArr, secondArr) {
      // 勾选操作两次对比
      let newArr = [];
      newArr = firstArr.filter(item => {
        return !secondArr.includes(item);
      });
      this.firstList = secondArr;
      return newArr.join(',');
    },
    addEventFormCancleBtn() {
      // 取消
      this.addEventdialogVisible = false;
    },
    addEventFormSubmitBtn() {
      // 确定
      this.$refs.form.validate(valid => {
        if (!valid) {
          return false;
        }
      });
      let url = '';
      let datas = {};
      if (this.add === '添加同级文件夹') {
        if (this.type === 'STAGING') {
          url = '/project/addOrUpdateStaging';
          datas = {
            projectNo: this.projectNo,
            projectId: this.projectId,
            projectName: this.projectName,
            name: this.form.name
          };
        } else if (this.type === 'BUILD') {
          url = '/project/addOrUpdateBuilding';
          datas = {
            projectNo: this.projectNo,
            projectId: this.projectId,
            projectName: this.projectName,
            name: this.form.name,
            stagingNo: this.stagingNo
          };
        } else if (this.type === 'FLOOR') {
          url = '/project/addOrUpdateFloor';
          datas = {
            projectNo: this.projectNo,
            projectId: this.projectId,
            projectName: this.projectName,
            name: this.form.name,
            stagingNo: this.stagingNo,
            buildName: this.buildName,
            buildNo: this.buildNo
          };
        } else if (this.type === 'ROOM') {
          url = '/project/addOrUpdateRoom';
          datas = {
            projectNo: this.projectNo,
            projectId: this.projectId,
            projectName: this.projectName,
            innerNo: this.form.name,
            stagingNo: this.stagingNo,
            buildNo: this.buildNo,
            floorNo: this.floorNo,
            buildName: this.buildName,
            floorName: this.floorName,
            isRoom: '1'
          };
        }
      } else if (this.add === '添加子文件夹') {
        if (this.type === 'PROJECT') {
          url = '/project/addOrUpdateStaging';
          datas = {
            projectNo: this.innerNo,
            projectId: this.id,
            projectName: this.name,
            name: this.form.name
          };
        } else if (this.type === 'STAGING') {
          url = '/project/addOrUpdateBuilding';
          datas = {
            projectNo: this.projectNo,
            projectId: this.projectId,
            projectName: this.projectName,
            name: this.form.name,
            stagingNo: this.innerNo
          };
        } else if (this.type === 'BUILD') {
          url = '/project/addOrUpdateFloor';
          datas = {
            projectNo: this.projectNo,
            projectId: this.projectId,
            projectName: this.projectName,
            name: this.form.name,
            stagingNo: this.stagingNo,
            buildName: this.buildName,
            buildNo: this.innerNo
          };
        } else if (this.type === 'FLOOR') {
          url = '/project/addOrUpdateRoom';
          datas = {
            projectNo: this.projectNo,
            projectId: this.projectId,
            projectName: this.projectName,
            innerNo: this.form.name,
            stagingNo: this.stagingNo,
            buildNo: this.buildNo,
            floorNo: this.innerNo,
            buildName: this.buildName,
            floorName: this.floorName,
            isRoom: '1'
          };
        }
      } else if (this.add === '重命名') {
        if (this.type === 'STAGING') {
          url = '/project/addOrUpdateStaging';
          datas = {
            projectNo: this.projectNo,
            innerNo: this.innerNo,
            projectId: this.projectId,
            projectName: this.projectName,
            name: this.form.name
          };
        } else if (this.type === 'BUILD') {
          url = '/project/addOrUpdateBuilding';
          datas = {
            projectNo: this.projectNo,
            projectId: this.projectId,
            projectName: this.projectName,
            name: this.form.name,
            stagingNo: this.stagingNo,
            innerNo: this.innerNo
          };
        } else if (this.type === 'FLOOR') {
          url = '/project/addOrUpdateFloor';
          datas = {
            projectNo: this.projectNo,
            projectId: this.projectId,
            projectName: this.projectName,
            name: this.form.name,
            stagingNo: this.stagingNo,
            buildName: this.buildName,
            buildNo: this.buildNo,
            innerNo: this.innerNo
          };
        } else if (this.type === 'ROOM') {
          url = '/project/addOrUpdateRoom';
          datas = {
            projectNo: this.projectNo,
            projectId: this.projectId,
            projectName: this.projectName,
            innerNo: this.form.name,
            stagingNo: this.stagingNo,
            buildNo: this.buildNo,
            floorNo: this.floorNo,
            // innerNo: this.innerNo,
            buildName: this.buildName,
            floorName: this.floorName,
            isRoom: '1'
          };
        }
      }
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.$axios(url, datas, 'POST')
        .then(data => {
          loading.close();
          let messages = '';
          let types = '';
          if (data.data) {
            messages = data.data.message;
            types = 'success';
          } else {
            messages = '项目房间名称重复,新增失败';
            types = 'warning';
          }
          this.addEventdialogVisible = false;
          this.$message({
            message: messages,
            type: types
          });
          this.search();
          // console.log(data);
        })
        .catch(data => {
          loading.close();
          // console.log('=======================ssss', data);
        });
    },
    treeFolder() {
      // 添加同级文件夹
      this.isShowTreeMenu = false;
      this.add = '添加同级文件夹';
      this.addEventdialogVisible = true;
    },
    treeNode() {
      // 添加子文件夹
      this.isShowTreeMenu = false;
      this.add = '添加子文件夹';
      this.addEventdialogVisible = true;
    },
    treeDelete() {
      // 删除
      let url = '';
      let datas = {};
      this.isShowTreeMenu = false;
      if (this.createBy === 'SAP' || this.createBy === 'JX') {
        return false;
      }
      if (this.type === 'PROJECT') {
        return false;
      }
      if (this.type === 'STAGING') {
        url = '/project/deleteStaging';
        datas = {
          innerNo: this.innerNo,
          projectNo: this.projectNo
        };
      } else if (this.type === 'BUILD') {
        url = '/project/deleteBuilding';
        datas = {
          innerNo: this.innerNo,
          projectNo: this.projectNo,
          stagingNo: this.stagingNo
        };
      } else if (this.type === 'FLOOR') {
        url = '/project/deleteFloor';
        datas = {
          innerNo: this.innerNo,
          projectNo: this.projectNo,
          stagingNo: this.stagingNo,
          buildNo: this.buildNo
        };
      } else if (this.type === 'ROOM') {
        url = '/project/deleteRoom';
        datas = {
          innerNo: this.innerNo,
          projectNo: this.projectNo,
          stagingNo: this.stagingNo,
          buildNo: this.buildNo,
          floorNo: this.floorNo
        };
      } else if (this.type === 'MODEL') {
        url = '/modelView/deleteViewRelation';
        datas = [{
          modelId: this.innerNo,
          sourceType: this.sourceType,
          sourceId: this.sourceId
        }];
      }
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$axios(url, datas, 'POST')
            .then(res => {
              if (res && res.data) {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                this.$store.commit('SET_MODEL_ID', 'del');
                this.search();
              } else {
                this.$message({
                  type: 'warning',
                  message: '删除失败!'
                });
              }
              // console.log(data);
            })
            .catch(resultMsg => {
              // console.log(resultMsg);
            });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    treeRename() {
      // 重命名
      this.isShowTreeMenu = false;
      this.add = '重命名';
      this.addEventdialogVisible = true;
    },
    getRigInfo(e, data) {
      // 右键事件
      this.isShowTreeMenu = false;
      if (this.editT) {
        return;
      }
      // if (data.type === 'MODEL' && (!this.delModelNeedInnerNo || this.delModelNeedInnerNo !== data.innerNo)) {
      //   return;
      // }
      this.dels = false;
      if (!data.list || data.list.length < 1) {
        this.dels = true;
      } else {
        this.dels = false;
      }
      this.form.name = '';
      this.createBy = '';
      this.id = '';
      this.name = '';
      this.innerNo = '';
      this.type = '';
      this.projectNo = '';
      this.projectName = '';
      this.projectId = '';
      this.stagingNo = '';
      this.buildNo = '';
      this.buildName = '';
      this.floorNo = '';
      this.floorName = '';
      this.sourceId = '';
      this.sourceType = '';
      this.sourceType = data.sourceType || '';
      this.sourceId = data.sourceId || '';
      this.id = data.id || '';
      this.name = data.name || '';
      this.type = data.type || '';
      this.innerNo = data.innerNo || '';
      this.createBy = data.createBy || '';
      this.projectNo = data.projectNo || '';
      this.projectId = data.projectId || '';
      this.projectName = data.projectName || '';
      this.stagingNo = data.stagingNo || '';
      this.buildNo = data.buildNo || '';
      this.floorNo = data.floorNo || '';
      this.buildName = data.buildName || '';
      this.floorName = data.floorName || '';
      this.isShowTreeMenu = true;
      setTimeout(() => {
        const currentHeiht = document.body.clientHeight;
        const plusHeight = this.$refs.treeRight.offsetHeight;
        if (currentHeiht - 220 <= e.pageY) {
          this.onContextmenuTarget.x = e.pageX + 'px';
          this.onContextmenuTarget.y = e.pageY - plusHeight + 'px';
        } else {
          this.onContextmenuTarget.x = e.pageX + 'px';
          this.onContextmenuTarget.y = e.pageY + 'px';
        }
      });
    },
    nodeClick(data, a, b) {
      // 点击
      console.log('============in ', data, a, b);
      if (data.type === 'MODEL') {
        const viewId = data.innerNo || '';
        const modelNo = {};
        modelNo.projectNo = data.projectNo;
        modelNo.stagingNo = data.stagingNo;
        this.$store.commit('SET_VIEW_ID', viewId);
        sessionStorage.setItem('modelNo', JSON.stringify(modelNo));
        const indexArr = sessionStorage.getItem('treeCheckedArr')
          ? JSON.parse(sessionStorage.getItem('treeCheckedArr'))
          : [];
        for (let i = 0; i < indexArr.length; i++) {
          if (data.rownum === indexArr[i]) {
            // 判断是否关联
            this.alike = true;
            break;
          } else {
            this.alike = false;
          }
        }
        console.log('============in111111111111111111111111111111111111 ', indexArr, this.alike);
        if (this.alike) {
          this.$eventHub.$emit('bus-warehouseModel', true);
        } else {
          this.$eventHub.$emit('bus-warehouseModel', false);
        }
      }
      this.$store.commit('SET_CUR_MODEL_ID', data.filePath);
      // console.log('=================node', data, a, b);
      this.isShowTreeMenu = false;
    },
    search() {
      // 列表查询
      this.loading = true;
      const projectNo = sessionStorage.getItem('projectNo')
        ? sessionStorage.getItem('projectNo')
        : '';
      this.$axios(
        '/project/queryProjectTree',
        {
          projectNo: projectNo,
          dataNodes: [0, 1, 2, 3, 4, 5]
        },
        'POST'
      )
        .then(data => {
          this.loading = false;
          this.list = [];
          this.list.push(data.data.value);
          this.treeCheckedArr = sessionStorage.getItem('treeCheckedArr')
            ? JSON.parse(sessionStorage.getItem('treeCheckedArr'))
            : [];
        })
        .catch(resultMsg => {
          this.loading = false;
          //  console.log('=========error', resultMsg);
        });
    },
    hide() {
      // 组件关闭
      this.$emit('treeSwitch', false);
      this.$eventHub.$emit('bus-treeSwitch', false);
    },
    edit() {
      // 编辑
      this.editT = false;
      this.isEdit = '编辑结构树';
    },
    editStop() {
      // 不编辑
      this.filterText = '';
      this.isShowTreeMenu = false;
      sessionStorage.setItem('treeCheckedArr', []);
      this.editT = true;
      this.isEdit = '结构树';
      this.search();
      this.$refs['myScrollbar'].wrap.scrollTop = 0;
    }
  },
  computed: {},
  created: function() { },
  beforeMount: function() { },
  mounted: function() {
    this.search();
  },
  beforeDestroy: function() { },
  destroyed: function() { },
  directives: {}
};
</script>
