<template>
  <div
    class="seatChart"
    :class="{isFullscreen:isFullscreen}"
    ref="container">
    <div
      class="blankWrap"
      v-if="!seats.length">
      <p>当前座位表，未设置座位</p>
      <el-button
        type="primary"
        @click="$router.push({name:'seatConfig'})">
        立即设置
      </el-button>
    </div>
    <div style="z-index:999;position:absolute;right:20px;top:20px">
      <el-button
        v-if="currentTool !== 'removeLock'"
        type="primary"
        @click="$refs.dialog.show()">
        锁定座位
      </el-button>
      <el-button
        v-else
        type="primary"
        @click="lockSeat(null,type='removeLock')">
        解锁座位
      </el-button>
    </div>
    <v-stage
      ref="stage"
      :config="configKonva"
      style="background:#ddd"
      @click="handleStageClick"
      @wheel="handleWheel"
      @dragend="handleDragEnd"
      @mousedown="handleMouseDown"
      @mousemove="handleMouseMove"
      @mouseup="handleMouseUp">
      <v-layer>
        <v-group ref="group">
          <v-rect :config="bgConfig"></v-rect>

          <v-line :config="colLine"></v-line>
          <v-line :config="rowLine"></v-line>

          <v-circle
            v-for="(seat,index) in seats"
            :key="index"
            ref="seat"
            :config="seat"
            @mouseleave="handleSeatMouseLeave"
            @mouseenter="handleSeatMouseEnter"
          ></v-circle>

          <v-text
            v-for="(row,index) in seatsText"
            :key="'seat'+index"
            :config="row"></v-text>

          <v-text
            v-for="(row,index) in rowText1"
            :key="'a'+index"
            :config="row"></v-text>

          <v-text
            v-for="(row,index) in rowText2"
            :key="'b'+index"
            :config="row"></v-text>

          <v-text
            v-for="(col,index) in colText1"
            :key="'c'+index"
            :config="col"></v-text>

          <v-text
            v-for="(col,index) in colText2"
            :key="'d'+index"
            :config="col"></v-text>

          <v-rect
            :config="configSelection"
            ref="selection"></v-rect>

          <v-rect
            :config="val"
            v-for="(val,key) in rowRect"
            :key="'rowrect1'+key"></v-rect>

          <v-text
            :config="val"
            v-for="(val,key) in rowObject"
            :key="'row1'+key"></v-text>

          <v-rect
            :config="val"
            v-for="(val,key) in rowRect2"
            :key="'rowrect2'+key"></v-rect>

          <v-text
            :config="val"
            v-for="(val,key) in rowObject2"
            :key="'row2'+key"></v-text>
        </v-group>
      </v-layer>
    </v-stage>

    <div class="toolbar">
      <ul>
        <li
          :class="{active:currentTool===t.value}"
          @click="handleToolChange(t)"
          v-for="(t,i) in tools"
          :key="i">
          <el-tooltip
            :content="t.label"
            placement="left"
            effect="dark">
            <img
              :src="t.img"
              :width="t.size">
          </el-tooltip>
        </li>
      </ul>
    </div>

    <div
      class="popup"
      :class="{show:showPop}"
      :style="[popupStyle]">
      <div class="title">
        座位信息
      </div>
      <ul class="content">
        <li>排数：{{ popInfo.row_tag || '无' }}</li>
        <li>座位号：{{ popInfo.text || '无' }}</li>
        <li>座位名：{{ popInfo.seatName || '无' }}</li>
        <li>座位id：{{ popInfo.seat_id || '无' }}</li>
        <li>
          状态：
          <span
            style="color:red"
            v-if="popInfo.noprice">未绑定票种</span>
          <span
            :style="{color:popInfo.status ===1?'blue':'red'}"
            v-else>{{ popInfo.status ===0?'已售': popInfo.status ===2?'已锁定':'可售' }}</span>
        </li>
        <li v-if="popInfo.status===2 && popInfo.remark">
          备注：{{ popInfo.remark }}
        </li>
      </ul>
    </div>

    <div class="status-wrap">
      <span class="item">
        总数：<b>{{ this.totalNum }}</b>
      </span>
      <span class="item">
        可售：<b>{{ this.activeNum }}</b>
      </span>
      <span class="item">
        已售：<b>{{ this.saleNum }}</b>
      </span>
      <span class="item">
        冻结：<b>{{ this.lockNum }}</b>
      </span>
    </div>
    <!-- <div style="display: flex; flex-direction: column;position: absolute; left: 10px;top: 30px;">
      <div
        v-for="(item,index) in areaList"
        :key="index"
        class="status-wrap1">
        <span class="item">
          区域：<b>{{ item.name }}</b>
        </span>
        <span class="item">
          总数：<b>{{ item.totalSeat }}</b>
        </span>
        <span class="item">
          可售：<b>{{ item.leftSeat }}</b>
        </span>
        <span class="item">
          已售：<b>{{ item.usedSeat }}</b>
        </span>
      </div>
    </div> -->

    <Dialog
      ref="dialog"
      @update="lockSeat"></Dialog>
  </div>
