<template>
  <Dialog ref="dialog" class="dth-add" title="添加户型" width="300px" height="380px" left="765px" top="100px" :closeCallback="clean">
    <el-form ref="form" :model="form" label-width="90px">
      <el-form-item label="户型名称：">
        <el-input size="mini" v-model="form.name" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item label="底部高程：">
        <el-input-number size="mini" v-model="form.bottom" controls-position="right" @change="createDth" :min="0"
          :max="9999999" :step="0.1"></el-input-number>
      </el-form-item>
      <el-form-item label="楼层数：">
        <el-input-number size="mini" v-model="form.floor" controls-position="right" @change="createDth" :min="0"
          :max="999"></el-input-number>
      </el-form-item>
      <el-form-item label="层高：">
        <el-input-number size="mini" v-model="form.height" controls-position="right" @change="createDth" :min="0"
          :max="999"></el-input-number>
      </el-form-item>
      <el-form-item label="房间号：">
        <el-input-number size="mini" v-model="form.room_num" controls-position="right" :min="0"
          :max="999999"></el-input-number>
      </el-form-item>
      <el-form-item label="最小楼层号：">
        <el-input-number size="mini" v-model="form.min_floor_num" controls-position="right" :min="0"
          :max="999999"></el-input-number>
      </el-form-item>
    </el-form>
    <template slot="foot">
      <!-- <button @click="drawRange">绘制范围</button> -->
      <button @click="onSubmit">确认</button>
    </template>
    <span class="custom-divider"></span>
  </Dialog>
</template>

<script>
import Dialog from './Dialog.vue'

export default {
  components: {
    Dialog,
  },
  props: {
    options: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      params: [],
      form: {
        height: 3,
        floor: 2,
        bottom: 0,
        room_num: 1,
        min_floor_num: 1
      }
    }
  },
  created() {
  },
  mounted() {
    this.$nextTick(() => {
    })
  },
  methods: {
    open() {
      this.$refs.dialog.open()
    },
    close() {
      this.$refs.dialog.close()
    },
    clean() {
      this.Draw && this.Draw.end()
      this.Draw = null
      this.options.dth.clearAllUnitPrimitive()
      this.options.dth.clearDthPrimitive('temporary')
    },
    async onSubmit() {
      if (!this.form.name) {
        this.$message({
          message: '户型名称不能为空！',
          type: 'warning',
          duration: 1500
        });
        return
      }
      let url = ""
      if (this.options.host.endsWith("yjearth4.0")) {
        url = this.options.host + '/api/v1/dth/huxing/add'
      }
      else {
        url = this.options.host + '/yjearth4.0/api/v1/dth/huxing/add'
      }
      try {
        let params = this.initData()
        let response = await fetch(url, {
          method: 'post',
          body: JSON.stringify({ name: this.form.name, build_id: this.build.ID, dan_yuan_id: this.unit.ID, params }),
          headers: {
            'Content-Type': 'application/json',
            "token": this.options.token,
            "Authorization": "Bearer " + this.options.token,
          }
        })
        if (response.status === 200) {
          let data = await response.json()
          if (data.code === 200 || data.code === 0) {
            this.$message({
              message: '添加成功！',
              type: 'success',
              duration: 1500
            });
            this.close()
            this.options.dth.clearAllUnitPrimitive()
            this.options.dth.clearDthPrimitive()
            this.$emit('getHXList', this.unit.ID)
            // this.$emit('onSubmitCallBack')
          }
        }
      } catch (error) {
        console.log(error)
      }
    },

    drawRange(data) {
      this.build = data.build
      this.unit = data.unit
      this.options.dth.deactivate()
      this.Draw && this.Draw.end()
      this.Draw = new YJ.Draw.DrawPolygon(this.options.sdk)
      this.Draw.start((a, positions) => {
        this.options.dth.activate()
        if (positions.length < 3) {
          this.$message({
            message: '至少需要三个点',
            type: 'warning',
            duration: 1500
          });
          this.options.dth.clearAllUnitPrimitive()
          return
        }
        else {
          let range = JSON.parse(this.unit.range)
          let array = []
          for (let i = 0; i < range.length; i++) {
            array.push([range[i].lng, range[i].lat])
          }
          let unit = turf.polygon([array]);
          let array2 = []
          for (let i = 0; i < positions.length; i++) {
            array2.push([positions[i].lng, positions[i].lat])
          }
          array2.push([positions[0].lng, positions[0].lat])
          let hx = turf.polygon([array2]);
          let intersection = turf.intersect(unit, hx);
          console.log(intersection)
          if (!intersection) {
            this.$message({
              message: '请在单元范围内绘制!',
              type: 'warning',
              duration: 1500
            });
            this.options.dth.clearAllUnitPrimitive()
            return
          }
          let hxPos = []
          for (let i = 0; i < intersection.geometry.coordinates[0].length; i++) {
            hxPos.push({ lng: intersection.geometry.coordinates[0][i][0], lat: intersection.geometry.coordinates[0][i][1] })
          }
          this.open()
          this.form.range = hxPos
          let bottom = positions[0].alt
          for (let i = 1; i < positions.length; i++) {
            if (bottom > positions[i].alt) {
              bottom = positions[i].alt
            }
          }
          this.form.bottom = Number(bottom.toFixed(2))
          this.createDth()
        }
      })
    },

    createDth() {
      this.options.dth.clearDthPrimitive('temporary')
      let params = this.initData()
      for (let i = 0; i < params.length; i++) {
        params[i].ID = 'temporary'
      }
      this.options.dth.addDthPrimitive(params, this.build, this.unit)
    },

    initData() {
      let array = []
      for (let i = 0; i < this.form.floor; i++) {
        array.push({
          range: JSON.stringify(this.form.range),
          bottom: this.form.bottom + (i * this.form.height),
          top: this.form.bottom + ((i + 1) * this.form.height),
          height: this.form.height,
          room_num: (this.form.min_floor_num + i) + '-' + this.form.room_num,
          floor_num: this.form.min_floor_num + i
        })
      }
      return array
    }
  }
}
</script>

<style scoped>
</style>