<template>
  <el-dialog id='checkGraphy' title='添加平面图' :visible.sync='checkGraphyVisible' width='500px' @close='handleClose'>
    <div class='bodys'>
      <el-cascader
        :options='options'
        :show-all-levels='false'
        @change='handleChange'
        @active-item-change='handleItemChange'
        clearable
        placeholder='请选择模型文件'
        v-model='casVal'
      ></el-cascader>
      <!-- <span>
                &nbsp;&nbsp;或&nbsp;&nbsp;
                <el-upload class='upload-demo' action='string' :http-request='uploadAndSubmit' :show-file-list='false'>
                    <el-button type>上传图片</el-button>
                </el-upload>
                <span>（支持jpg,png格式）</span>
            </span> -->
      <!-- 展示框 -->
      <!-- <div class='showBox'>
        <drawFloor ref='drawFloorDialog' :showTools='false' :id='0' :dialog='true'></drawFloor>
      </div> -->
    </div>
    <span slot='footer' class='dialog-footer'>
            <el-button @click='handleClose'>取 消</el-button>
            <el-button type='primary' @click='bindGraphy'>确 定</el-button>
        </span>
  </el-dialog>
</template>
<script>
import drawFloor from './drawFloor'
import { mapGetters } from 'vuex'
import request from '@/api/model/file.js'
import { bindFloorModel } from '@/api/model/file'
import { manageUpdateFloor } from '@/api/scan/request'

export default {
  components: {
    drawFloor,
  },
  computed: {
    ...mapGetters('layout', ['projectId']),
  },
  props: {
    alreadyRelatedModel: {
      default: [],
    },
  },
  data() {
    return {
      casVal: [],
      jsonKey: '', //map.josn
      checkGraphyVisible: false,
      options: [],
      floor: {}, // 当前选中的楼层数据
      modelIdToFloorId: {},
      key: '',
    }
  },
  methods: {
    // 弹窗显示
    showDialog(floor) {
      this.floor = floor
      this.checkGraphyVisible = true
    },
    // 关闭弹窗
    handleClose() {
      this.checkGraphyVisible = false
      this.casVal = []
      // this.$refs.drawFloorDialog.clearGraphy()
    },
    //上传图片
    uploadAndSubmit(item) {
      let file = item.file
      console.log(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=' + file.uid + '.' + 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.jsonKey = ''
                // vm.$refs.drawFloorDialog.initGraphy(vm.key, 3)
                //vm.$emit("getKey", file.uid + '.' + type, vm.keyName);
              }
            }
          }
        }
      }
      reader.readAsArrayBuffer(file)
    },
    // 更新楼层 平面图文件
    bindGraphy() {
      if (!this.jsonKey && !this.key) {
        this.$message.warning('请选择模型文件')
        return
      }
      if (this.alreadyRelatedModel.indexOf(this.modelIdToFloorId[this.jsonKey]) > -1) {
        this.$message.warning('此模型已关联该建筑下的楼层')
        return
      }
      let pa = {
        floorId: this.floor.FloorID,
        buildingId: this.floor.BuildID,
        cover: true,
        currentModelId: this.floor.CurrentModelId
      }
      if (this.jsonKey) {
        pa.id = this.modelIdToFloorId[this.jsonKey]
        bindFloorModel(pa, (res) => {
          this.$message.success('更新成功')
          this.handleClose()
          this.$emit('refresh', this.jsonKey, pa)
        })
      }
      if (this.key) {
        let Param = {
          content: [{ id: this.floor.FloorID, infos: { floorMap: this.key } }]
        }
        manageUpdateFloor(Param, (res) => {
          this.$message.success('更新成功')
          this.handleClose()
          this.$emit('refresh', this.key)
        })
      }
    },
    // 点击多级联动
    handleChange(val) {
      // this.$refs.drawFloorDialog.initGraphy(val[1], 1)
      this.jsonKey = val[1]
      this.key = ''
    },
    // 通过id查询文件夹下模型文件
    handleItemChange(val) {
      let data = {
        FolderId: val[0],
        Status: '4',
        ProjectId: this.projectId,
      }
      request.queryFloorList(data, (res) => {
        let tempArr = res.Content.map((t) => {
          this.modelIdToFloorId[t.CurrentModelId] = t.Id
          return {
            value: t.CurrentModelId,
            label: t.FloorName,
          }
        })
        this.pushChild(this.options, tempArr, val[0])
      })
    },
    // 将模型文件list填到相应的文件夹下
    pushChild(options, arr, Code) {
      options.map((option) => {
        if (option.value == Code) {
          option.children = arr
        } else {
          if (option.children) {
            this.pushChild(option.children, arr, Code)
          }
        }
      })
    },
    init() {
      this.getDirectory()
    },
    // 获取文件夹
    getDirectory() {
      request.queryModel('', (res) => {
        this.options = res.Content.map((t) => {
          return {
            value: t.Id,
            label: t.Name,
            children: [],
          }
        })
      })
    },
  },
  created() {
    this.init()
  },
  watch: {
    projectId() {
      this.init()
    },
  },
}
</script>
<style lang="less">
#checkGraphy {
  .bodys {
    .upload-demo {
      display: inline-block;
    }

    .showBox {
      box-sizing: border-box;
      width: 100%;
      height: 300px;
      border: 1px #ccc solid;
      padding: 10px;
      margin-top: 20px;
    }
  }
}
</style>
