<template>
  <!-- 查看平面图页面 -->
  <div id='repetitionGraphy'>
    <div class='buttons'>
      <el-button icon='el-icon-back' size='mini' @click='backRouter'></el-button>
      <template v-if="!hasModel">
        <el-upload class='upload-demo' action='string' :http-request='uploadAndSubmit' :show-file-list='false' v-if="step==-1" accept=".jpg,.png"
          :before-upload="beforeUpload">
          <el-button size="mini">{{hasGraph?'替换平面图图片':'上传平面图图片'}}</el-button>
        </el-upload>
        <el-button style='float:right;' size='mini' type='primary' v-if="step==0" @click="nextStep" :disabled="nextStepBtnDisable">下一步</el-button>
        <el-button style='float:right;' size='mini' type='primary' v-if="step==1" @click="nextStep">保存</el-button>
        <el-button style='float:right;' size='mini' v-if="step==1" @click="lastStep">上一步</el-button>
      </template>
      <template v-else>
        <el-button v-if='!isEdit' size='mini' @click='changeGraphy'>{{hasGraph?'替换模型文件':'关联模型文件'}}</el-button>
        <el-button v-if='(sign||otherSign)&&!isEdit' size='mini' @click='editGraphy'>编辑平面图</el-button>
        <el-button v-if='isEdit' size='mini' @click='cancel'>取消</el-button>
        <el-button v-if='isEdit' size='mini' @click='confirm' type='primary'>确认</el-button>
        <span :title="repeatTextTips" class="repeatTips" v-if="repeatFloor.length">{{repeatTextTips}}</span>
      </template>
      <span style='float:right;' v-if='file.FolderName'>当前对应的模型文件：{{file.FolderName}} - {{file.FloorName}}</span>
    </div>
    <!-- 展示图片 -->
    <div class='drawImg'>
      <div style="width: 100%;height: 100%;position: relative;" v-if="hasGraph">
        <drawFloor ref='drawFloor' :isEdit='isEdit' :showTools='true' :id='1' @changeSign='changeSign' @getGraphSuc="getGraphSuc" @handled="repeatHandled"></drawFloor>
        <div class="stepContainer" v-if="step>-1">
          <el-steps :active="step" align-center finish-status="success" process-status="process">
            <el-step title="设定比例尺" :description="stepDes[0]"></el-step>
            <el-step title="楼层对齐" :description="stepDes[1]"></el-step>
          </el-steps>
        </div>
        <ul class="floorList" v-if="step==1">
          <template v-if="floorList.length > 1">
            <li style="border-bottom:1px solid #ccc;text-align: center;padding: 0">选择对齐楼层</li>
            <li v-for="t in floorList" :key="t.id">
              <el-radio v-model="floorRadio" :label="t" @change="changeFloor" :disabled="t.id == FloorID">{{t.localId || t.localName}}</el-radio>
            </li>
          </template>
          <template v-else>
            <li style="text-align: center;padding: 0">
              暂无对齐楼层
            </li>
          </template>
        </ul>
      </div>
      <div style="width: 100%;height: 100%" v-else>
        <div class="center" style="padding-top: 300px">
          <i class="icon-wushuju iconfont"></i>暂无平面图
        </div>
      </div>
    </div>
    <!-- 查看图片弹窗 -->
    <checkGraphy ref='checkGraphy' @refresh='refresh' :alreadyRelatedModel='alreadyRelatedModel'></checkGraphy>
    <!-- 设定比例尺弹窗 -->
    <setScaleDialog ref="setScaleDialog" @textChange="scaleTextChange"></setScaleDialog>
    <!-- 退出时弹窗提示 -->
    <backTips ref='backTips' @back="runBack"></backTips>
  </div>
</template>
<script>
import drawFloor from './drawGraphy/drawFloor'
import checkGraphy from './drawGraphy/checkGraphy' //查看图片
import setScaleDialog from '@/components/old-adm/ready/components/setScaleDialog'
import backTips from '@/components/old-adm/ready/components/backTips'