</template>

<script>
import Konva from 'konva'
import throttle from 'lodash/throttle'
import { updateBatchSeat } from '@/api/batch'
import Dialog from './Dialog'
import moment from 'moment'
const SEAT_SIZE = 30
const SEATS_DISTANCE = 40
const STAGE_PADDING = 120

const defautColor = 'rgba(220,220,220,0.5)'
// config.fill = 'rgba(74,144,226,0.5)' // blue
// config.fill = 'rgba(126,211,33,0.5)' // green
const configCircle = {
  x: 50,
  y: 50,
  radius: SEAT_SIZE / 2,
  fill: defautColor,
  stroke: 'rgb(74, 144, 226)',
  strokeWidth: 0,
  name: 'seat',
  isSelected: false
}

const tools = [
  {
    label: '座位选择',
    value: 'seatSelect',
    img: require('./icons/select.png'),
    size: 30
  },
  // {
  //   label: '空位选择',
  //   value: 'blankSelect',
  //   img: require('./icons/blankSelect.png'),
  //   size: 30
  // },
  {
    label: '框选删除',
    value: 'removeSelect',
    img: require('./icons/delete.png'),
    size: 36
  },
  {
    label: '框选解锁',
    value: 'removeLock',
    img: require('./icons/blankSelect.png'),
    size: 30
  },
  {
    label: '重置舞台',
    value: 'resetSize',
    img: require('./icons/resize.png'),
    size: 24
  },
  {
    label: '全屏',
    isNotChange: true,
    value: 'fullscreen',
    img: require('./icons/fullscreen.png'),
    size: 24
  }
]

