<template>
  <div class="model_box" ref="model_box">
    <iframe
      frameborder="0"
      marginwidth="0"
      marginheight="0"
      allowfullscreen="true"
      name="bimComponentModelPage"
      id="bimComponentModelPage"
      width="100%"
      style="height: 100%;"
      allowtransparency="yes"
      scrolling="no"
    ></iframe>
    <div style="position:absolute;bottom:60px;left: 50%;
  transform: translateX(-50%);width:390px;height:54px;">
      <viewTool @viewToolHandler="viewToolHandler" v-if="!tool"></viewTool>
    </div>
    <div v-if="tips" class="bf_tips">
      <div class="bf-tips-container">
        <div>
          <p class="span_colorN">
            请使用
            <span class="span_color">W</span>
            <span class="span_color">A</span>
            <span class="span_color">S</span>
            <span class="span_color">D</span>
            和
            <span class="span_color">Q</span>
            <span class="span_color">E</span>
            移动
            <span
              style="cursor: pointer;"
              @click="hide_tips"
            >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;X</span>
          </p>
          <p class="span_colorN">
            请使用
            <span class="span_color">I</span>
            <span class="span_color">J</span>
            <span class="span_color">K</span>
            <span class="span_color">L</span>
            转向
          </p>
          <p class="span_colorN">
            按住
            <span class="span_color">SHIFT</span>
            或空格可加速
          </p>
        </div>
      </div>
    </div>
    <!-- 右键鼠标显示 -->
    <div style="position:absolute;top:0px;left:0px" v-show="showlayer" ref="layerposition">
      <layer @selectElementBox="selectElementBox" ref="layer" :showactive="showactive"></layer>
      <div style="position:absolute;top:130px;right:-40px" v-if="pickershow">
        <el-color-picker
          v-model="colorValue"
          show-alpha
          :predefine="predefineColors"
          @active-change="changeElementColor"
          @change="setElementColor"
        ></el-color-picker>
      </div>
    </div>
  </div>
</template>