import ScanController from '@/controller/old-adm/ScanController'
import FileController from '@/controller/old-adm/fileController'
import {SItemStatus, SImageShowType } from "@saga-web/cad-engine"
import { SImageItem } from '@saga-web/graph/lib'
import { SMathUtil } from "@saga-web/cad-engine/lib/utils/SMathUtil"
export default {
  components: {
    drawFloor,
    checkGraphy,
    setScaleDialog,
    backTips
  },
  data() {
    return {
      modelId: '', //
      isEdit: false, // 是否编辑模式
      FloorID: '',
      file: {},
      alreadyRelatedModel: [],
      sign: false,
      otherSign: false,
      hasGraph: false, // 当前楼层是否有平面图
      hasModel: false, // 项目中时候有模型文件
      step: -1, // 当前处于第几步 同时为比例尺item判断是否创建的可编辑的依据;能否返回上页的依据
      key: '', // 当楼层图为图片时图的key
      stepDes: [
        '请在图上点击两点绘制线段并标记实际长度',
        '请移动图片与其他楼层对齐'
      ], // 描述文字
      floorList: [], // 当前建筑下所有楼层
      floorRadio: '', // 当前选中的楼层对象
      imgService: `${window.__systemConf.baseServiceUrl}/image-service/common/image_get?systemId=dataPlatform&key=`,
      curImgItem: null, // 对齐的楼层图片
      scaleItem: null, // 比例尺item
      baseImgItem: null, // 当前楼层图的图片
      nextStepBtnDisable: true, // 比例尺item创建标识
      timeOut: true, // 保存按钮延时3秒可操作
      repeatFloor: [], // 重复的楼层
      handled: false,
    }
  },
  created() {
    this.modelId = this.$route.query.modelId
    this.FloorID = this.$route.query.FloorID
    this.BuildID = this.$route.query.BuildID
    this.BuildName = this.$route.query.BuildName
    this.FloorName = this.$route.query.FloorName
    if (this.modelId != '') {
      this.hasGraph = true;
      const temp = this.modelId.split('.');
      if (temp[1] && (temp[1].toLowerCase() == 'png' || temp[1].toLowerCase() == 'jpg')) {
        // return
      } else {
        this.init()
      }
    } else {
      this.init()
    }
    this.getCountModel()
    this.$nextTick(() => {
      this.$refs.drawFloor.buildFloorName = `${this.BuildName}-${this.FloorName}`
    })
  },
  computed: {
    repeatTextTips() {
      let str = `当前楼层与${this.repeatFloor.join('、')}关联同一个平面图`
      if (!this.handled) {
        str += `，请通过「编辑平面图」划分当前楼层对应的平面图范围`
      }
      return str
    }
  },
  mounted() { },
  methods: {
    init() {
      this.getFloorData()
    },
    // 返回路由
    backRouter() {
      // 底图为图片  上传完图片后未保存
      if (this.step > -1) {
        this.$refs.backTips.showDialog();
      } else {
        this.runBack()
      }
    },
    runBack() {
      this.$router.push({ name: 'buildFloor', query: {buildingId: this.BuildID} })
    },
    // 替换模型文件
    changeGraphy() {
      this.$refs.checkGraphy.showDialog({ FloorID: this.FloorID, BuildID: this.BuildID, CurrentModelId: this.currentModelId })
    },
    // 确认保存
    confirm() {
      let sceneMark = this.$refs.drawFloor.drawMainScene.sceneMark,
        Outline = null
      if (sceneMark) {
        if (sceneMark.outLine.length < 3) {
          this.$message.warning('请添加轮廓线')
          return
        }
        if (!sceneMark.closeFlag) {
          this.$message.warning('请按回车闭合轮廓线')
          this.$refs.drawFloor.focus()
          return
        }
        Outline = this.$refs.drawFloor.drawMainScene.sceneMark.outLine
        Outline = Outline.map((t) => {
          return {
            X: t.x.toFixed(2),
            Y: -t.y.toFixed(2),
          }
        })
      }
      let pa = {
        content: [{ id: this.FloorID, outline: Outline }]
      }
      if (!Outline) {
        pa.nullItems = ['outline']
      }
      ScanController.floorUpdateOutline(pa).then((res) => {
        this.isEdit = false
        this.$message.success('更新成功');
        this.handled = !!Outline;
      })
    },
    // 取消
    cancel() {
      this.isEdit = false
      this.$refs.drawFloor.init()
    },
    // 编辑平面图
    editGraphy() {
      this.isEdit = true
    },
    // 替换模型文件成功
    refresh(modelId,pa) {
      this.modelId = modelId
      this.hasGraph = true;
      const temp = this.modelId.split('.');
      if (temp[1]) {
        if (temp[1].toLowerCase() != 'png' && temp[1].toLowerCase() != 'jpg') {
          // do nothing
        } else {
          // do nothing
        }
      } else {
        this.key = '';
        if (pa && pa.id) {
          this.getFileName(pa.id)
          this.currentModelId = pa.id;
        }
        this.initFromModelId(this.modelId)
      }
    },
    // 获取文件夹名称
    getFileName(modelId) {
      if (!modelId) return
      let pa = {
        Id: modelId,
      }
      FileController.getFileNameById(pa).then((res) => {
        this.file = res
      })
    },
    // 获取楼层
    // 标识 无值:初始化进入 有值'next': 下一步进入
    getFloorData(flag) {
      let floorParam = {
        pageSize: 1000,
        filters: `buildingId='${this.BuildID}'`,
        orders: 'floorSequenceID desc'
      }
      ScanController.floorQueryAndSign(floorParam).then((res) => {
        this.floorList = res.content.filter(t => t.infos && t.infos.floorMap || t.id == this.FloorID);
        // todo
        if (flag && flag == 'next') {
          this.floorRadio = this.floorList[0];
          if (this.floorRadio.id != this.FloorID) {
            this.loadOtherImg(this.floorRadio)
          }
        }
        this.alreadyRelatedModel = res.content.map((t) => {
          if (t.id != this.FloorID) return t.modelId
          this.sign = t.Sign > 0
          this.currentModelId = t.modelId;
          t.modelId && this.getFileName(t.modelId)
        }).filter((t) => t)
      })
    },
    changeSign(flag, arr) {
      this.otherSign = flag;
      this.repeatFloor = arr.map(t => `${t.building.localName || t.building.name}-${t.localName || t.name}`)
    },
    // 统计项目下是否有模型文件
    getCountModel() {
      FileController.countModel({ Filters: "Status in [4]" }).then(res => {
        this.hasModel = res.Count > 0
      })
    },
    //上传图片
    uploadAndSubmit(item) {
      let file = item.file
      let reader = new FileReader()
      let vm = this
      let fileType = file.name.split('.')
      let type = fileType[fileType.length - 1]
      let uploadKey = file.uid
      reader.onloadend = function () {
        // 这个事件在读取结束后，无论成功或者失败都会触发
        if (reader.error) {
        } else {
          // document.getElementById("bytesRead").textContent = file.size;
          // 构造 XMLHttpRequest 对象，发送文件 Binary 数据
          var xhr = new XMLHttpRequest()
          xhr.open(
                    /* method */ 'POST',
            /* target url */
            '/image-service/common/image_upload?systemId=dataPlatform&secret=9e0891a7a8c8e885&overwrite=true&key=' + uploadKey + '.' + type
            /*, async, default to true */
          )
          //xhr.overrideMimeType("application/octet-stream");
          xhr.send(reader.result)
          xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
              if (xhr.status == 200) {
                vm.key = uploadKey + '.' + type
                // 将图片展示
                vm.refresh(uploadKey + '.' + type)
                // 设置步骤为第一步
                vm.step = 0;
                // watch中不会走到initGraph,所以手动触发
                vm.$nextTick(() => {
                  vm.initFromModelId(uploadKey + '.' + type)
                })
                // 设定保存按钮不可操作
                this.timeOut = true;
              }
            }
          }
        }
      }
      reader.readAsArrayBuffer(file)
    },
    // 上传前判断
    beforeUpload(file) {
      // 拿到当前上传图片的name，判断其后缀名是否符合
      let type = this.isImage(file.name);
      if (!type) {
        this.$message.error('仅支持png、jpg格式的图片');
        return false
      }
      return true
    },
    // 封装一个判断图片文件后缀名的方法
    isImage(fileName) {
      if (typeof fileName !== 'string') return;
      let name = fileName.toLowerCase();
      return name.endsWith('.png') || name.endsWith('.jpg');
    },
    // 更新楼层key 为图片,同时更新比例尺
    updateFloorKey() {
      const scaleItem = this.$refs.drawFloor.scaleItem;
      // 比例尺坐标处理,当底图被对齐操作后,需要跟随底图改变坐标
      const line = scaleItem.line.map(t => {
        return { x: t.x + this.baseImgItem.x, y: t.y + this.baseImgItem.y }
      })
      // 计算放缩比例
      const proDis = SMathUtil.pointDistance(line[0].x, line[0].y, line[1].x, line[1].y)
      const proText = scaleItem.text.substring(0, scaleItem.text.length - 3);
      const proScale = proDis / proText;
      let Param = {
        content: [{
          id: this.FloorID,
          infos: {
            floorMap: this.key,
            floorMapRatio: proScale,
            floorMapShift: JSON.stringify({ x: this.baseImgItem.x, y: this.baseImgItem.y })
          },
          properties: {
            line: line,
            text: scaleItem.text
          }
        }],
      }
      ScanController.manageUpdateFloor(Param).then((res) => {
        this.$message.success('更新成功')
        this.step = -1;
        this.baseImgItem.globalAlpha = 1
        this.baseImgItem.moveable = false;
        scaleItem.show()
        this.removeLast()
        this.$refs.drawFloor.fit()
      })
    },
    // 根据modelid初始化
    initFromModelId(id) {
      const temp = id.split('.')[1];
      if (temp) {
        if (temp.toLowerCase() == 'png' || temp.toLowerCase() == 'jpg') {
          this.$refs.drawFloor.initGraphy(id, 3)
        } else {
          this.$refs.drawFloor.initGraphy(id, 2)
        }
      } else {
        this.$refs.drawFloor.initGraphy(id, 1)
      }
    },
    // 上一步
    lastStep() {
      this.step = 0;
      this.$refs.drawFloor.scaleItem.show()
      this.baseImgItem.globalAlpha = 1
      this.baseImgItem.moveable = false;
      this.removeLast()
    },
    // 下一步||保存
    nextStep() {
      this.baseImgItem = this.$refs.drawFloor.drawMainScene.imgList[0]
      this.baseImgItem.globalAlpha = 0.5
      this.baseImgItem.moveable = true;
      // 下一步
      if (this.step == 0) {
        this.step = 1;
        this.$refs.drawFloor.scaleItem.hide();
        // 获取楼层列表
        this.getFloorData('next')
        // 延时3秒可操作性保存按钮
        setTimeout(() => {
          this.timeOut = false
        }, 3000)
      } else if (this.step == 1) {
        // 保存
        this.updateFloorKey();
      }
    },
    // 加载图成功 仅在底图为图片时返回成功
    getGraphSuc() {
      const scaleItem = this.$refs.drawFloor.scaleItem
      if (this.step == 0) {
        scaleItem.status = SItemStatus.Create;
        this.$refs.drawFloor.drawMainScene.grabItem = scaleItem;
        scaleItem.connect('changText', this, this.changeText)
        scaleItem.moveable = true;
        this.clearScaleData(scaleItem);
      } else if (this.step == -1) {
        scaleItem.status = SItemStatus.Normal;
      }
    },
    // 修改比例尺文字
    changeText(t, e) {
      this.$refs.setScaleDialog.showDialog(t)
    },
    // 文本修改
    scaleTextChange(v) {
      if (v > 0) {
        this.nextStepBtnDisable = false
      }
    },
    // 第二部楼层修改
    changeFloor(v) {
      // v->当前改为的楼层对象
      this.removeLast();
      this.loadOtherImg(v)
    },
    // 加载其他楼层图片
    loadOtherImg(v) {
      if (v.infos && v.infos.floorMap) {
        const temp = this.modelId.split('.');
        if (temp[1] && (temp[1].toLowerCase() == 'png' || temp[1].toLowerCase() == 'jpg')) {
          const url = this.imgService + v.infos.floorMap
          this.curImgItem = new SImageItem(null, url);
          this.curImgItem.enabled = false;
          this.curImgItem.showType = SImageShowType.AutoFit;
          if (v.properties) {
            try {
              const point = JSON.parse(v.infos.floorMapShift)
              // 计算两个比例尺差距
              const scaleItem = this.$refs.drawFloor.scaleItem
              this.curImgItem.zOrder = scaleItem.zOrder - 1;
              const r = this.calScaleGap(v.properties, scaleItem);
              if (r != 1) {
                this.$message.warning('比例尺相差较大,可以返回上一步修改比例尺')
              }
              this.curImgItem.showType == SImageShowType.Full;
              this.curImgItem.moveTo(point.x, point.y);
            } catch (err) {
              console.log(err);
            }
          }
          this.$refs.drawFloor.drawMainScene.addItem(this.curImgItem);
          this.$refs.drawFloor.fit()
        }
      }
    },
    // 清除上一张底图
    removeLast() {
      if (this.curImgItem) {
        this.$refs.drawFloor.drawMainScene.removeItem(this.curImgItem);
        this.curImgItem = null;
        this.$refs.drawFloor.view.update()
      }
    },
    // 清空比例尺数据
    clearScaleData(scaleItem) {
      scaleItem.line = [];
      scaleItem.pointChange();
      scaleItem.text = '0 mm';
    },
    // 计算两个比例尺差距
    calScaleGap(pro, item) {
      // pro -> 楼层的properties
      // item -> 当前的比例尺item
      let result = 1
      if (pro.line.length && pro.text) {
        try {
          const proDis = SMathUtil.pointDistance(pro.line[0].x, pro.line[0].y, pro.line[1].x, pro.line[1].y)
          const proText = pro.Text.substring(0, pro.text.length - 3);
          const proScale = proDis / proText;
          const itemDis = SMathUtil.pointDistance(item.line[0].x, item.line[0].y, item.line[1].x, item.line[1].y)
          const itemText = item.text.substring(0, item.text.length - 3);
          const itemScale = itemDis / itemText;
          result = (proScale / itemScale).toFixed()
        } catch (err) {
          console.log(err);
        }
      }
      return result;
    },
    // 是否处理过平面图重复
    repeatHandled(flag) {
      this.handled = flag;
    }
  },
  watch: {
    // modelId(n, o) {
    //   if (o && n != o) {
    //     if (n) {
    //       // 替换的时候需要走
    //       this.$nextTick(() => {
    //         this.initFromModelId(n)
    //       })
    //     }
    //   }
    // },
  },
}
</script>
<style lang="less">
#repetitionGraphy {
  width: 100%;
  height: 100%;
  background: #fff;
  position: relative;
  padding: 10px;
  box-sizing: border-box;
  .repeatTips {
    display: inline-block;
    max-width: 800px;
    font-size: 12px;
    overflow: hidden;
    line-height: 1;
    margin-left: 10px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    color: red;
  }
  .drawImg {
    width: 100%;
    margin-top: 10px;
    height: calc(100% - 40px);
  }
  .upload-demo {
    display: inline-block;
  }
  .stepContainer {
    width: 100%;
    position: absolute;
    top: 0;
    left: 50%;
    margin-left: -50%;
    z-index: 9;
    background-color: #fff;
  }
  .floorList {
    position: absolute;
    width: 100px;
    max-height: 250px;
    overflow-x: hidden;
    overflow-y: auto;
    left: 40px;
    top: 200px;
    z-index: 10;
    background: #fff;
    border: 1px solid #ccc;
    li {
      box-sizing: border-box;
      padding: 0 10px;
      width: 100%;
    }
  }
}
</style>
