<template>
  <div class="form-wrap">
    <el-form
      class="search-box"
      ref="form"
      :model="form"
      :inline="true"
      label-width="100px"
    >
      <el-form-item
        label="查看日期"
      >
        <el-date-picker
          v-model="dateList"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder=""
          end-placeholder=""
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="">
        <span style="white-space:nowrap;color:#F5A623">
          时间跨度最多14天</span>
      </el-form-item>
      <div class="btn-wrap">
        <el-button
          type="primary"
          @click="getList"
        >
          查询
        </el-button>
        <el-button
          @click="reset()"
        >
          清除
        </el-button>
        <el-button
          @click="$refs.chartInfo.show(null,'add')"
        >
          新增
        </el-button>
      </div>
    </el-form>

    <div class="table-box">
      <div class="block-title">
        座位表管理
      </div>
      <el-table
        ref="multipleTable"
        border
        stripe
        tooltip-effect="dark"
        v-loading="loading"
        :data="tableData">
        <el-table-column
          prop="id"
          label="编号"
          width="80"
        >
        </el-table-column>
        <el-table-column
          prop="name"
          label="剧厅"
        >
        </el-table-column>
        <el-table-column
          prop="x"
          label="区域(行*列)"
        >
          <template slot-scope="scope">
            {{ scope.row.y }} * {{ scope.row.x }}
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
        >
          <template slot-scope="scope">
            {{ scope.row.createTime | formatTime }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
        >
          <template slot-scope="scope">
            <el-link
              type="primary"
              size="small"
              @click="$refs.chartInfo.show(scope.row,'edit')"
            >
              编辑
            </el-link>
            <el-link
              type="primary"
              size="small"
              @click="handelSelectChart(scope.row)"
            >
              编辑座位图
            </el-link>
            <el-link
              type="primary"
              size="small"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        background
        :current-page.sync="form.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="form.pageSize"
        @size-change="handleSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="getList()"
        :total="total">
      </el-pagination>
    </div>

    <!-- 座位图信息编辑 -->
    <seatChartInfoModal
      ref="chartInfo"
      @update="getList"></seatChartInfoModal>

    <SeatEditor ref="seatEditor"></SeatEditor>
  </div>
</template>

<script>
import { getSeatConfigList, deleteSeatConfig, getSeatArea, addSeat, getSeatList, deleteSeat, updateSeat } from '@/api/seat'
import moment from 'moment'
import seatChartInfoModal from '../../seatSetting/seatChartInfoModal'
import SeatEditor from '../../seatSetting/SeatEditor/index.vue'
import groupby from 'lodash/groupBy'

export default {
  created () {
    this.getList()
  },
  components: {
    SeatEditor,
    seatChartInfoModal
  },
  data () {
    return {
      dateList: [],
      form: {
        pageNum: 1,
        pageSize: 10,
        keyWords1: '',
        keyWords2: '',
        keyWords3: ''
      },
      total: 1,
      loading: false,
      tableData: [],
      chart: null,
      areaList: [],
      selectedChart: 0,
      selectedArea: 0,
      selectedBlankSeats: [],
      existSeats: []
    }
  },
  methods: {
    handleSizeChange (size) {
      this.form.pageSize = size
      this.getList()
    },
    getList () {
      this.loading = true
      let params = JSON.parse(JSON.stringify(this.form))
      if (this.dateList === null || this.dateList.length !== 2) {
        params.keyWords1 = ''
        params.keyWords2 = ''
      } else {
        params.keyWords1 = moment(this.dateList[0]).format('YYYY-MM-DD')
        params.keyWords2 = moment(this.dateList[1]).format('YYYY-MM-DD')
      }
      getSeatConfigList(params).then(res => {
        this.tableData = res.list
        this.total = res.total
      }).finally(() => {
        this.loading = false
      })
    },
    reset () {
      this.$refs.form.resetFields()
      this.dateList = []
    },
    handleDelete (id) {
      this.$confirm('确认删除吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSeatConfig(id).then(res => {
          this.$message.success('删除成功')
          this.getList()
        })
      }).catch(() => {})
    },
    handelSelectChart (chart) {
      this.$refs.seatEditor.show(chart)
    },
    async getAreaList () {
      this.colorMap = {}

      await getSeatArea({ keyWords1: this.selectedChart }).then(res => {
        this.areaList = res.list
        this.selectedArea = (this.areaList[0] && this.areaList[0].id) || 0

        this.areaList.forEach((item, index) => {
          this.colorMap[item.id] = this.colorPalette[index]
        })
      })

      this.getSeatList()
    },

    getSeatList () {
      getSeatList({ keyWords1: this.selectedChart, pageSize: -1, pageNum: 0 }).then(res => {
        this.existSeats = res.list.map(item => {
          item.fill = this.colorMap[item.area_id] || 'gray'
          return item
        })
      })
    },

    handleAddToArea () {
      if (!this.selectedArea) return this.$message.error('请选择区域')

      const selectedSeats = this.$refs.seatChart.getSelectedSeat()

      addSeat({
        config_id: this.selectedChart,
        area_id: this.selectedArea,
        seatList: selectedSeats
      }).then(res => {
        this.$message.success('添加成功')
        this.getSeatList()
      })
    },
    handleDeleteSeat () {
      let selectedSeats = this.$refs.seatChart.getSelectedSeat()

      selectedSeats = selectedSeats.filter(item => {
        return item.area_id
      })

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

      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSeat({
          idList: selectedSeats.map(i => i.id)
        }).then(res => {
          this.$message.success('删除成功')
          this.getSeatList()
        })
      }).catch(() => {})
    },
    // 批量重命名
    handleRenameAll () {
      let seats = JSON.parse(JSON.stringify(this.existSeats))
      // 按行分组
      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 + '')
          item.row_tag = (rowIndex + 1 + '')
        })
      })

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

        this.getSeatList()
      })
    }
  },
  watch: {
    selectedArea (val) {
      if (val) {

      }
    }
  }

}
</script>

<style lang="scss" scoped>
.form-wrap {
  .el-input,.el-select,.el-date-editor,.el-date-editor.el-input,.el-input-number {
    width: 300px;
  }
}

</style>