<script>
/* global TiViewer */
/* global $store */
import viewTool from './viewTool.vue';
import layer from './layer.vue';
export default {
  name: 'modelView',
  props: ['tool'],
  data() {
    return {
      onContextmenuTarget: {
        x: 0,
        y: 0
      },
      tips: false,
      viewPoints: '',
      showlayer: false,
      pickershow: false,
      colorValue: 'rgba(17, 0, 6, 1)',
      predefineColors: [
        '#ff4500',
        '#ff8c00',
        '#ffd700',
        '#90ee90',
        '#00ced1',
        '#1e90ff',
        '#c71585',
        'rgba(255, 69, 0, 0.68)',
        'rgb(255, 120, 0)',
        'hsv(51, 100, 98)',
        'hsva(120, 40, 94, 0.5)',
        'hsl(181, 100%, 37%)',
        'hsla(209, 100%, 56%, 0.73)',
        '#c7158577'
      ],
      modelView: '',
      projectId: sessionStorage.getItem('projectId') ? sessionStorage.getItem('projectId') : 'ge',
      showactive: '',
      iframeInfo: {
        width: '',
        height: '',
        viewerMid: ''
      },
      snapshotsImg: '',
      elementList: [],
      modelViewUidList: '',
      selectElementId: [],
      elelmentBoxStatus: false,
      modelViewUid: '',
      viewColor: '',
      modelViewSnapshot: ''
    };
  },
  methods: {
    hide_tips() {
      this.tips = false;
    },
    changeElementColor(data) {
      const curColor = data.replace('rgba(', '').replace(')', '').split(',');
      const newColor = [];
      curColor.forEach((item) => {
        if (item > 1) {
          newColor.push((item / 255).toFixed(1));
        } else {
          newColor.push((item));
        }
      });
      this.viewColor = newColor.join('-');
      console.log('color:', this.viewColor);
    },
    setElementColor() {
      const elementArr = this.elementList.join(',');
      this.modelView.setElementColorAlt(elementArr, this.viewColor.toString());
      this.modelView.selectByElementInfo({ op: 'r' });
      this.showlayer = false;
    },
    initModelView(iFrame, modelid) {
      if (!iFrame) {
        this.iframeInfo.viewerMid = modelid;
      }
      const that = this;
      console.log('that.projectId', that.projectId, sessionStorage.getItem('projectId'));
      const iFrameDomObj = iFrame;
      const iFrameDoc = iFrameDomObj.contentWindow.document;
      const sUrl = 'http://139.159.246.200:4110/Home/BimEmbed?&Refresh=' + new Date().getTime();
      let sHtml = '<form action="' + sUrl + '" method="post" target="_self" id="bim_post" >';
      sHtml += '<input id="u" name="u" type="hidden" value="' + 'rel://' + that.projectId + '\\combine.gemsproj' + '" />';
      sHtml += '<input id="w" name="w" type="hidden" value="' + that.iframeInfo.width + '" />';
      sHtml += '<input id="h" name="h" type="hidden" value="' + that.iframeInfo.height + '" />';
      sHtml += '<input id="v" name="v" type="hidden" value="' + that.iframeInfo.viewerMid + '" />';
      sHtml += '<input id="cam" name="cam" type="hidden" value="building" />';
      sHtml += '</form>';

      iFrameDoc.write(sHtml);
      iFrameDoc.getElementById('bim_post').submit();
      that.modelView = new TiViewer(iFrameDomObj);
      that.modelView.register(() => {
        that.modelView.tiCmd({
          cmd: 'setConfig',
          data: {
            HideGrid: false,
            labels: false,
            snapshots: false,
            bOnSaveLabelFileCallback: false,
            bShowToolbar: false
          }
        });
        that.modelView.zoomToTarget();

        that.modelView.setUserName(sessionStorage.getItem('userName'));

        that.modelView.onNotify = function(data) {
          // console.log('nonotify', data);
          that.getSnapshots();
          if (data.func === 'OnContextMenu') {
            if (that.$refs.layerposition && that.$refs.layerposition.style) {
              // that.$refs.layerposition.style.left = data.data.xy.x + 'px';
              // that.$refs.layerposition.style.top = data.data.xy.y + 'px';
              const currentHeiht = document.body.clientHeight;
              const plusHeight = that.$refs.layerposition.offsetHeight ? that.$refs.layerposition.offsetHeight : 248;
              if (currentHeiht - 248 <= data.data.xy.y) {
                that.$refs.layerposition.style.left = data.data.xy.x + 'px';
                that.$refs.layerposition.style.top = data.data.xy.y - plusHeight + 'px';
              } else {
                that.$refs.layerposition.style.left = data.data.xy.x + 'px';
                that.$refs.layerposition.style.top = data.data.xy.y + 'px';
              }
            }
            // console.log('1111111111111111111111111', data.data.ICode);
            if (data.data.ICode !== 'dummy') {
              if (that.elementList.length > 0) {
                // show all
                that.showlayer = true;
                console.log('that.elementList', that.elementList);
                that.showactive = that.elementList.length;
              } else {
                // only show 显示的list
                that.showlayer = true;
                console.log('that.elementList', that.elementList.length);
                that.showactive = that.elementList.length;
              }
            } else {
              // only show 显示的list
              that.showlayer = true;
              console.log('that.elementList', that.elementList.length);
              that.showactive = that.elementList.length;
            }
          }
        };
        that.modelView.onSelect = function(data) {
          // console.log('onselect', data);
          that.getSnapshots();
          that.showlayer = false;
          that.pickershow = false;
          if (data && data.length > 0) {
            that.elementList = data;
            that.elelmentBoxStatus = true;
            let datas = [];
            datas = data[0].split('_');
            const lengths = datas.length - 1;
            that.modelViewUid = datas[0];
            const uuId = datas[lengths];
            that.$store.commit('SET_MODELVIEW_UID', that.modelViewUid);
            that.$axios('artifacts/queryArtifactsInformation', {uuId: uuId}, 'POST')
              .then(res => {
                const uuIds = {};
                uuIds.viewId = res.data.value.viewId;
                uuIds.stagingNo = res.data.value.stagingNo;
                uuIds.projectNo = res.data.value.projectNo;
                sessionStorage.setItem('uuIds', JSON.stringify(uuIds));
                // sessionStorage.setItem('uuIds', uuIds);
                that.$store.commit('SET_VIEW_ID', uuIds.viewId);
              })
              .catch(resultMsg => {
              });
          } else {
            that.elementList = [];
            that.elelmentBoxStatus = false;
            that.modelViewUid = '';
            that.$store.commit('SET_MODELVIEW_UID', that.modelViewUid);
          }
        };
        that.modelView.onSaveSnapshotFile = function(username, guid, title, content, isNew) {
          console.log('saveModelViewSnapshot', username, content);
          that.$store.commit('SET_MODELVIEW_3D_SNAPSHOT', content);
          that.modelViewSnapshot = content;
        };
        this.viewPoints = this.$route.query.v;
        if (this.viewPoints) {
          this.searchViewPoint();
        }

        console.log('out');
      });
    },
    resizeWindow() {
      const that = this;
      console.log(that.modelView.setCameraIsometric);
      try {
        const modelInfo = {};
        if (this.tool) {
          modelInfo.newW = Number(document.documentElement.clientWidth);
        } else {
          modelInfo.newW = Number(document.documentElement.clientWidth - 63);
        }

        modelInfo.newH = Number(document.documentElement.clientHeight);
        // 通过TiViewer.onresize接口来改变窗口大小
        if (that.modelView != null) {
          that.modelView.onresize(modelInfo);
        }
      } catch (e) {
        console.log(e);
      }
    },
    setDisplayMode(modelid) {
      this.modelView.hideAllModel();
      const curModelView = {};
      console.log('==========ssss', modelid, modelid.length);
      if (modelid && modelid !== 'del') {
        const newModelListid = new Set(modelid.split('&')[0].split(','));
        const curModelListid = new Set(modelid.split('&')[1].split(','));
        console.log('====newModelListid=======', [...newModelListid]);
        console.log('====curModelListid=======', [...curModelListid]);
        if ([...newModelListid] && [...newModelListid][0] !== '' && [...newModelListid].length > 0) {
          [...newModelListid].forEach((item) => {
            curModelView[item] = 'solid';
          });
        }

        if ([...curModelListid] && [...curModelListid][0] !== '' && [...curModelListid].length > 0) {
          [...curModelListid].forEach((item) => {
            curModelView[item] = 'hidden';
          });
        }
      } else {
        modelid = ' ';
      }
      console.log('modelid===', curModelView);
      const modelInfo = {
        ModelInfo: curModelView,
        bZoomTo: true
      };
      this.modelView.setDisplayMode(modelInfo);
    },
    getSnapshots() {
      const that = this;
      that.modelView.get2DImageData((url) => {
        that.$store.commit('SET_MODELVIEW_SNAPSHOT', url);
      });
    },
    getModelViewSnapshot(title) {
      const that = this;
      const param = {
        cmd: 'newSnapshot',
        data: { title: title }
      };
      console.log('getModelViewSnapshot', param, that.modelViewSnapshot);
      that.modelView.tiCmd(param);
    },
    searchViewPoint() {
      const projectId = sessionStorage.getItem('projectId')
        ? sessionStorage.getItem('projectId')
        : '';
      this.$axios('/modelView/queryPointList', {projectId: projectId}, 'POST')
        .then(res => {
          this.viewPointList = res.data.value;
          const a = this.viewPointList.filter(item => item.name === this.viewPoints)[0];
          if (a) {
            sessionStorage.setItem('tree-viewId', a.viewId);
            this.$store.commit('SET_VIEWPOINT_CONTENT', a.cameraContent);
          } else {
            this.$message({
              type: 'error',
              message: '不存在这个视点'
            });
          }
        });
    },
    showViewPoint(content) {
      try {
        const viewPointContent = JSON.parse(JSON.parse(content));
        console.log('====', viewPointContent, viewPointContent.username, viewPointContent.guid);
        this.modelView.loadSnapshotFileAndShow(JSON.parse(content), viewPointContent.username, viewPointContent.guid);
      } catch (err) {
        console.log('showViewPoint', err);
      }
    },
    viewToolHandler(val) {
      console.log(val);
      const that = this;
      const view = that.modelView;
      let param = {};
      let gravityParam = {};
      switch (val) {
      case 'select':
      case 'cancle-boxSelect':
        this.tips = false;
        view.toggleLinearMeasure(false);
        view.toggleClipBox(false);
        view.setMouseModeRotate();
        break;
      case 'boxSelect':
        this.tips = false;
        view.toggleLinearMeasure(false);
        view.toggleClipBox(false);
        view.setMouseModeSelect();
        break;
      case 'measure':
        this.tips = false;
        view.toggleLinearMeasure(true);
        view.toggleClipBox(false);
        break;
      case 'nomal-measure':
        this.tips = false;
        view.toggleLinearMeasure(false);
        view.toggleClipBox(false);
        break;
      case 'leveling':
        this.tips = false;
        view.setLinearMeasureConstraint('X');
        view.toggleClipBox(false);
        break;
      case 'vertical':
        this.tips = false;
        view.setLinearMeasureConstraint('Y');
        view.toggleClipBox(false);
        break;
      case 'linearZ':
        this.tips = false;
        view.setLinearMeasureConstraint('Z');
        view.toggleClipBox(false);
        break;
      case 'linearNull':
        this.tips = false;
        view.setLinearMeasureConstraint(null);
        view.toggleClipBox(false);
        break;
      case 'showToggleClipBox':
        this.tips = false;
        view.toggleLinearMeasure(false);
        view.toggleClipBox(true);
        break;
      case 'hideToggleClipBox':
        this.tips = false;
        view.toggleLinearMeasure(false);
        view.toggleClipBox(false);
        break;
      case 'resetClipBox':
        this.tips = false;
        view.toggleLinearMeasure(false);
        view.resetClipBox();
        break;
      case 'move':
        this.tips = true;
        view.toggleClipBox(false);
        param = {
          cmd: 'bindKeyEvents'
        };
        view.tiCmd(param);
        gravityParam = {
          cmd: 'gravityOn'
        };
        view.tiCmd(gravityParam);
        break;
      case 'nomal-move':
        this.tips = false;
        view.toggleClipBox(false);
        param = {
          cmd: 'unbindKeyEvents'
        };
        view.tiCmd(param);
        gravityParam = {
          cmd: 'gravityOff'
        };
        view.tiCmd(gravityParam);
        break;
      case 'forward':
        view.toggleClipBox(false);
        param = {
          cmd: 'setFlightKeyDown',
          data: { key: 'forward' }
        };
        view.tiCmd(param);
        break;
      case 'left':
        view.toggleClipBox(false);
        param = {
          cmd: 'setFlightKeyDown',
          data: { key: 'left' }
        };
        view.tiCmd(param);
        break;
      case 'right':
        view.toggleClipBox(false);
        param = {
          cmd: 'setFlightKeyDown',
          data: { key: 'right' }
        };
        view.tiCmd(param);
        break;
      case 'backward':
        view.toggleClipBox(false);
        param = {
          cmd: 'setFlightKeyDown',
          data: { key: 'backward' }
        };
        view.tiCmd(param);
        break;
      case 'up':
        view.toggleClipBox(false);
        param = {
          cmd: 'setFlightKeyDown',
          data: { key: 'up' }
        };
        view.tiCmd(param);
        break;
      case 'down':
        view.toggleClipBox(false);
        param = {
          cmd: 'setFlightKeyDown',
          data: { key: 'down' }
        };
        view.tiCmd(param);
        break;
      case 'turn-up':
        view.toggleClipBox(false);
        param = {
          cmd: 'setFlightKeyDown',
          data: { key: 'turn-up' }
        };
        view.tiCmd(param);
        break;
      case 'turn-down':
        view.toggleClipBox(false);
        param = {
          cmd: 'setFlightKeyDown',
          data: { key: 'turn-down' }
        };
        view.tiCmd(param);
        break;
      case 'turn-left':
        view.toggleClipBox(false);
        param = {
          cmd: 'setFlightKeyDown',
          data: { key: 'turn-left' }
        };
        view.tiCmd(param);
        break;
      case 'turn-right':
        view.toggleClipBox(false);
        param = {
          cmd: 'setFlightKeyDown',
          data: { key: 'turn-right' }
        };
        view.tiCmd(param);
        break;
      case 'setFlightKeyUp':
        view.toggleClipBox(false);
        param = {
          cmd: 'clearFlightKey'
        };
        view.tiCmd(param);
        break;
      case 'sprint':
        view.toggleClipBox(false);
        param = {
          cmd: 'setFlightKeyDown',
          data: { key: 'sprint' }
        };
        view.tiCmd(param);
        break;
      default:
        view.toggleLinearMeasure(false);
        view.toggleClipBox(false);
        view.setMouseModeRotate();
        break;
      }
    },
    selectElementBox(type) {
      let elementArr = '';
      console.log('=========xxx', type);
      switch (type) {
      case 'isolated':
        elementArr = this.elementList.join(',');
        this.modelView.setElementIsolated(elementArr);
        this.showlayer = false;
        break;
      case 'setElementVisibleAlt':
        this.elementList.filter(item => {
          if (item) {
            this.selectElementId.push(item);
          }
        });
        console.log('==========xxx', this.selectElementId);
        elementArr = this.selectElementId.join(',');

        this.modelView.setElementVisibleAlt(elementArr, 0);
        this.showlayer = false;
        break;
      case 'setElementVisible':
        this.selectElementId = [];
        elementArr = this.elementList.join(',');
        this.modelView.setElementVisibleAlt(elementArr, 1);
        this.showlayer = false;
        break;
      case 'setElementHide':
        this.elementList.filter(item => {
          if (item) {
            this.selectElementId.push(item);
          }
        });
        console.log('==========xxx', this.selectElementId);
        elementArr = this.selectElementId.join(',');
        console.log('=================elementArr', elementArr);
        this.modelView.changeElementVisibleAlt(elementArr, 0);
        this.showlayer = false;
        break;
      case 'setElementColorAlt':
        this.pickershow = true;
        break;
      case 'clearElementColor':
        this.modelView.clearElementColor();
        this.showlayer = false;
        break;
      case 'basicInfo':
        this.showlayer = false;
        break;
      default:
        elementArr = this.elementList.join(',');
        this.modelView.setElementVisibleAlt(elementArr, 1);
        this.showlayer = false;
        break;
      }
    },
    keyHandle(type) {
      this.viewToolHandler(type);
    },
    getViewPointStatus(status) {
      console.log('==========getViewPointStatus', status);
      if (status) {
        this.getModelViewSnapshot('BIM-BROWSER');
      }
    },
    setModelViewUidHide(elementArr) {
      console.log('============hide uid');
      this.modelView.setElementVisibleAlt(elementArr, 0);
    },
    setModelViewUidListHide(data) {
      const uidList = [];
      const modelUidArr = data ? data.split(',') : [];
      const eemidList = this.modelViewUidList ? this.modelViewUidList.split(',') : [];
      const eemidArr = [];
      modelUidArr.forEach(item => {
        uidList.push({
          id: item,
          vis: 1
        });
      });

      eemidList.forEach(item => {
        if (item) {
          eemidArr.push({
            id: item,
            vis: 1
          });
        }
      });

      const curViewList = [
        {
          v: $store.state.tree.curModelId,
          vis: 0,
          e: uidList
        }
      ];
      console.log('=================setModelViewUidListHide', curViewList);
      this.modelView.setElementVisible(curViewList);
    }
  },
  computed: {
    getModelViewProjectId() {
      return {
        // projectId: $store.state.tree.projectId,
        projectId: sessionStorage.getItem('projectId') ? sessionStorage.getItem('projectId') : 'ge',
        viewerMid: $store.state.tree.modelId,
      };
    },
    getModelViewUidList() {
      return {
        modelViewUidList: $store.state.warehouse.modelViewUidList,
      };
    },
    getViewPointContent() {
      return $store.state.viewpoint.viewPointContent;
    },
    getModelViewAllUidList() {
      return $store.state.warehouse.modelAllUidList;
    },
  },
  watch: {
    getModelViewProjectId(data) {
      console.log('========date==view', data);
      this.projectId = data.projectId ? data.projectId : '';
      this.viewerMid = data.viewerMid ? data.viewerMid : '';
      this.modelViewUidList = data.modelViewUidList ? data.modelViewUidList : '';
      this.setDisplayMode(this.viewerMid);
    },
    getModelViewUidList(data) {
      this.modelViewUidList = data.modelViewUidList ? data.modelViewUidList : '';
      console.log('===============test url', this.modelViewUidList);
      // this.setModelViewUidHide(this.modelViewUidList);
      this.setModelViewUidListHide(this.modelViewUidList);
    },
    getViewPointContent(data) {
      console.log('??????', data);
      this.showViewPoint(data);
    },
    getModelViewAllUidList(data) {
      console.log('=============aaaaaa', data);
      this.setModelViewUidListHide(data);
    }
  },
  components: { viewTool, layer },
  created() {
    this.$eventHub.$on('bus-showViewPoint', this.showViewPoint2);
    this.$eventHub.$on('bus-setVeiwpointModel', this.getViewPointStatus);
    // this.$eventHub.$on('bus-viewpointToModelView', this.showViewpointToModelView);
    const that = this;
    document.onkeydown = function(e) {
      const key = window.event.keyCode;
      switch (key) {
      case 65:
      case 37:
        that.keyHandle('left');
        break;
      case 68:
      case 39:
        that.keyHandle('right');
        break;
      case 69:
      case 34:
        that.keyHandle('down');
        break;
      case 83:
      case 40:
        that.keyHandle('backward');
        break;
      case 81:
      case 33:
        that.keyHandle('up');
        break;
      case 87:
      case 38:
        that.keyHandle('forward');
        break;
      case 73:
        that.keyHandle('turn-up');
        break;
      case 74:
        that.keyHandle('turn-left');
        break;
      case 75:
        that.keyHandle('turn-down');
        break;
      case 76:
        that.keyHandle('turn-right');
        break;
      case 16:
        that.keyHandle('sprint');
        break;
      default:
        console.log('=============down key', key);
        break;
      }
    };
    document.onkeyup = function(e) {
      that.keyHandle('setFlightKeyUp');
    };
  },
  beforeMount: function() { },
  mounted() {
    console.log('===this.$route.query.id', this.$route.query.id, sessionStorage.getItem('projectId'));
    const modelid = sessionStorage.getItem('modelid');
    const sProjectId = sessionStorage.getItem('projectId') ? sessionStorage.getItem('projectId') : 'ge';
    const cprojectId = this.$cookies.get('project') ? this.$cookies.get('project').projectId : sProjectId;
    this.projectId = this.$route.query.pid ? this.$route.query.pid : cprojectId;
    const that = this;
    const modelLayout = document.getElementById('bimComponentModelPage');
    this.iframeInfo.width = modelLayout.clientWidth;
    this.iframeInfo.height = modelLayout.offsetHeight;
    this.iframeInfo.viewerMid = modelid;
    console.log(' this.iframeInfo==', this.iframeInfo, this.projectId);
    this.initModelView(modelLayout, modelid);
    that.$store.commit('SET_MODELVIEW_X', that.iframeInfo.width);
    that.$store.commit('SET_MODELVIEW_Y', that.iframeInfo.height);
    window.onresize = function() {
      that.$store.commit('SET_MODELVIEW_X', document.getElementById('bimComponentModelPage').offsetWidth);
      that.$store.commit('SET_MODELVIEW_Y', document.getElementById('bimComponentModelPage').offsetHeight);
      that.resizeWindow();
    };
  },
  beforeDestroy: function() { },
  destroyed: function() { },
  directives: {}
};
</script>
<style scoped lang="scss">
  .model_box{
    width: 100%;
    height: 100%;

    .span_color {
      text-align: left;
      color: #f5a623;
    }
    .span_colorN {
      text-align: left;
    }

    .bf_tips {
      height: 72px;
      position: absolute;
      width: 220px;
      padding: 10px;
      top: 10px;
      left: 50%;
      transform: translate(-50%, 0);
      border-radius: 3px;
      background-color: #eff7ff;
      border: solid 1px #a0cbfc;

      .bf-tips-container {
        height: 26px;
        line-height: 26px;
        text-align: center;
        font-size: 14px;
        color: #666666;
      }
    }
  }
</style>
