<template>
  <div class="vdr_mark">
    <vue-draggable-resizable
      class="vdrmark"
      :w="240"
      :h="900"
      style="z-index: 1;"
      :minw="240"
      :minh="250"
      :active="true"
      :drag-cancel="'.cancel'"
      :handles="['br']"
      @deactivated="onDeactivated"
      :parent="true"
      :resizable="false"
      :x="modelView_x"
      :y="50"
    >
      <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">
          <span v-if="chooseList && chooseList.length > 0 && isAdd" @click="addPro"
            style="position: absolute;padding-left:20px;color:#0057ff;cursor: pointer;">
              加入问题（{{chooseList.length}}）</span>
          <img v-if="!NoSearch" class="cancel_img" style="top:55px;" @click="adds" src="@/assets/bianji.png">
        </div>
        <div
          class="filtertree"
          style="height:800px;padding-top: 40px;"
          v-loading="loading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
        >
          <el-scrollbar style="height:100%;width: 100%;">
            <div
              style="text-align: center;margin-top: 30px;"
              v-if="list.length === 0 && seasrchs"
            >没有查询到数据!</div>
            <div
            class="van-user-divdad"
              style="width:198px;height:158px;padding-left:20px;"
              v-for="item of list"
              :key="item.id"
            >
              <div class="van-user-item-div" @dblclick="openView(item)" @click="trueImgUrl(item)"
               style="width:198px;height:128px;cursor: pointer;">
                <img class="van-user-item-box" :src="item.cameraMark">
                 <div class="van-user-item-divson">
                <i class="van-user-delete" @click.stop="deleteItem(item)"></i>
                <div class="van-user-check" v-if="isAdd">
                    <span aria-checked="mixed"  @click.stop="checkedItem(item)" class="el-checkbox__input"
                    :class="{'is-checked':item.isChecked}">
                      <span class="el-checkbox__inner"></span>
                      <input type="checkbox" aria-hidden="true" class="el-checkbox__original" value="">
                    </span>
                </div>
                </div>
              </div>
              <div class="formark_right">
                <div style="width:198px;height:28px;">
                  <p v-if="!item.edit" class="div_top_p" @click="editInput(item)">{{item.name + checked}}</p>
                  <el-input v-else class="cancel" style="width:198px;height: 28px;font-size:18px;position: relative;
                  top: -20px;" @blur="editP(item)" @keyup.enter.native="editP(item)" maxlength="20" v-model="item.name"
                   clearable>
                  </el-input>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </vue-draggable-resizable>
    <el-dialog
      :visible.sync="dialogVisible"
      width="100%"
      height="100%"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <div class="dialog_div" v-if="imgUrl">
        <img :src="TrueImgUrl" style="width:100%;height:100%;">
      </div>
      <div v-else class="dialog_div">
        <div class="dialog_left" style="width:100%;">
          <img :src="form.cameraMark" style="width:100%;height:100%;">
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Kscreenshot from 'kscreenshot';
export default {
  data() {
    return {
      formId: '',
      proList: [],
      proAllList: [],
      isAdd: false,
      chooseList: [],
      checked: '',
      seasrchs: false,
      loading: false,
      TrueImgUrl: '',
      imgUrl: false,
      list: [],
      // 横轴坐标（左上角0点）
      modelView_x: 1200,
      // 竖轴坐标（左上角0点）
      modelView_y: 0,
      dialogVisible: false,
      form: {},
      NoSearch: false,
      time: null
    };
  },
  computed: {
    getModelInfoX() {
      return this.$store.state.modelview.viewX;
    },
  },
  watch: {
    getModelInfoX(val) {
      this.modelView_x = Number(val) - 300;
    },
  },
  created: function() {
    this.modelView_x = Number(this.$store.state.modelview.viewX) - 300;
  },
  mounted: function() {
    window.addEventListener('message', (e) => {
      if (e.data.type === 1) {
        // 新建
        console.log('===================121212122222222222222', e.data.type, e.data.list);
        this.proList = e.data.list;
        this.isAdd = true;
        sessionStorage.setItem('isAdd', '1');
        sessionStorage.setItem('proType', '1');
        sessionStorage.setItem('proList', JSON.stringify(e.data.list));
        setTimeout(() => {
          this.search();
        }, 300);
      } else if (e.data.type === 2) {
        this.isAdd = false;
        this.formId = e.data.formId;
        console.log('=============message', e.data.type, this.formId);
        sessionStorage.setItem('isAdd', '0');
        sessionStorage.setItem('proType', '2');
        sessionStorage.setItem('formId', this.formId);
        setTimeout(() => {
          this.search();
        }, 300);
      } else if (e.data.type === 0) {
        console.log('===================121212122222222222222', e.data.type, e.data.list);
        this.list = e.data.list;
        this.isAdd = false;
        sessionStorage.setItem('isAdd', '0');
        sessionStorage.setItem('proType', '0');
        sessionStorage.setItem('list', JSON.stringify(this.list));
      }
    }, false);
    this.NoSearch = window.location.search.indexOf('type=hide') !== -1;
    // 当type=hide时 从不刷新页面
    if (this.NoSearch) {
      this.isAdd = false;
      this.list = sessionStorage.getItem('list') ? JSON.parse(sessionStorage.getItem('list')) : [];
    } else if (!this.NoSearch) {
      this.isAdd = sessionStorage.getItem('isAdd') ? sessionStorage.getItem('isAdd') !== '0' : false;
      const proType = sessionStorage.getItem('proType');
      if (proType === '1') {
        console.log('===================gogoggo');
        this.proList = sessionStorage.getItem('proList') ? JSON.parse(sessionStorage.getItem('proList')) : [];
      } else if (proType === '2') {
        this.formId = sessionStorage.getItem('formId') ? sessionStorage.getItem('formId') : '';
      }
      console.log('================dsfdsf');
      setTimeout(() => {
        this.search();
      }, 300);
    }
    const that = this;
    this.opens = new Kscreenshot({key: 6000000,
      endCB: function(img) {
        const imgs = img;
        that.form.cameraMark = imgs;
        const f = that.form;
        if (!f.viewId || !f.cameraMark || !f.projectCode || !f.cameraModel || !f.mbpId) {
          that.$message({
            message: '请先选择或者点击视图模型',
            type: 'warning'
          });
          console.log('---------------------==========================', that.form);
        } else {
          that.$axios('/modelView/addSnapshot', that.form, 'POST')
            .then(res => {
              console.log(111111111111111111111, res);
              if (res && res.data.code === 200) {
                that.$message({
                  type: 'success',
                  message: res.data.message
                });
                this.endScreenShot();
                setTimeout(() => {
                  that.dialogVisible = false;
                  // this.$eventHub.$emit('bus-img', true);
                  that.search();
                }, 500);
                // this.chooseList = [];
              } else {
                that.$message({
                  type: 'warning',
                  message: '模型快照更新失败!'
                });
                this.endScreenShot();
                setTimeout(() => {
                  that.dialogVisible = false;
                  that.search();
                }, 300);
                // setTimeout(() => {
                //   opens.startScreenShot();
                // }, 0);
              }
            })
            .catch(res => {
              that.$message({
                type: 'warning',
                message: '模型快照更新失败!!'
              });
              this.endScreenShot();
              setTimeout(() => {
                that.dialogVisible = false;
              }, 300);
              // setTimeout(() => {
              //   opens.startScreenShot();
              // }, 0);
            });
        }
      },
      // needDownload: true,
      endScreenShot: function() {}});
  },
  methods: {
    onDeactivated() { },
    addPro() {
      // 加入问题发送数据
      console.log(11111111111111111111111);
      const Obj = {};
      Obj.type = 1;
      this.proAllList.push.apply(this.proAllList, this.chooseList);
      Obj.list = this.proAllList;
      window.parent.postMessage((Obj), '*');
    },
    openView(item) {
      // console.log('2222222222222222222222222222222');
      clearTimeout(this.time);
      if (item && item.cameraModel) {
        sessionStorage.setItem('tree-viewId', item.viewId);
        this.$store.commit('SET_VIEWPOINT_CONTENT', item.cameraModel);
      } else {
        this.$store.commit('SET_VIEWPOINT_CONTENT', '');
      }
    },
    // cancel() {
    //   // 弹窗取消
    //   if (this.editY) {
    //     this.dialogVisible = false;
    //     this.search();
    //   } else {
    //     this.$confirm('是否要丢弃此次标记？', {
    //       confirmButtonText: '确定',
    //       cancelButtonText: '取消',
    //       center: true
    //     })
    //       .then(() => {
    //         this.$message({
    //           type: 'success',
    //           message: '丢弃成功!'
    //         });
    //         this.dialogVisible = false;
    //         this.search();
    //       })
    //       .catch(() => {
    //         this.$message({
    //           type: 'info',
    //           message: '已取消丢弃'
    //         });
    //       });
    //   }
    // },
    /**
     * 删除当前项
     */
    deleteItem(item) {
      this.$axios('/modelView/deleteSnapshot', { id: item.id }, 'POST')
        .then(res => {
          if (res && res.data && res.data.message) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.search();
          }
        })
        .catch(res => {
          this.$message({
            type: 'warning',
            message: res.data.message
          });
        });
    },
    /**
     * 点击复选框
     */
    checkedItem(item) {
      item.isChecked = !item.isChecked;
      if (item.isChecked) {
        this.chooseList.push(item);
      } else {
        for (let i = 0; i < this.chooseList.length; i++) {
          const el = this.chooseList[i];
          if (el.id === item.id) {
            this.chooseList.splice(i, 1);
          }
        }
      }
    },
    editP(item) {
      // 输入框失焦事件 回车事件
      this.checked = ' ';
      item.edit = false;
      setTimeout(() => {
        // 表格数据实时变化
        this.checked = '';
      }, 500);
      this.$axios('/modelView/editSnapshot', { id: item.id, name: item.name }, 'POST')
        .then(res => {
          if (res && res.data && res.data.message) {
            this.$message({
              type: 'success',
              message: '模型快照更新成功!'
            });
            this.search();
          }
        })
        .catch(res => {
          this.$message({
            type: 'warning',
            message: res.data.message
          });
        });
    },
    editInput(item) {
      // 文字切换输入框事件
      this.checked = ' ';
      item.edit = true;
      setTimeout(() => {
        // 表格数据实时变化
        this.checked = '';
      }, 500);
    },
    clears() {
      // 搜索清空
      this.search();
    },
    handleClose() {
      // 关闭弹窗
      this.dialogVisible = false;
      if (this.imgUrl) {
        this.imgUrl = false;
      } else {
        this.search();
      }
    },
    trueImgUrl(item) {
      // 弹窗左边图片展示
      const that = this;
      clearTimeout(that.time);
      that.time = setTimeout(() => {
        that.TrueImgUrl = '';
        that.TrueImgUrl = item.cameraMark;
        that.dialogVisible = true;
        that.imgUrl = true;
      }, 300);
    },
    search() {
      // 列表查询接口
      this.loading = true;
      const projectCode = sessionStorage.getItem('projectNo')
        ? sessionStorage.getItem('projectNo') : '';
      const proType = sessionStorage.getItem('proType')
        ? sessionStorage.getItem('proType') : '';
      const URL = !this.formId ? '/modelView/querySnapshotList'
        : 'problem-server/modelSnapshot/findModelSnapshotListByForm';
      const params = !this.formId ? { projectCode: projectCode } : { formId: this.formId };
      this.$axios(URL, params, 'POST')
        .then(res => {
          this.loading = false;
          this.list = [];
          this.list = res.data.value;
          this.seasrchs = true;
          if (proType === '1') {
            this.chooseList = [];
            this.proAllList = [];
            console.log(1111111111111111111111111111111111, this.proList, this.list);
            this.proList.forEach(item => {
              this.list.forEach(dom => {
                if (item.id === dom.id) {
                  dom.isChecked = true;
                  this.chooseList.push(dom);
                }
              });
              const bSign = this.list.every(dom => {
                return item.id !== dom.id;
              });
              if (bSign) {
                this.proAllList.push(item);
              }
            });
          }
        })
        .catch(resultMsg => {
          this.seasrchs = true;
          this.loading = false;
        });
    },
    hide() {
      // 视点关闭
      this.$emit('WebMarkSwitch', false);
      this.$eventHub.$emit('bus-WebMarkSwitch', false);
    },
    adds() {
      // 新增
      this.form.viewId = this.$store.state.tree.viewId || '';
      this.form.projectCode = sessionStorage.getItem('projectNo') || '';
      this.form.mbpId = sessionStorage.getItem('id') || '';
      this.form.cameraMark = this.$store.state.modelview.snapshot || '';
      setTimeout(() => {
        this.dialogVisible = true;
        this.$eventHub.$emit('bus-setVeiwpointModel', this.dialogVisible);
      }, 50);
      setTimeout(() => {
        this.form.cameraModel = this.$store.state.modelview.modelViewSnapshot;
        this.opens.startScreenShot();
      }, 500);
    }
  },
  beforeMount: function() { },
  beforeDestroy: function() { },
  destroyed: function() { },
  directives: {}
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    .el-loading-mask {top: -10px;}
    .el-radio__input.is-checked {
        .el-radio__inner {
          background-color: #0057ff;
          border-color: #0057ff;
        }
        &+.el-radio__label {
          color: #fff;
        }
    }
    .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner{
      background: #0057ff;
      border-color: #0057ff;
    }
    .el-checkbox__input.is-checked+.el-checkbox__label,.el-table th>.cell.highlight,
    .el-table-filter__bottom button:hover{
      color: #0057ff;
    }
    .el-checkbox__input.is-focus .el-checkbox__inner {
        border-color: #dcdfe6;
    }
    .van-user-divdad {
        .el-checkbox__inner {
        width: 17px;
        height: 17px;
        opacity: .6;
        background-color: #2f343b;
        }
        .el-checkbox__inner::after {
        left: 5px;
        height: 8px;
        width: 4px;
        }
        .el-checkbox__input.is-checked .el-checkbox__inner,
        .el-checkbox__input.is-indeterminate .el-checkbox__inner {
        background: #0057ff;
        border-color: #0057ff;
        opacity: 1;
        }
        .van-user-check {
            content: '';
            float: right;
        }
        .div_top_p {
          width:198px;
          height: 28px;
          font-size:18px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          position: relative;
          top: -15px;
        }
        .van-user-item-div {
            width:198px;
            height:128px;
            cursor: pointer;

            &:hover {
                .van-user-delete {
                    display: block;
                }
            }
            .van-user-item-divson {
                position: relative;
                float: left;
                top: -115px;
                left: 15px;
                height: 20px;
                width: 168px;
            }
        }
        .van-user-delete {
            display: none;
            content: '';
            float: left;
            width: 20px;
            height: 20px;
            background: url("../../assets/shanchusuoluetu.png") no-repeat;
            cursor: pointer;
        }
        .van-user-item-box {
            width:100%;
            height:100%;
            cursor: pointer;
        }
    }
</style>
