<template>
  <el-container class="content">
    <el-main>
      <el-row style="z-index:3">
        <el-form :inline="true" class="demo-form-inline" size="mini">
          <el-form-item>
            <el-button @click="bgMove=!bgMove">{{bgMove?'固定':'拖拽'}}底图</el-button>
          </el-form-item>
          <!-- <el-form-item label="宽">
          <el-input-number v-model="width" :min="1" label="描述文字"></el-input-number>
        </el-form-item>
        <el-form-item label="高">
          <el-input-number v-model="height" :min="1" label="描述文字"></el-input-number>
        </el-form-item>
        <el-form-item label="比率">
          <el-input-number v-model="mapRate" label="描述文字"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button @click="createMap">生成网格</el-button>
          </el-form-item>-->
          <!-- <el-form-item>
            <el-button type="primary" @click="">添加点标</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="danger" @click="bgMove=true">取消添加</el-button>
          </el-form-item>-->
          <el-form-item>
            <el-button type="primary" @click="add" icon="el-icon-plus" circle></el-button>
          </el-form-item>

          <el-form-item>
            <el-button type="danger" @click="subtraction" icon="el-icon-minus" circle></el-button>
          </el-form-item>

          <!-- <el-form-item>
            <el-button @click="saveMapInfo" type="warning">保存</el-button>
          </el-form-item>-->
        </el-form>
      </el-row>
      <div class="dragContent" ref="dragContent" :style="{cursor:isDown&&bgMove?'move':(bgMove?'default':'crosshair'),top:bgPosition.top+'px',left:bgPosition.left+'px'}" @mousedown="isDown=true" @mousemove="bgMouseMove" @mouseup="isDown=false">
        <img draggable="false" :src="mapImage" :style="{height:areaHeight+'px'}" ref="bgImg" class="bgImg" alt>
        <!-- <div class="gridInfo" style="z-index:2">
          <div class="grid-item" v-for="(item,index) in oldMapInfo" :style="{width:100/width/rate+'%',height:100/height/rate+'%',backgroundColor:color[item]}"></div>
        </div>-->
        <!-- <div class="gridInfo">
          <div class="grid-item" v-for="(item,index) in mapInfo" @click="choosePoint(index)" :style="{width:100/width/rate+'%',height:100/height/rate+'%',backgroundColor:colorArea[canAdd(item)?0:(parseInt(item)!=0?2:1)],color:canAdd(item)?'#fff':'#666'}">
            <template v-if="chooseIdex===index">
              <img src="../assets/location.png" v-if="!isAreaShowPoint" alt>
              <img src="../assets/door.png" v-else-if='doorFlag' alt="">
              <img src="../assets/location2.png" v-else alt="">
            </template>
          </div>
        </div>-->
        <canvas ref="canvas" class="gridCanvas" @mousedown="drawStart"></canvas>
      </div>
    </el-main>
  </el-container>