export default {
  props: {
    areaList: {
      type: Array,
      default: () => []
    },
    data: {
      type: Array,
      default: () => []
    },
    batchCondigId: {
      type: Number,
      default: 0
    },
    batchDate: {
      type: Date,
      default: ''
    },
    rows: {
      type: Number,
      default: 10
    },
    columns: {
      type: Number,
      default: 10
    },
    value: {
      type: Array,
      default: () => []
    }
  },
  created () {
    // this.reset()
  },
  components: {
    Dialog
  },
  computed: {
    totalNum () {
      return this.seats.length
    },
    activeNum () {
      const seats = this.seats.filter(i => i.status === 1 && !i.noprice)
      return seats.length
    },
    saleNum () {
      const seats = this.seats.filter(i => i.status === 0)
      return seats.length
    },
    lockNum () {
      const seats = this.seats.filter(i => i.status === 2)
      return seats.length
    },
    selectionEl () {
      return this.$refs.selection.getNode()
    },
    stage () {
      return this.$refs.stage.getNode()
    },
    group () {
      return this.$refs.group.getNode()
    },
    selected () {
      return this.seats.filter(item => {
        return item.isSelected
      })
    },
    seatsText () {
      return this.seats.map(seat => {
        const s = Object.assign({}, seat)

        return {
          x: s.x - SEAT_SIZE / 2,
          y: s.y - SEAT_SIZE / 2,
          width: SEAT_SIZE,
          height: SEAT_SIZE,
          fill: '#fff',
          align: 'center',
          text: s.text,
          verticalAlign: 'middle',
          fontSize: SEAT_SIZE / 2,
          listening: false
        }
      })
    }
  },
  data () {
    return {
      tools,
      scaleBy: 1.1,
      newScale: 1,
      currentTool: 'seatSelect',
      configKonva: {
        width: 1000,
        height: 800,
        scaleX: 1,
        scaleY: 1,
        x: 0,
        y: 0,
        draggable: false
      },
      textConfig: {
        x: 0,
        y: 0,
        text: '第一排',
        fill: '#000',
        width: 100,
        align: 'center',
        fontSize: 18
      },
      colLine: {
        points: [0, 0, 0, 0],
        stroke: 'red',
        strokeWidth: 1,
        visible: false
      },
      rowLine: {
        points: [0, 0, 0, 0],
        stroke: 'red',
        strokeWidth: 1,
        visible: false
      },
      bgConfig: {
        x: 0,
        y: 0,
        width: 300,
        height: 300,
        fill: 'rgba(255,255,255,0.8)'
      },
      seats: [],
      colText1: [],
      colText2: [],
      rowText1: [],
      rowText2: [],
      selectPosition: {
        x1: 0,
        y1: 0,
        x2: 0,
        y2: 0
      },
      configSelection: {
        width: 0,
        height: 0,
        visible: false,
        fill: 'rgba(48,77,121,0.5)'
      },
      showPop: false,
      popupStyle: {
        left: 0,
        top: 0
      },
      popInfo: {},
      isFullscreen: false,
      rowObject: {},
      rowRect: {},
      rowObject2: {},
      rowRect2: {}
    }
  },
  methods: {
    reset () {
      // this.createSeats()

      // this.setRowText()
      // this.setColText()
    },
    initSize () {
      this.bgConfig.width = SEATS_DISTANCE * (this.columns - 1) + STAGE_PADDING * 2 + SEAT_SIZE
      this.bgConfig.height = SEATS_DISTANCE * (this.rows - 1) + STAGE_PADDING * 2 + SEAT_SIZE
      this.configKonva.width = 0
      this.configKonva.height = 0

      this.$nextTick(() => {
        const { offsetWidth: width, offsetHeight: height } = this.$refs.container

        this.configKonva.width = width
        this.configKonva.height = height

        const clientRect = this.stage.getClientRect({ skipTransform: true })

        this.clientRect = clientRect

        // 根据容器进行缩放
        if (width / height >= clientRect.width / clientRect.height) {
          this.newScale = height / (clientRect.height)
          this.configKonva.y = 0
          this.configKonva.x = (width - clientRect.width * this.newScale) / 2
        } else {
          this.newScale = width / (clientRect.width)
          this.configKonva.x = 0
          this.configKonva.y = (height - clientRect.height * this.newScale) / 2
        }

        this.configKonva.scaleX = this.newScale
        this.configKonva.scaleY = this.newScale

        this.initStageSize = JSON.parse(JSON.stringify(this.configKonva))
      })
    },
    lockSeat (remark, type) {
      this.$confirm(`确定${type ? '解锁' : '锁定'}已选中的座位？`, '确认提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let list = this.selected.map(item => {
          return {
            batch_config_id: this.batchCondigId,
            batch_date: moment(this.batchDate).format('YYYY-MM-DD'),
            seat_id: item.seat_id
          }
        })
        let params = {
          list: list,
          remark: remark || '',
          status: type ? 1 : 2
        }
        updateBatchSeat(params).then(res => {
          this.$message.success(type ? '解锁座位成功' : '锁定座位成功')
          this.$emit('updateSeat')
        })
      })
    },
    createSeats () {
      const seats = Array(this.columns * this.rows).fill(configCircle)
      this.seatMap = {}

      this.seats = seats.map((item, index) => {
        const seat = Object.assign({}, item)
        const xIndex = (index) % this.columns
        const yIndex = Math.floor(index / this.columns)

        seat.location = {
          x: xIndex,
          y: yIndex
        }

        seat.x = STAGE_PADDING + SEATS_DISTANCE * xIndex + SEAT_SIZE / 2
        seat.y = STAGE_PADDING + SEATS_DISTANCE * yIndex + SEAT_SIZE / 2
        seat.id = index

        // 座位定位表
        this.seatMap[`seat_${xIndex}_${yIndex}`] = seat

        return seat
      })
    },
    setRowText () {
      const rowText = Array(this.rows).fill({
        x: 0,
        y: 0,
        text: 0,
        fill: 'rgb(48,77,121)'
      })

      this.rowText1 = rowText.map((item, index) => {
        const text = Object.assign({}, item)

        text.text = index + 1
        text.x = STAGE_PADDING - SEATS_DISTANCE
        text.y = STAGE_PADDING + SEATS_DISTANCE * index
        text.height = SEAT_SIZE
        text.fontSize = SEAT_SIZE
        text.verticalAlign = 'middle'

        return text
      })

      this.rowText2 = rowText.map((item, index) => {
        const text = Object.assign({}, item)

        text.text = index + 1
        text.x = STAGE_PADDING + SEATS_DISTANCE * this.columns
        text.y = STAGE_PADDING + SEATS_DISTANCE * index
        text.height = SEAT_SIZE
        text.fontSize = SEAT_SIZE
        text.verticalAlign = 'middle'

        return text
      })
    },
    setColText () {
      const colText = Array(this.columns).fill({
        x: 0,
        y: 0,
        text: 0,
        fill: 'rgb(48,77,121)'
      })

      this.colText1 = colText.map((item, index) => {
        const text = Object.assign({}, item)

        text.text = index + 1
        text.x = STAGE_PADDING + SEATS_DISTANCE * index + SEAT_SIZE / 2 - SEATS_DISTANCE / 2
        text.y = STAGE_PADDING + SEATS_DISTANCE * this.rows
        text.fontSize = SEAT_SIZE
        text.height = SEATS_DISTANCE
        text.width = SEATS_DISTANCE
        text.align = 'center'

        return text
      })

      this.colText2 = colText.map((item, index) => {
        const text = Object.assign({}, item)

        text.text = index + 1
        text.x = STAGE_PADDING + SEATS_DISTANCE * index + SEAT_SIZE / 2 - SEATS_DISTANCE / 2
        text.y = STAGE_PADDING - SEATS_DISTANCE
        text.fontSize = SEAT_SIZE
        text.height = SEATS_DISTANCE
        text.width = SEATS_DISTANCE
        text.align = 'center'

        return text
      })
    },
    handleWheel (e) {
      if (this.configSelection.visible) return

      const scaleBy = this.scaleBy
      e.evt.preventDefault()

      var oldScale = this.stage.scaleX()

      var pointer = this.stage.getPointerPosition()

      var mousePointTo = {
        x: (pointer.x - this.stage.x()) / oldScale,
        y: (pointer.y - this.stage.y()) / oldScale
      }

      this.newScale =
          e.evt.deltaY > 0 ? oldScale * scaleBy : oldScale / scaleBy

      this.configKonva = Object.assign({}, this.configKonva, {
        x: pointer.x - mousePointTo.x * this.newScale,
        y: pointer.y - mousePointTo.y * this.newScale,
        scaleX: this.newScale,
        scaleY: this.newScale
      })
    },
    handleStageClick (e) {
      const { x1, y1, x2, y2 } = this.selectPosition

      // 区分点击还是画框
      if (Math.abs(x1 - x2) >= 5 || Math.abs(y1 - y2) >= 5) {
        return
      }

      if (e.target.className !== 'Circle') {
        // 未选中座位不重置
        return
        // // 重置选中状态
        // this.seats.forEach(seat => {
        //   seat.fill = seat.color
        //   seat.isSelected = false
        //   // 锁定的座位不操作
        //   if (seat.status === 2 && seat.remark) return

        //   seat.strokeWidth = 0
        // })
      } else {
        const target = this.seats.find(i => e.target.attrs.id === i.id)

        if (e.target.attrs.status === 0) return
        if (e.target.attrs.status === 1 && this.currentTool === 'removeLock') return
        if (e.target.attrs.status === 2 && this.currentTool === 'seatSelect') return
        if (e.target.attrs.noprice) return

        target.isSelected = !target.isSelected
        target.fill = target.isSelected ? 'red' : target.color
        target.strokeWidth = target.isSelected ? 2 : 0
      }
      this.$parent.handleAreaClick({ color: e.target.attrs.color, id: e.target.attrs.area_id, name: e.target.attrs.areaName })
    },
    handleMouseDown (e) {
      if (this.configKonva.draggable) return

      const pos = this.stage.getPointerPosition()

      this.selectPosition = {
        x1: pos.x,
        y1: pos.y,
        x2: pos.x,
        y2: pos.y
      }
      this.configSelection = Object.assign({}, this.configSelection, {
        // visible: true,
        width: 0,
        height: 0
      })
      this.selectIsStart = true
    },
    handleMouseMove: throttle(function () {
      // 参考线
      // if (this.configSelection.visible) {
      //   this.colLine.visible = false
      //   this.rowLine.visible = false
      // } else {
      //   this.setLinePosition()
      // }

      if (this.configKonva.draggable) return

      this.selectPosition.x2 = this.stage.getPointerPosition().x
      this.selectPosition.y2 = this.stage.getPointerPosition().y

      const { x1, y1, x2, y2 } = this.selectPosition
      // 舞台偏移
      const { x, y } = this.stage.absolutePosition()

      if (!this.selectIsStart) return

      if (Math.abs(x1 - x2) >= 3 && Math.abs(y1 - y2) >= 3) {
        this.configSelection.visible = true
      }

      if (!this.configSelection.visible) return

      this.configSelection = Object.assign({}, this.configSelection, {
        x: (Math.min(x1, x2) - x) / this.newScale,
        y: (Math.min(y1, y2) - y) / this.newScale,
        width: Math.abs(x2 - x1) / this.newScale,
        height: Math.abs(y2 - y1) / this.newScale
      })
    }, 50),
    // 设置参考线位置
    setLinePosition: throttle(function () {
      // 舞台偏移
      const { x, y } = this.stage.absolutePosition()

      const { x: currentX, y: currentY } = this.stage.getPointerPosition()

      this.colLine.points = [(currentX - x) / this.newScale, 0, (currentX - x) / this.newScale, this.clientRect.height]

      if (currentX - x <= 0 || (currentX - x) >= this.clientRect.width * this.newScale) {
        this.colLine.visible = false
      } else {
        this.colLine.visible = true
      }

      this.rowLine.points = [0, (currentY - y) / this.newScale, this.clientRect.width, (currentY - y) / this.newScale]

      if (currentY - y <= 0 || (currentY - y) >= this.clientRect.height * this.newScale) {
        this.rowLine.visible = false
      } else {
        this.rowLine.visible = true
      }
    }, 50),
    handleMouseUp () {
      this.selectIsStart = false

      if (!this.configSelection.visible) return

      setTimeout(() => {
        this.configSelection.visible = false
        this.selectPosition = {
          x1: 0, y1: 0, x2: 0, y2: 0
        }
      }, 50)

      const { x1, y1, x2, y2 } = this.selectPosition

      if (Math.abs(x1 - x2) <= 5 && Math.abs(y1 - y2) <= 5) {
        return
      }
      const seatsEl = this.$refs.seat.map(item => {
        return item.getNode()
      })

      const box = this.selectionEl.getClientRect()

      // 选中的元素
      const selected = seatsEl.filter(seat => {
        return Konva.Util.haveIntersection(box, seat.getClientRect())
      })

      selected.forEach(el => {
        let config
        config = this.seats.find(i => i.id === el.attrs.id)
        // 选择现存座位
        if (this.currentTool === 'seatSelect') {
          config = this.seats.find(i => i.id === el.attrs.id && i.area_id && i.status !== 2)
        }
        // 框选锁定座位
        if (this.currentTool === 'removeLock') {
          // 切换选中
          config = this.seats.find(i => i.id === el.attrs.id && i.area_id && i.status === 2)
        }
        if (!config || !config.status || config.noprice) return

        // 框选移除选择
        if (this.currentTool === 'removeSelect') {
          // 切换选中
          config.isSelected = false
          config.fill = config.color
          return
        }

        // 切换选中
        config.isSelected = true
        config.strokeWidth = 2
        config.fill = 'red'
        // config.fill = 'rgba(74,144,226,0.5)' // blue
        // config.fill = 'rgba(126,211,33,0.5)' // green
      })
    },
    handleKeyDown (e) {
      console.log(e.code)
      if (e.code === 'Space') {
        e.preventDefault()
        this.configKonva.draggable = true
      }
      if (e.code === 'F12') {
        e.preventDefault()

        this.isFullscreen = !this.isFullscreen
        const btn = this.tools.find(i => i.value === 'fullscreen')

        btn.label = this.isFullscreen ? '退出全屏' : '全屏'

        this.$nextTick(() => {
          this.initSize()
        })
      }
    },
    handleKeyUp (e) {
      if (e.code === 'Space') {
        e.preventDefault()
        this.configKonva.draggable = false
      }
    },
    handleSeatMouseEnter (e) {
      this.popTimer && clearTimeout(this.popTimer)

      // 无区域id的不显示浮层
      if (!e.target.attrs.area_id) return

      const position = e.target.getAbsolutePosition()

      this.popupStyle = {
        left: 20 + position.x + 'px',
        top: -100 + position.y + 'px'
      }

      this.showPop = true

      this.popInfo = e.target.attrs
      const container = this.stage.getContainer()
      if (e.target.attrs.status && !(e.target.attrs.status === 2 && this.currentTool === 'seatSelect') && !(e.target.attrs.status === 1 && this.currentTool === 'removeLock') && !e.target.attrs.noprice) {
        container.style.cursor = 'pointer'
      } else {
        container.style.cursor = 'not-allowed'
      }
    },
    handleSeatMouseLeave (e) {
      this.popTimer && clearTimeout(this.popTimer)

      this.showPop = false

      this.popTimer = setTimeout(() => {
        this.popInfo = {}
      }, 500)

      const container = this.stage.getContainer()
      container.style.cursor = ''
    },
    handleDragEnd (e) {
      this.configKonva.x = this.stage.attrs.x
      this.configKonva.y = this.stage.attrs.y
    },
    handleToolChange (t) {
      if (!t.isNotChange) {
        this.currentTool = t.value
      }

      switch (t.value) {
        case 'seatSelect':
          this.seats.forEach(seat => {
            if (seat.status === 2) {
              seat.isSelected = false
              seat.fill = seat.color
            }
          })
          break
        case 'removeLock':
          this.seats.forEach(seat => {
            if (seat.status === 1) {
              seat.isSelected = false
              seat.fill = seat.color
            }
          })
          break
        case 'resetSize':
          this.configKonva = Object.assign({}, this.configKonva, this.initStageSize)
          break
        case 'fullscreen':
          this.isFullscreen = !this.isFullscreen
          t.label = this.isFullscreen ? '退出全屏' : '全屏'
          this.$nextTick(() => {
            this.initSize()
          })
      }
    },
    getRowText (rowObject) {
      this.rowObject = rowObject
      console.log('%c [ this.rowObject ]-861', 'font-size:13px; background:pink; color:#bf2c9f;', this.rowObject)
      for (let key in rowObject) {
        rowObject[key].x = 10
        rowObject[key].y = STAGE_PADDING + SEATS_DISTANCE * rowObject[key].y
        rowObject[key].text = '第 ' + key + ' 排'

        rowObject[key].fill = '#2987db'
        rowObject[key].width = STAGE_PADDING - 20
        rowObject[key].height = SEAT_SIZE
        rowObject[key].align = 'center'
        rowObject[key].verticalAlign = 'middle'
        rowObject[key].fontSize = 18
      }

      this.rowObject2 = JSON.parse(JSON.stringify(rowObject))
      for (let key in this.rowObject2) {
        this.rowObject2[key].x = this.bgConfig.width - this.rowObject2[key].width - 10
      }

      this.rowRect = JSON.parse(JSON.stringify(rowObject))

      for (let key in this.rowRect) {
        this.rowRect[key].y = this.rowRect[key].y - 4
        this.rowRect[key].height = SEAT_SIZE + 4
        this.rowRect[key].stroke = '#2987db'
        this.rowRect[key].strokeWidth = 2
        this.rowRect[key].fill = '#edf4fd'
      }

      this.rowRect2 = JSON.parse(JSON.stringify(this.rowRect))
      for (let key in this.rowRect2) {
        this.rowRect2[key].x = this.bgConfig.width - this.rowRect2[key].width - 10
      }
    }
  },
  mounted () {
    this.initSize()

    // 监听容器大小变化
    this.boxObserver = new ResizeObserver(entries => {
      this.initSize()
    })

    this.boxObserver.observe(this.$refs.container)

    window.addEventListener('resize', this.initSize)

    document.addEventListener('keydown', this.handleKeyDown)

    document.addEventListener('keyup', this.handleKeyUp)
  },
  beforeDestroy () {
    this.boxObserver.unobserve(this.$refs.container)

    window.removeEventListener('resize', this.initSize)

    document.removeEventListener('keydown', this.handleKeyDown)

    document.removeEventListener('keyup', this.handleKeyUp)
  },
  watch: {
    selected (val) {
      this.$emit('input', val)
    },
    data: {
      handler (val) {
        this.reset()
        this.initStageSize = null

        this.$nextTick(() => {
          this.initSize()

          if (val.length) {
            const rowObject = {}
            this.seats = val.map((item, index) => {
              const seat = Object.assign({}, item)
              if (!rowObject[seat.row_tag]) {
                rowObject[seat.row_tag] = {
                  y: seat.y
                }
              }
              const xIndex = seat.x
              const yIndex = seat.y

              seat.location = {
                x: xIndex,
                y: yIndex
              }

              seat.x = STAGE_PADDING + SEATS_DISTANCE * xIndex + SEAT_SIZE / 2
              seat.y = STAGE_PADDING + SEATS_DISTANCE * yIndex + SEAT_SIZE / 2

              seat.id = seat.seat_id

              seat.radius = SEAT_SIZE / 2

              // seat.name = 'seat'

              seat.text = seat.name
              seat.color = seat.fill // 备份区域颜色值

              seat.isSelected = false

              if (item.status === 2 && item.remark) {
                seat.strokeWidth = 2
                seat.stroke = 'red'
              }
              return seat
            })

            this.getRowText(rowObject)
          } else {
            this.seats = []
          }
        })
      },
      immediate: true
    }
  },
  selected (val) {
    this.$nextTick(() => {
      this.group.cache()
      this.group.getLayer().batchDraw()
    })
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.seatChart {
  position: relative;  width: 100%;height: 100%; overflow: hidden;
  &.isFullscreen{
    position:fixed; left: 0;top: 0;z-index: 1002;
  }
}

.toolbar {
  position: absolute; top: 50%;right: 10px;transform: translateY(-50%); background: #fff; border-radius: 5px; box-shadow: 0 0 10px #ddd;
  li{
    border-bottom: 1px solid #ddd; width: 50px;height: 50px; display: flex; align-items: center; justify-content: center;
  }
  li.active{
    background: rgba(74, 144, 226,0.5);
  }
}

.popup {
  position: absolute; z-index: 999;  min-width: 150px; min-height: 50px;overflow: hidden;line-height: 1.8; pointer-events: none; background: #fff; border: 1px solid rgb(158, 158, 158);border-radius: 5px ; box-shadow: 0 0 10px rgba(0,0,0,.5); opacity: 0;transition: all .3s;
}
.popup .title {
  padding: 0 5px; color: #555; text-align: center;  background: #eee; border-bottom: 1px solid #ddd;
}
.popup .content {
  padding: 5px 10px;
}
.popup.show {
  opacity: 1;
}

.blankWrap{
  position: absolute; left: 50%;top: 50%; transform: translate(-50%,-50%); z-index: 10; color: #666; text-align: center;
}

.status-wrap{
  position: absolute; left: 10px;top: 5px; background: #fff; box-shadow: 0 0 5px rgba(0,0,0,.2); padding: 5px 10px; border-radius: 3px;
  .item{
    display: inline-block;
  }
  .item + .item {
    margin-left: 10px;
  }
  b{
    color: red;
  }
}
.status-wrap1{
   background: #fff; box-shadow: 0 0 5px rgba(0,0,0,.2); padding: 5px 10px; border-radius: 3px;margin-top:20px;
  .item{
    display: inline-block;
  }
  .item + .item {
    margin-left: 10px;
  }
  b{
    color: red;
  }
}
</style>
