<template>
  <el-dialog
    title="座位编辑"
    :visible.sync="visible"
    width="30%"
    fullscreen
    @close="handleClose">
    <div slot="title">
      座位 <span class="note">操作提示：使用<i>鼠标框选</i>快速选择座位<i>（座位选择）</i>或空位<i>（空位选择）</i>；按住<i>空格</i>按下鼠标进行舞台位置移动；鼠标<i>滚轮</i>控制舞台缩放；双击<i>区域标签</i>进行区域编辑</span>
    </div>

    <div
      class="seatEditorWrap"
      element-loading-spinner="el-icon-loading"
      element-loading-text="拼命加载中"
      v-loading="loading">
      <div class="topBar">
        <ul class="areaTag">
          <li>
            <el-tooltip
              content="新增区域"
              placement="bottom"
              effect="dark">
              <el-button
                size="mini"
                icon="el-icon-plus"
                @click="$refs.seatAreaModal.show('add',{config_id:chart.id})"
                circle></el-button>
            </el-tooltip>
          </li>
          <li
            @dblclick="$refs.seatAreaModal.show('edit',item)"
            v-for="(item,index) in areaList"
            :key="index">
            <i :style="{backgroundColor:item.color}"></i> {{ item.name }}
          </li>
        </ul>

        <div class="seatNum">
          当前座位数：<b>{{ this.seatsData.length }}</b>
        </div>
      </div>

      <div class="main">
        <SeatChart
          ref="seatChart"
          :data="seatsData"
          :rows="chart.y"
          :columns="chart.x"
          v-if="visible"
        ></SeatChart>
      </div>

      <div class="controls">
        <el-button
          type="primary"
          @click="$refs.areaAction.show('add')">
          添加座位
        </el-button>

        <el-button
          type="primary"
          @click="$refs.areaAction.show('update')">
          修改座位区域
        </el-button>

        <el-button
          type="primary"
          @click="$refs.seatAreaNameModal.show()">
          座位命名
        </el-button>

        <el-button
          type="primary"
          @click="handleRenamePartrevert">
          部分反向命名
        </el-button>

        <el-button
          type="primary"
          @click="handleRenamePart">
          部分重命名
        </el-button>

        <el-button
          type="primary"
          @click="handleRenameAll">
          一键重命名
        </el-button>

        <el-button
          type="danger"
          @click="handleDeleteSeat">
          删除座位
        </el-button>
      </div>
    </div>

    <!-- <span slot="footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button
        type="primary"
        @click="handleSubmit">保存</el-button>
    </span> -->

    <!-- 座位区域操作弹窗 -->
    <AreaAction
      :get-selected-seats="getSelectedSeats"
      :area-list="areaList"
      :selected-chart="chart.id"
      :selected-area="selectedArea"
      @update="getSeatList"
      ref="areaAction"></AreaAction>

    <!-- 区域编辑 -->
    <SeatAreaModal
      ref="seatAreaModal"
      @update="getAreaList"></SeatAreaModal>

    <!-- 区域编辑名称 -->
    <SeatAreaNameModal
      :get-selected-seats="getSelectedSeats"
      ref="seatAreaNameModal"
      @update="SetAreaName"></SeatAreaNameModal>
  </el-dialog>
</template>

<script>
import {
  getSeatArea,
  getSeatList,
  deleteSeat,
  updateSeat
} from '@/api/seat'

import AreaAction from './AreaAction'
import SeatChart from '@/components/SeatChart'
import SeatAreaModal from './SeatAreaModal'
import SeatAreaNameModal from './SeatAreaNameModal'

import groupby from 'lodash/groupBy'