</template>
<script>
import { mapState } from 'vuex'
import { format } from 'date-fns'
import zh from 'date-fns/locale/zh_cn'
export default {
  name: 'drugArea',
  props: {
    areaHeight: {
      type: Number,
      default: 100
    },
    landmarkId: {
      type: Number,
      default: 0
    },
    areaId: {
      type: Number,
      default: 0
    },
    mapPointInfo: {
      type: Object,
      default: () => {
        return {
          x: '',
          y: '',
          index: ''
        }
      }
    },
    doorFlag: {
      type: Boolean,
      default: false
    },
    isAreaShowPoint: {
      type: Boolean,
      default: false
    },
    hasRange: {
      type: Boolean,
      default: false
    }
  },
  created() {
    if (this.landmarkId) {
      this.getInfo()
    }

    setTimeout(() => {
      this.areaWidth = this.$refs.bgImg.offsetWidth
      this.$refs.canvas.width = this.areaWidth
      this.$refs.canvas.height = this.areaHeight
      this.drawContent()
    }, 1000)
  },
  data() {
    return {
      areaWidth: 0,
      isDown: false,
      bgMove: false,
      bgPosition: {
        left: 0,
        top: 60
      },
      width: 32,
      height: 22,
      rate: 1,
      mapRate: 1,
      mapInfo: [],
      color: ['rgba(111, 189, 39,0.5)', 'rgba(227,98,100,0.4)', 'rgba(83,147,255,0.4)'],
      colorArea: ['rgba(255,255,255,0)', 'rgba(0,0,0,0.6)', 'rgba(103,46,26,0.6)'],
      nowAdd: 0,
      startMoveIndex: 0,
      nowMoveIndex: 0,
      nowMapInfo: [],
      mapImage: '',
      mapWidth: '',
      mapHeight: '',
      oldMapInfo: [],
      tableData: [],
    }
  },
  watch: {
    landmarkId() {
      this.getInfo()
    },
    mapPointInfo() {
      this.drawContent()
    },
    areaHeight() {
      setTimeout(() => {
        this.areaWidth = this.$refs.bgImg.offsetWidth
        this.$refs.canvas.width = this.areaWidth
        this.$refs.canvas.height = this.areaHeight
        this.drawContent()
      }, 500)
    }
  },
  computed: {
    ...mapState(['totalHeight']),
    chooseIdex() {
      if (this.mapPointInfo.index) {
        return parseInt(this.mapPointInfo.index)
      }
      else {
        return ''
      }

    }

  },
  methods: {
    drawContent() {
      var width = this.areaWidth / this.width
      var height = this.areaHeight / this.height
      var list = [...this.oldMapInfo]
      var ctx = this.$refs.canvas.getContext('2d')
      ctx.clearRect(0, 0, this.areaWidth, this.areaHeight);
      ctx.fillStyle = this.color[0];
      ctx.fillRect(0, 0, this.areaWidth, this.areaHeight);
      for (var i = 0; i < list.length; i++) {
        if (list[i] > 0) {
          ctx.clearRect(width * this.getX(i), height * this.getY(i), width, height);
          ctx.fillStyle = this.color[list[i]];
          ctx.fillRect(width * this.getX(i), height * this.getY(i), width, height);
        }
      }

      ctx.fillStyle = 'rgba(0,0,0,0.2)';
      ctx.fillRect(0, 0, this.areaWidth, this.areaHeight);

      var lineWidth = 2
      if (list.length > 1000) {
        lineWidth = 1
      }
      else if (list.length > 10000) {
        lineWidth = 0.5
      }
      var idList = [...this.mapInfo]

      for (var i = 0; i < idList.length; i++) {

        if (this.canAdd(idList[i])) {
          ctx.clearRect(width * this.getX(i), height * this.getY(i), width, height);
          ctx.fillStyle = this.colorArea[0];
          ctx.fillRect(width * this.getX(i), height * this.getY(i), width, height);
        }

      }

      for (var i = 0; i < this.width; i++) {
        ctx.beginPath();
        ctx.lineWidth = lineWidth;
        ctx.moveTo(width * i, 0);
        ctx.lineTo(width * i, this.areaHeight);
        ctx.strokeStyle = 'rgb(255,255,255,255)';
        ctx.stroke();
      }

      for (var i = 0; i < this.height; i++) {
        ctx.beginPath();
        ctx.lineWidth = lineWidth;
        ctx.moveTo(0, height * i);
        ctx.lineTo(this.areaWidth, height * i);
        ctx.strokeStyle = 'rgb(255,255,255,255)';
        ctx.stroke();
      }

      if (this.mapPointInfo.index) {
        //  <img src="../assets/location.png" v-if="!isAreaShowPoint" alt>
        //       <img src="../assets/door.png" v-else-if='doorFlag' alt="">
        //       <img src="../assets/location2.png" v-else alt="">
        var img = new Image();
        if (!this.isAreaShowPoint) {
          img.src = require('../assets/1280700.png');
        }
        else if (this.doorFlag) {
          img.src = require('../assets/657087.png');
        }
        else {
          img.src = require('../assets/1280700.png');
        }
        var x = this.mapPointInfo.x
        var y = this.mapPointInfo.y
        img.onload = function () {
          ctx.drawImage(img, x * width + width / 2 - 16, y * height + height / 2 - 32);
        };



        if (this.hasRange && this.mapPointInfo.angle) {
          var img2 = new Image();
          img2.src = require('../assets/fangxiang.png');
          img2.onload = () => {
            ctx.moveTo(x * width + width / 2, y * height + height / 2);
            ctx.lineTo(x * width + width / 2+50, y * height + height / 2);
            ctx.setLineDash([5,5]);
             ctx.lineWidth =2;
            ctx.strokeStyle = 'rgb(0,0,0,0.5)';
            ctx.stroke();
             ctx.setLineDash([5,0]);
              ctx.lineWidth =1;
            ctx.translate(x * width + width / 2, y * height + height / 2);
            ctx.rotate(-Number(this.mapPointInfo.angle) * Math.PI / 180);
            ctx.drawImage(img2, 0, -8)
            ctx.rotate(Number(this.mapPointInfo.angle) * Math.PI / 180);
            ctx.translate(-x * width - width / 2, -y * height - height / 2);
            ctx.font = "14px 微软雅黑";
            ctx.fillStyle = 'red';
            ctx.fillText(Number(this.mapPointInfo.angle), x * width + width, y * height + 5, 100);
              ctx.fillText(Number(this.mapPointInfo.angle), x * width + width+0.5, y * height + 5+0.5, 100);
          }
        }
      }


    },
    choosePoint(index) {
      if (this.bgMove) {
        return
      }
      if (this.canAdd(this.mapInfo[index]) && !this.isAreaShowPoint) {
        this.$emit('choosePoint', {
          x: this.getX(index),
          y: this.getY(index),
          index: index
        })
      }
      else if (!this.canAdd(this.mapInfo[index]) && this.isAreaShowPoint) {
        this.$emit('choosePoint', {
          x: this.getX(index),
          y: this.getY(index),
          index: index
        })
      }
      else {
        this.$alert('只能在区域' + (this.isAreaShowPoint ? '外' : '内') + '添加', '提示', {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
      }

    },
    canAdd(id) {
      if (this.areaId) {
        if (this.areaId == parseInt(id)) {
          return true
        }
        else {
          return false
        }
      }
      else {
        return true
      }
    },
    add() {
      this.$emit('mapAddition')
    },
    subtraction() {
      this.$emit('subtraction')
    },
    bgMouseMove(e) {
      
      if (this.isDown) {
        if (this.bgMove) {
          var width = this.$refs.dragContent.offsetWidth
          var height = this.$refs.dragContent.offsetHeight
          var left = this.bgPosition.left + e.movementX
          var top = this.bgPosition.top + e.movementY
          if (left > 0) {
            left = 0
          }
          if (left < 0 - width + window.innerWidth*0.35-50) {
            left = this.bgPosition.left
          }

          if (top > 60) {
            top = 60
          }
          if (top < 0 - height +window.innerHeight*0.5-50) {
            top = this.bgPosition.top
          }
          this.bgPosition = {
            left: left,
            top: top
          }
        }

      }
    },
    createMap() {
      var sum = this.width * this.rate * this.height * this.rate
      var list = []
      for (var i = 0; i < sum; i++) {
        list.push(0)
      }
      this.mapInfo = list
      this.nowAdd = 0
      //   this.drawContent()

    },

    addStart(index) {
      if (this.bgMove) {
        return
      }
      this.nowMapInfo = [...this.mapInfo]
      this.startMoveIndex = index
      if (parseInt(this.nowAdd) != 0 && parseInt(this.mapInfo[index]) > 0) {

      }
      else {
        this.mapInfo.splice(index, 1, this.nowAdd)
      }

    },
    changeMap(index) {
      if (this.bgMove) {
        return
      }
      if (this.isDown) {
        this.nowMoveIndex = index
        this.mapInfo = [...this.nowMapInfo]
        this.getChangeList(this.startMoveIndex, index).forEach(item => {
          if (parseInt(this.nowAdd) != 0 && parseInt(this.mapInfo[item]) > 0) {
          }
          else {
            this.mapInfo.splice(item, 1, this.nowAdd)
          }
        })
      }

    },
    getX(index) {
      return index % (this.width * this.rate)
    },
    getY(index) {
      return parseInt(index / (this.width * this.rate))
    },
    getChangeList(index1, index2) {
      var list = []
      var list1 = [this.getX(index1), this.getX(index2)].sort((a, b) => { return a - b })
      var list2 = [this.getY(index1), this.getY(index2)].sort((a, b) => { return a - b })
      for (var i = list1[0]; i <= list1[1]; i++) {
        for (var j = list2[0]; j <= list2[1]; j++) {
          if (list.indexOf(this.getIndex(i, j)) == -1) {
            list.push(this.getIndex(i, j))
          }
        }
      }
      return list
    },
    getIndex(x, y) {
      return y * (this.width * this.rate) + x
    },
    saveMapInfo() {

      if (this.landmarkId) {


        var data = {
          id: this.landmarkId,
          mapWidth: this.width,
          mapHeight: this.height,
          rate: this.rate,
          areaMapInfo: this.mapInfo.join(','),
        };

        this.$http.post({
          url: '/landMark/update',
          data: data
        }).then(res => {
          if (res.success) {
            this.$message.success('成功');
          } else {
            this.$message.warning('失败')
          }
        });

      }
    },
    rowClick(row, event, column) {
      this.nowAdd = row.id
      this.bgMove = false
    },
    getInfo() {
      this.$http.get({
        url: '/landMark/getOne',
        data: {
          id: this.landmarkId
        }
      }).then(res => {
        if (res.success) {


          this.width = res.data.mapWidth || 20;
          this.height = res.data.mapHeight || 20;
          this.mapRate = res.data.mapRate || 1;
          if (res.data.mapInfo) {
            this.oldMapInfo = res.data.mapInfo.split('');
          }

          if (res.data.areaMapInfo) {
            this.mapInfo = res.data.areaMapInfo.split(',')
          }
          else {
            var list = []
            this.oldMapInfo.forEach(item => {
              list.push(0)
            })
            this.mapInfo = list
          }

          this.mapImage = res.data.mapSprite || require('../assets/demo_picture.jpg');

        }
      })
    },
    drawStart(e) {
      var width = this.areaWidth / this.width
      var height = this.areaHeight / this.height
      var x = parseInt(e.offsetX / width)
      var y = parseInt(e.offsetY / height)
      this.choosePoint(y * this.width + x)
    },
  }
}



</script>
<style lang="less" scoped>
.content {
  position: relative;
}
.dragContent {
  position: absolute;
  top: 60px;
  left: 0;
  border: 2px dashed #ccc;
  // cursor: move;
  z-index: 1;
  .gridInfo {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 3;
    display: flex;
    flex-wrap: wrap;

    .grid-item {
      background-color: rgba(0, 0, 0, 0.3);
      box-sizing: border-box;
      border: 1px solid rgba(255, 255, 255, 1);
      text-align: center;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-weight: bold;
      font-size: 18px;
      img {
        width: 50%;
      }
    }
  }

  .gridCanvas {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 3;
  }
}
.bgImg {
  position: relative;
  width: auto;
  z-index: 2;
}
</style>
