<template>
  <div class="page">
    <div class="main">
      <div class="selectedWrap">
        <div class="top-title">
          已选择座位 [ {{ selectedSeat.length }} ]
        </div>
        <div class="content">
          <div
            class="blankItem"
            v-if="!groupSeats.length">
            未选择座位
          </div>

          <ul class="list areaList">
            <li
              v-for="(item,index) in groupSeats"
              :key="index">
              <div class="seatInfo">
                <el-tag
                  :color="colorMap[item.groupId]"
                  style="color:#fff">
                  {{ areaMap[item.groupId] && areaMap[item.groupId].name }} [ {{ item.groupSeatsName.length }} ]
                </el-tag> :{{ item.groupSeatsName.join('、') }}
              </div>

              <div style="width:215px; margin-left:10px">
                <el-select
                  v-model="item.ticketTypeId"
                  @change="handleTicketTypeChange($event,item,index)">
                  <el-option
                    v-for="(i,tidx) in item.priceMap"
                    :key="'a'+tidx"
                    :label="i.ticketTypeName"
                    :value="i.ticketTypeId"></el-option>
                </el-select>
              </div>
            </li>
          </ul>
        </div>
      </div>

      <div v-if="chart">
        <ul
          class="areaTag"
          v-if="areaList.length">
          <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>
        <!-- <span class="note">操作提示：使用<i>鼠标框选</i>快速选择座位<i>（座位选择）</i>或空位<i>（空位选择）</i>；按住<i>空格</i>按下鼠标进行舞台位置移动；鼠标<i>滚轮</i>控制舞台缩放</span> -->
      </div>
      <div
        class="seatWrap"
        v-loading="chartLoading">
        <SeatChart
          v-model="selectedSeat"
          ref="seatChart"
          @updateSeat="getBatchSeat"
          v-if="chart"
          :area-list="areaList"
          :data="seatsData"
          :batch-condig-id="currentBatch"
          :batch-date="date"
          :rows="chart.y"
          :columns="chart.x"></SeatChart>

        <div
          class="blankWrap"
          v-else>
          <div class="inner">
            <template v-if="!batchList.length">
              <div style="margin-bottom:10px">
                当前节目暂无场次可选
              </div>
              <el-button
                type="primary"
                @click="goPerformBatch">
                立即排片
              </el-button>
            </template>

            <template v-else>
              <div style="margin-bottom:10px">
                暂无座位表
              </div>
              <el-button
                type="primary"
                @click="goBind">
                立即绑定
              </el-button>
            </template>
          </div>
        </div>
      </div>
    </div>

    <div class="side">
      <el-card v-loading="performListLoading">
        <div
          class="top-title"
          slot="header">
          节目选择
          <div>
            <el-date-picker
              style="width:140px"
              :clearable="false"
              :picker-options="pickerOptions"
              @change="handleDateChange"
              v-model="date"
              type="date"
              placeholder="选择日期时间">
            </el-date-picker>

            <el-button
              style="margin:0 0 0 10px"
              type="primary"
              size="small"
              @click="getPerformList">
              更新
            </el-button>
          </div>
        </div>

        <div
          class="blankItem"
          v-if="!performList.length">
          <el-button
            type="primary"
            @click="$router.push({name:'performConfig'})">
            管理节目
          </el-button>
        </div>

        <ul
          class="list"
          v-else>
          <li
            :class="{active:item.id===currentPerform}"
            @click="handlePerformClick(item)"
            v-for="(item,index) in performList"
            :key="index">
            {{ item.name }}
          </li>
        </ul>
      </el-card>

      <el-card
        header="场次选择"
        v-loading="batchListLoading">
        <div
          class="top-title"
          slot="header">
          场次选择
        </div>
        <div v-if="!batchList.length">
          暂无场次
        </div>
        <ul
          class="list"
          v-else>
          <li
            :class="{active:item.batch_config_id===currentBatch}"
            @click="handleBatchClick(item)"
            v-for="(item,index) in batchList"
            :key="index">
            {{ item.name }}
          </li>
        </ul>
      </el-card>
      <el-card
        v-if="is_auto_assign_seat.configValue==='1'"
        header="区域选择"
        v-loading="batchListLoading">
        <div
          class="top-title"
          slot="header">
          区域选择
        </div>
        <div v-if="!areaList.length">
          暂无区域
        </div>
        <ul
          class="list"
          v-else>
          <li
            :class="{active:item.id===currentArea}"
            @click="handleAreaClick(item)"
            v-for="(item,index) in areaList"
            :key="index">
            {{ `${item.name}  共${item.totalSeat} 已售${item.usedSeat} 剩余${item.leftSeat} 冻结${item.lockedSeat}` }}
          </li>
        </ul>
        <div
          v-if="currentTicket.ticketTypeName"
          style="margin:10px 0">
          门票数量: <el-input-number
            v-model="currentTicketNum"
            :precision="0"
            :min="1"></el-input-number>
        </div>
        <div class="btnWrap">
          <el-button
            :disabled="!currentTicket.ticketTypeName||selectedSeat.length!==0"
            type="primary"
            @click="handleSubmit(false)">
            提交区域选择
          </el-button>
        </div>
      </el-card>
      <div
        class="btnWrap"
      >
        <el-button
          :disabled="selectedSeat.length===0"
          type="primary"
          @click="handleSubmit(true)">
          提交座位选择
        </el-button>
      </div>
    </div>

    <InfoModalMazu
      @update="getBatchSeat"
      ref="infoModalmazu"
      :price-plan="pricePlan"
      :selected-seat="selectedSeat"></InfoModalMazu>

    <InfoModal
      @update="getBatchSeat"
      ref="infoModal"
      :price-plan="pricePlan"
      :selected-seat="selectedSeat"></InfoModal>
  </div>