export default {
  components: {
    SeatChart,
    AreaAction,
    SeatAreaModal,
    SeatAreaNameModal
  },
  data () {
    return {
      loading: false,
      visible: false,
      areaVisible: false,
      chart: { id: 0 },
      areaList: [],
      seatsData: [],
      selectedArea: 0
    }
  },
  methods: {
    async show (chart) {
      this.chart = chart
      this.visible = true
      this.getAreaList()
    },

    handleClose () {
      this.visible = false
    },

    async getAreaList () {
      this.loading = true
      this.colorMap = {}

      // 等待区域列表，进行座位区域染色

      try {
        await getSeatArea({ pageSize: -1, pageNum: 0, keyWords1: this.chart.id }).then(res => {
          this.areaList = res.list
          console.log('this.areaList', this.areaList)
          this.selectedArea = (this.areaList[0] && this.areaList[0].id) || 0

          this.areaList.forEach((item, index) => {
            this.colorMap[item.id] = this.colorPalette[index]
            item.color = this.colorPalette[index]
          })
          console.log('this.areaList', this.areaList)
        })
      } catch (e) {
        console.log(e)

        this.loading = false
      }

      this.getSeatList()
    },

    getSeatList () {
      this.loading = true

      getSeatList({ keyWords1: this.chart.id, pageSize: -1, pageNum: 0 }).then(res => {
        this.seatsData = res.list.map(item => {
          item.fill = this.colorMap[item.area_id] || 'gray'
          return item
        })
      }).finally(() => {
        this.loading = false
      })
    },

    getSelectedSeats () {
      let selected = this.$refs.seatChart.selected

      selected = selected.map((item, index) => {
        return {
          name: (index + 1 + '').padStart(2, '0'),
          x: item.location.x,
          y: item.location.y,
          area_id: item.area_id,
          id: item.seat_id
        }
      })

      return selected
    },

    SetAreaName (seatName) {
      let seats = JSON.parse(JSON.stringify(this.getSelectedSeats()))
      // 按行分组
      let groupSeats = groupby(seats, i => i.y)

      // 所有行号
      let rowKeys = Object.keys(groupSeats)

      // 排序
      rowKeys.sort((a, b) => {
        return Number(a) - Number(b)
      })

      rowKeys.forEach((rowkey, rowIndex) => {
        let row = groupSeats[rowkey]

        // 按x排序
        row.sort((a, b) => {
          return a.x - b.x
        })
        row.forEach((item, index) => {
          item.name = (index + 1 + '').padStart(2, '0')
          item.row_tag = (rowIndex + 1 + '')
          item.seatName = seatName
        })
      })
      updateSeat({
        seats
      }).then(res => {
        this.$message.success('操作成功')

        this.getSeatList()
      })
    },
    // 部分反向重命名
    handleRenamePartrevert () {
      let seats = JSON.parse(JSON.stringify(this.getSelectedSeats()))
      // 按行分组
      let groupSeats = groupby(seats, i => i.y)

      // console.log(groupSeats)

      // 所有行号
      let rowKeys = Object.keys(groupSeats)

      // 排序
      rowKeys.sort((a, b) => {
        return Number(a) - Number(b)
      })

      rowKeys.forEach((rowkey, rowIndex) => {
        let row = groupSeats[rowkey]

        // 按x排序
        row.sort((a, b) => {
          return a.x - b.x
        })

        // console.log(rowkey, row, rowIndex)
        console.log('%c [ row ]-277', 'font-size:13px; background:pink; color:#bf2c9f;', row.length)

        row.forEach((item, index) => {
          item.name = (row.length - index + '').padStart(2, '0')
          item.row_tag = (rowIndex + 1 + '')
          console.log('%c [ item ]-277', 'font-size:13px; background:pink; color:#bf2c9f;', item)
        })
      })

      updateSeat({
        seats
      }).then(res => {
        this.$message.success('操作成功')

        this.getSeatList()
      })
    },
    // 部分重命名
    handleRenamePart () {
      let seats = JSON.parse(JSON.stringify(this.getSelectedSeats()))
      // 按行分组
      let groupSeats = groupby(seats, i => i.y)

      // console.log(groupSeats)

      // 所有行号
      let rowKeys = Object.keys(groupSeats)

      // 排序
      rowKeys.sort((a, b) => {
        return Number(a) - Number(b)
      })
      let rowIndex_ = 0
      rowKeys.forEach((rowkey, rowIndex) => {
        let row = groupSeats[rowkey]
        rowIndex_++
        // 按x排序
        row.sort((a, b) => {
          return a.x - b.x
        })

        // console.log(rowkey, row, rowIndex)
        console.log('%c [ row ]-277', 'font-size:13px; background:pink; color:#bf2c9f;', row.length)

        row.forEach((item, index) => {
          item.name = (index + 1 + '').padStart(2, '0')
          item.row_tag = (rowIndex_ + '')
          console.log('%c [ item ]-277', 'font-size:13px; background:pink; color:#bf2c9f;', item)
        })
      })

      updateSeat({
        seats
      }).then(res => {
        this.$message.success('操作成功')

        this.getSeatList()
      })
    },
    // 批量重命名
    handleRenameAll () {
      let seats = JSON.parse(JSON.stringify(this.seatsData))
      // 按行分组
      let groupSeats = groupby(seats, i => i.y)

      // console.log(groupSeats)

      // 所有行号
      let rowKeys = Object.keys(groupSeats)

      // 排序
      rowKeys.sort((a, b) => {
        return Number(a) - Number(b)
      })

      rowKeys.forEach((rowkey, rowIndex) => {
        let row = groupSeats[rowkey]

        // 按x排序
        row.sort((a, b) => {
          return a.x - b.x
        })

        // console.log(rowkey, row, rowIndex)

        row.forEach((item, index) => {
          item.name = (index + 1 + '').padStart(2, '0')
          item.row_tag = (rowIndex + 1 + '')
        })
      })

      updateSeat({
        seats
      }).then(res => {
        this.$message.success('操作成功')

        this.getSeatList()
      })
    },
    handleDeleteSeat () {
      this.selected = this.getSelectedSeats()

      // 可删除的座位
      this.selected = this.selected.filter(item => {
        return item.id
      })

      if (!this.selected.length) return this.$message.error('请选择要删除的座位')

      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSeat({
          idList: this.selected.map(i => i.id)
        }).then(res => {
          this.$message.success('删除成功')
          this.getSeatList()
        })
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.seatEditorWrap {
  display: flex; flex-direction: column;  flex: 1; overflow: hidden;
}

.note{
 font-size: 12px; margin-left: 50px; color: #666;
 i{
   display: inline-block; background: #eee; border: 1px solid #ddd; color: red; padding: 3px; margin: 0 5px; font-style: normal;
 }
}

.main {
  flex: 1;
}

.topBar{
  position: relative;

  .seatNum{
    position: absolute; right: 0; top: 0; line-height: 30px; padding: 10px;
  }
  b {
    color: red;
  }
}

.areaTag {
  padding: 10px; text-align: center;background: rgb(225, 235, 248);border-bottom: 1px solid #ddd;
  height: 30px; line-height: 30px;
  li {
    display: inline-block; margin-right: 16px; user-select: none; cursor: pointer;
  }
  i {
    display: inline-block;  width: 10px;height: 10px;
  }
}

.controls{
   padding: 10px; text-align: center; background: rgb(225, 235, 248); border-top: 1px solid #ddd;
}
</style>

<style lang="scss">
.el-dialog.is-fullscreen {
  display: flex; height: 100%; margin-top: 0; flex-direction: column;
  .el-dialog__body {
    display: flex;  width: 100%; color: #000; flex: 1;
  }
}

</style>
