<template>
  <div class="vdr_viewpoint">
    <vue-draggable-resizable
      class="vdrviewpoint"
      :w="292"
      :h="500"
      style="z-index: 1;"
      :minw="200"
      :minh="250"
      :active="true"
      :drag-cancel="'.cancel'"
      :handles="['br']"
      @deactivated="onDeactivated"
      :parent="true"
      :resizable="false"
      :x="615"
      :y="35"
    >
      <div class="div_tree" style="width:100%;height:100%;">
        <div class="tree_top">
          <span>视点</span>
          <img class="top_img" @click="hide" src="@/assets/shanchu.png">
        </div>
        <div class="cancel">
          <el-input
            class="tree_input"
            placeholder="输入关键字查询"
            v-model="filterText"
            suffix-icon="el-icon-search"
            clearable
            @clear="clears"
          ></el-input>
          <img class="cancel_img" @click="adds" src="@/assets/xinzeng.png">
        </div>
        <div
          style="height:350px;"
          v-loading="loading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
        >
          <el-scrollbar style="height:100%;">
            <div class="filtertree">
              <div
                style="text-align: center;margin-top: 30px;"
                v-if="list.length === 0 && seasrchs"
              >没有查询到数据!</div>
              <!-- <el-tooltip placement="left" effect="light" v-for="(item,index) of list" :key="index"> -->
              <el-popover
                placement="left"
                width="250"
                trigger="hover"
                v-for="(item,index) of list"
                :key="index"
              >
                <div>
                  <p style="word-wrap:break-word;">{{item.content}}</p>
                  <br>
                  <p>
                    <span style="float:left;width:90px;overflow: hidden;
                    text-overflow: ellipsis;white-space: nowrap;">{{item.userName}}</span>
                    <span style="float:right;width:150px;">{{item.createrTime}}</span>
                  </p>
                </div>
                <div
                  class="div_radio"
                  slot="reference"
                  @click="left_Change(item)"
                  @contextmenu.prevent="right_menu(item,index,$event)"
                >
                  <el-radio v-model="radio" :label="index">{{item.name}}</el-radio>
                </div>
              </el-popover>
              <!-- </el-tooltip> -->
            </div>
          </el-scrollbar>
        </div>
      </div>
    </vue-draggable-resizable>
    <div
      class="right_menu"
      v-if="ShowMenu"
      :style="{'left':onContextmenuTarget.x,'top':onContextmenuTarget.y}"
      ref="treeR"
    >
      <div style="height:100%;width:100%;">
        <button class="right_button" @click="markEdit">编辑</button>
        <button class="right_button" @click="markDelete">删除</button>
      </div>
    </div>
    <el-dialog
      :title="title"
      top="20%"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      width="20%"
    >
      <el-form ref="from" :model="from" :rules="fromRule">
        <el-form-item prop="name">
          <el-input v-model="from.name" placeholder="请输入视点名称" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            style="margin-top:20px;"
            type="textarea"
            :rows="3"
            resize="none"
            maxlength="100"
            placeholder="请输入视点描述"
            v-model="from.content"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'viewpoint',
  data() {
    return {
      seasrchs: false,
      loading: false,
      from: {
        name: '',
        content: ''
      },
      fromRule: {
        name: [
          { required: true, message: '请输入视点名称', trigger: 'blur' },
          { max: 20, message: '长度在20个字符内', trigger: 'blur' }
        ]
      },
      onContextmenuTarget: {
        x: 0,
        y: 0
      },
      editY: true,
      ShowMenu: false,
      list: [],
      filterText: '',
      radio: '',
      dialogVisible: false,
      viewpointModel: ''
    };
  },
  watch: {
    filterText(val) {
      // 输入框过滤搜索
      if (!val) {
        this.search();
      } else {
        this.list = this.list.filter(item => (~item.name.indexOf(val)));
      }
    }
  },
  methods: {
    onDeactivated() { },
    clears() {
      // 清空输入框
      this.search();
    },
    handleClose(done) {
      // 关闭弹窗
      if (this.$refs.from !== undefined) {
        this.$refs.from.resetFields();
      }
      done();
      this.search();
    },
    markEdit() {
      // 视点编辑
      this.editY = true;
      this.ShowMenu = false;
      this.dialogVisible = true;
    },
    markDelete() {
      // 视点删除
      this.ShowMenu = false;
      this.$confirm(`是否要删除视点 ${this.from.name}`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true
      })
        .then(() => {
          this.$axios(`/modelView/deletePoint`, { 'id': this.from.id }, 'GET')
            .then(res => {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.search();
              this.radio = '';
            })
            .catch(resultMsg => {
              // console.log(resultMsg);
            });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    right_menu(item, index, $event) {
      // 右键事件
      if (this.radio !== index) {
        this.ShowMenu = false;
      } else {
        this.from.id = item.id;
        this.from.name = item.name;
        this.from.content = item.content;
        this.ShowMenu = true;
        setTimeout(() => {
          const currentHeiht = document.body.clientHeight;
          const plusHeight = this.$refs.treeR.offsetHeight;
          if (currentHeiht - 220 <= $event.pageY) {
            this.onContextmenuTarget.x = $event.pageX + 'px';
            this.onContextmenuTarget.y = $event.pageY - plusHeight + 'px';
          } else {
            this.onContextmenuTarget.x = $event.pageX + 'px';
            this.onContextmenuTarget.y = $event.pageY + 'px';
          }
        }, 0);
      }
    },
    left_Change(item) {
      // 鼠标左键点击事件
      if (item && item.cameraContent) {
        // console.log('==========444');
        sessionStorage.setItem('tree-viewId', item.viewId);
        this.$store.commit('SET_VIEWPOINT_CONTENT', item.cameraContent);
      } else {
        this.$store.commit('SET_VIEWPOINT_CONTENT', '');
      }
      this.ShowMenu = false;
    },
    hide() {
      // 关闭组件
      this.$emit('viewpointSwitch', false);
      this.$eventHub.$emit('bus-viewpointSwitch', false);
    },
    adds() {
      // 新增
      this.from = {
        name: '',
        content: ''
      };
      this.editY = false;
      this.dialogVisible = true;
      this.$eventHub.$emit('bus-setVeiwpointModel', this.dialogVisible);
    },
    search() {
      // 列表查询接口
      this.loading = true;
      const projectId = sessionStorage.getItem('projectId')
        ? sessionStorage.getItem('projectId')
        : '';
      this.$axios('/modelView/queryPointList', { projectId: projectId }, 'POST')
        .then(res => {
          this.seasrchs = true;
          this.loading = false;
          this.list = [];
          this.list = res.data.value;
          this.radio = '';
        })
        .catch(resultMsg => {
          this.seasrchs = true;
          this.loading = false;
          // console.log(resultMsg);
        });
    },
    cancel() {
      // 关闭弹窗
      this.$refs.from.resetFields();
      this.dialogVisible = false;
      this.search();
    },
    save() {
      // 保存
      // console.log('=========this.$refs.from', this.$refs.from);
      this.$refs.from.validate(valid => {
        // console.log('==============valid==', valid);
        if (!valid) {
          // console.log('=====================in returh');
        } else {
          // 要保存的视图数据 this.viewpointModel
          this.viewpointModel = this.$store.state.modelview.modelViewSnapshot
            ? this.$store.state.modelview.modelViewSnapshot
            : '';
          // console.log(this.viewpointModel);
          let url = '';
          if (this.editY === true) {
            url = '/modelView/editPoint';
          } else if (this.editY === false) {
            url = '/modelView/addPoint';
            // 将视图数据拼接到from里
            this.from.cameraContent = this.viewpointModel;
            this.from.viewId = sessionStorage.getItem('tree-viewId');
            this.from.projectId = sessionStorage.getItem('projectId');
          }
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          this.$axios(url, this.from, 'POST')
            .then(res => {
              loading.close();
              this.$message({
                message: res.data.message,
                type: 'success'
              });
              this.dialogVisible = false;
              this.search();
            })
            .catch(resultMsg => {
              // console.log('add tag error', resultMsg);
            });
        }
      });
    }
  },
  computed: {
    title() {
      return this.editY ? '编辑视点' : '新建视点';
    }
  },
  created: function() { },
  beforeMount: function() { },
  mounted: function() {
    this.search();
  },
  beforeDestroy: function() { },
  destroyed: function() { },
  directives: {}
};
</script>