</template>

<script>
import { list, getBatchByPerform } from '@/api/perform'
import { getTicketPricePlanList } from '@/api/ticketPricePlan'
import { getBatchSeat } from '@/api/batch'
import moment from 'moment'
import SeatChart from '@/components/SeatChart/ChartOnlyRead'
import groupBy from 'lodash/groupBy'
import InfoModalMazu from './theaterSale/InfoModalMazu'
import InfoModal from './theaterSale/InfoModal'

import { getSystemConfigList } from '@/api/systemConfig'

export default {
  async created () {
    this.$localStore.delete('batch_config_id')
    this.$localStore.delete('perform_id')
    this.getPerformList()
    this.getTicketPricePlanList()
    const res = await getSystemConfigList()
    this.is_auto_assign_seat = res.list.find(v => v.configKey === 'is_auto_assign_seat')
  },
  components: {
    SeatChart,
    InfoModalMazu,
    InfoModal
  },
  data () {
    return {
      is_auto_assign_seat: '0',
      date: new Date(moment().startOf('day').valueOf()),
      areaNameMap: {},
      priceMap: {},
      currentPerform: 0,
      currentBatch: 0,
      currentArea: 0,
      currentTicket: {},
      currentTicketNum: 1,
      performListLoading: false,
      chart: null,
      selectedSeat: [],
      areaList: [],
      groupSeats: [],
      chartLoading: false,
      seatsData: [],
      pricePlan: [],
      performList: [],
      batchListLoading: false,
      batchList: [],
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '明天',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }]
        // disabledDate (time) {
        //   let startTime = moment().format('YYYY-MM-DD') + ' 00:00:00'
        //   return moment(time).isBefore(startTime)
        // }
      }
    }
  },
  methods: {
    handleTicketTypeChange (e, item) {
      // 批量修改座位票种
      item.seats.forEach(i => { i.ticketTypeId = e })
    },
    getGroupSeats () {
      const result = []
      if (this.selectedSeat.length) {
        const groupData = groupBy(this.selectedSeat, item => item.area_id)

        for (let key in groupData) {
          const ticketTypeId = this.priceMap[key] && this.priceMap[key].length && this.priceMap[key][0].ticketTypeId

          groupData[key].forEach(i => { i.ticketTypeId = ticketTypeId })

          const item = {
            groupId: key,
            ticketTypeId: ticketTypeId,
            seats: groupData[key],
            groupSeatsName: groupData[key].map(i => {
              return i.seatName || (i.row_tag + '排' + i.name + '座')
            }),
            priceMap: this.priceMap[key]
          }

          result.push(item)
        }
      }

      this.groupSeats = result
    },
    handleDateChange (data) {
      this.getPerformList()
    },
    handlePerformClick (item) {
      this.currentPerform = item.id

      this.getBatchByPerform()
    },

    handleBatchClick (item) {
      this.currentBatch = item.batch_config_id
      this.getBatchSeat()
    },
    handleAreaClick (item) {
      let areaSeats = this.seatsData.filter(v => v.areaName === item.name)
      if (areaSeats.every(v => v.noprice)) {
        return this.$message.error('当前区域无票可售')
      }
      this.currentArea = item.id
      this.currentTicket = this.priceMap[item.id][0] || {}
    },
    // handleBatchChange (e) {
    //   this.currentBatch = e
    //   this.getBatchSeat()
    // },
    getTicketPricePlanList () {
      getTicketPricePlanList({ keyWords1: 1, pageNum: 0, pageSize: -1 }).then(res => {
        // this.pricePlan={}
        this.pricePlan = res.list
      })
    },
    getPerformList () {
      this.performListLoading = true

      list({ keyWords1: 1, keyWords2: moment(this.date).format('YYYY-MM-DD'), pageNum: 0, pageSize: -1 }).then(res => {
        this.performList = res.list

        if (this.performList.length) {
          let isHavePerformId = this.performList.find(i => i.id === this.$localStore.get('perform_id'))
          this.currentPerform = this.$localStore.get('perform_id') && isHavePerformId ? isHavePerformId.id : this.performList[0].id
          this.getBatchByPerform()
        } else {
          this.currentPerform = 0
          this.batchList = []
          this.chart = null
          this.seatsData = []
          this.areaList = []
        }
      }).finally(() => {
        this.performListLoading = false
      })
    },
    getBatchByPerform (id) {
      if (!this.currentPerform) return

      const date = moment(this.date).format('YYYY-MM-DD')

      this.batchListLoading = true

      getBatchByPerform({ keyWords1: date, keyWords2: this.currentPerform }).then(res => {
        this.batchList = res.list.sort((a, b) => {
          return moment(a.startTime, 'HH:mm:ss').isAfter(moment(b.startTime, 'HH:mm:ss')) ? 1 : -1
        })
        //  .filter(item => {
        //           if ((date !== moment().format('YYYY-MM-DD') || item.startTime > moment().format('HH:mm:ss')) && item.if_valid) {
        //             return item
        //           }
        //         })
        if (this.batchList.length) {
          let isHaveBatchId = this.batchList.find(i => i.batch_config_id === this.$localStore.get('batch_config_id'))
          this.currentBatch = this.$localStore.get('batch_config_id') && isHaveBatchId ? isHaveBatchId.batch_config_id : this.batchList[0].batch_config_id
          this.getBatchSeat()
        } else {
          // 重置数据
          this.currentBatch = 0
          this.chart = null
          this.seatsData = []
          this.areaList = []
        }
      }).finally(() => {
        this.batchListLoading = false
      })
    },
    getBatchSeat () {
      this.chartLoading = true

      getBatchSeat({ batch_config_id: this.currentBatch, batch_date: moment(this.date).format('YYYY-MM-DD') }).then(res => {
        this.chart = res

        // 赋值并着色
        this.colorMap = {}
        this.areaMap = {}
        this.priceMap = {}

        res.area_list.forEach((item, index) => {
          item.totalSeat = 0
          item.leftSeat = 0
          item.usedSeat = 0
          item.lockedSeat = 0
          this.colorMap[item.id] = this.colorPalette[index]
          this.areaMap[item.id] = item
          item.color = this.colorPalette[index]
        })

        this.areaList = res.area_list

        this.priceList = res.price_list
        console.log('%c [ this.priceList ]-445', 'font-size:13px; background:pink; color:#bf2c9f;', this.priceList)

        res.price_list.forEach(item => {
          this.priceMap[item.area_id] = item.ticket_type_list
        })

        this.seatsData = res.list.map(item => {
          this.areaList.forEach((e, index) => {
            if (item.area_id === this.areaList[index].id) {
              this.areaList[index].totalSeat += 1
              if (item.status === 1) {
                this.areaList[index].leftSeat += 1
              } else if (item.status === 0) {
                this.areaList[index].usedSeat += 1
              } else if (item.status === 2) {
                this.areaList[index].lockedSeat += 1
              }
            }
          })
          // 未绑定票种价格
          item.noprice = this.priceMap[item.area_id] && this.priceMap[item.area_id].length === 0
          // 未绑定票种价格和已订都设置为灰色
          // item.fill = (item.status && !item.noprice) ? (this.colorMap[item.area_id] || 'gray') : 'rgba(0,0,0,0.2)'
          item.fill = item.status === 2 ? 'rgb(17, 255, 255)' : item.status && !item.noprice ? (this.colorMap[item.area_id] || 'gray') : 'rgba(0,0,0,0.2)'
          item.areaName = this.areaMap[item.area_id] && this.areaMap[item.area_id].name
          return item
        })
      }).finally(() => {
        this.chartLoading = false
      })
    },
    goPerformBatch () {
      this.$router.push({ name: 'performBatch' })
    },
    goBind () {
      const currentBatch = this.batchList.find(i => i.batch_config_id === this.currentBatch)

      this.$router.push({ name: 'batchConfig_theatre', params: { batchName: currentBatch && currentBatch.name } })
    },
    handleSubmit (assignSeat) {
      if (!this.currentBatch) {
        return this.$message.error('无有效场次')
      }

      // if (!this.selectedSeat.length) {
      //   return this.$message.error('请选择座位')
      // }

      const currentBatch = this.batchList.find(i => i.batch_config_id === this.currentBatch)

      const emptyPriceSeat = this.selectedSeat.find(item => {
        return this.priceMap[item.area_id].length === 0
      })

      // 当前座位区域不存在票种价格信息
      if (emptyPriceSeat) {
        this.$confirm(`当前场次【${emptyPriceSeat.areaName}】未绑定票种，是否去绑定？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.goBind()
        }).catch(() => {})

        return
      }
      if (assignSeat) {
        // 自选座位
        this.$refs.infoModal.show({
          batchInfo: currentBatch,
          performInfo: this.performList.find(i => i.id === this.currentPerform),
          priceMap: this.priceMap,
          areaMap: this.areaMap,
          date: this.date
        },
        this.currentArea,
        this.currentTicket,
        this.currentTicketNum)
      } else {
        // 显示订单信息弹窗
        this.$refs.infoModalmazu.show({
          batchInfo: currentBatch,
          performInfo: this.performList.find(i => i.id === this.currentPerform),
          priceMap: this.priceMap,
          areaMap: this.areaMap,
          date: this.date
        },
        this.currentArea,
        this.currentTicket,
        this.currentTicketNum
        )
      }
    }
  },
  watch: {
    selectedSeat (val) {
      this.getGroupSeats()
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  position: absolute; top: 0; left: 0;display: flex; width: 100%; height: 100%;background: #ebe9e9;
}

.top-title {
  display: flex;  padding: 10px 10px; font-size: 16px;  line-height: 1.4;color: $blue; background: rgb(238, 238, 238); justify-content: space-between; align-items: center;
  .right-btn {
    display: flex;
  }
}

.main {
  flex: 1; position: relative; flex-direction: column; display: flex; margin-right: 5px;
  .seatWrap{
    flex:1
  }
}

.side {
  width: 300px;
  ::v-deep .el-card__header {
    padding: 0;
  }
  overflow: auto;
}

.list {
  li {
    padding: 10px 20px; margin-top: -1px; cursor: pointer; border-bottom: 1px solid #ddd; font-size: 14px;
  }
  li:last-child {
    border: none;
  }
  li:hover {
    background: rgba(247,206,96,.3);
  }
  li.active {
    background: rgb(247,206,96);
  }
}

.list.areaList{
  li{
    display: flex; justify-content: space-between; align-items: center;
  }
  .seatInfo{
    flex:1
  }
}

.el-card +.el-card{
  margin-top: 10px;
}
.note{
 font-size: 12px;  color: #666;display: flex;justify-content: center;align-items: center;height: 25px;
 i{
   display: inline-block; background: #eee; border: 1px solid #ddd; color: red; padding: 3px; margin: 0 5px; font-style: normal;
 }
}

.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;
  }
}

.selectedWrap{
  height: 150px; background: #fff; display: flex; flex-direction: column;
  .content{
    flex:1; overflow: auto;
  }
}

.btnWrap{
  padding: 10px; text-align: center;
}

.blankWrap{
  width: 100%; height: 100%; display: flex; justify-content: center; align-items: center;  color: #666; background:#fff url('./theaterSale/no_data.jpg') center center no-repeat; background-size: 550px;
  .inner{
    text-align: center;
  }
}

.blankItem{
  text-align: center; padding: 20px; color: #666;
}
</style>
