<template>
  <div class="form-wrap">
    <el-form
      class="search-box"
      ref="form"
      :model="form"
      :inline="true"
      label-width="100px"
    >
      <el-form-item
        label="日期范围"
        prop="date"
      >
        <el-date-picker
          :clearable="false"
          style="width:220px"
          @change="handleDateChange"
          v-model="dateRange"
          :picker-options="pickerOptions"
          type="datetimerange"
          placeholder="选择日期时间"
          :default-time="['00:00:00', '23:59:59']">
        </el-date-picker>
      </el-form-item>

      <el-form-item
        label="场次列表"
        prop="keyList1"
      >
        <el-select
          collapse-tags
          v-model="form.keyList1"
          multiple>
          <el-option
            v-for="item in performbatchList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <div class="btn-wrap">
        <el-button
          type="primary"
          @click="getList"
        >
          查询
        </el-button>
      </div>
    </el-form>

    <div class="table-box">
      <div class="block-title">
        场次列表
        <el-button
          @click="clearSelection">
          清空选择
        </el-button>
        <el-button
          type="primary"
          @click="batchPerform"
          style="margin-right:10px">
          排片
        </el-button>
        <el-button
          type="primary"
          @click="$refs.uniteBatch.show()"
          style="margin-right:10px">
          统一排片
        </el-button>
      </div>
      <el-table
        v-if="tableMaxHeight"
        :max-height="tableMaxHeight"
        border
        stripe
        v-loading="loading"
        :data="tableData">
        <el-table-column
          prop="batchConfig"
          label="场次信息"
          width="160"
          fixed="left"
        >
          <template slot-scope="scope">
            <ul>
              <li>
                <b>场次名称：</b>{{ scope.row.batchConfig.name }}
              </li>
              <li>
                <b>开始时间：</b>{{ scope.row.batchConfig.startTime }}
              </li>
              <li>
                <b>场次时长：</b>{{ scope.row.batchConfig.duration }}
              </li>
            </ul>
          </template>
        </el-table-column>

        <el-table-column
          width="90"
          height="100"
          v-for="(item,index) in dateArray"
          :key="index"
          :label="item + getDayOfWeek(item)"
          center
          class-name="item-wrap"
        >
          <template slot-scope="scope">
            <div
              @click="currentBatch({ ...scope.row.batchPerformList[index], batch_date: item, batchConfig: scope.row.batchConfig })"
              :class="{item:true,item_tag:scope.row.batchPerformList[index].selectTag}"
              v-if="scope.row.batchPerformList[index]">
              <span class="num">
                {{ scope.row.batchPerformList[index].performName }}
              </span>
            </div>
            <div
              class="item_close"
              v-if="!scope.row.batchPerformList[index]">
              <span class="num">
                未开放
              </span>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <Dialog
      ref="dialog"
      @update="getList"></Dialog>

    <UniteBatch
      ref="uniteBatch"
      @update="getList"
      :perform-list="performList"
      :performbatch-list="performbatchList"></UniteBatch>
  </div>
</template>

<script>
import Dialog from './Dialog'
import { getBatchPerformMatrix, list } from '@/api/perform'
import { getBatchConfigList } from '@/api/batch'
import UniteBatch from './UniteBatch'
import moment from 'moment'

let min = ''
let max = ''

export default {
  computed: {
    dateArray () {
      let diff = this.dateRange[1].getTime() - this.dateRange[0].getTime()
      let days = Math.round(diff / (24 * 60 * 60 * 1000))

      let dayArr = []
      for (let i = 0; i < days; i++) {
        dayArr.push(moment(this.dateRange[0]).add(i, 'day').format('YYYY-MM-DD'))
      }
      return dayArr
    }
  },
  components: {
    Dialog,
    UniteBatch
  },
  data () {
    return {
      loading: false,
      dateRange: [new Date(moment().startOf('day').valueOf()), new Date(moment().endOf('day').add(15, 'day').valueOf())],
      form: {
        keyWords1: '2020-02-27',
        keyWords2: '2020-03-01'
      },
      tableData: [],
      batchList: [],
      performList: [],
      performbatchList: [],
      tableMaxHeight: 0,
      pickerOptions: {
        disabledDate (time) {
          if (!min || !max) {
            return false
          }
          return time.getTime() >= max || time.getTime() <= min
        },
        onPick ({ maxDate, minDate }) {
          // 设置最大和最小可选择范围，14天
          max = minDate.getTime() + 14 * 24 * 60 * 60 * 1000
          min = minDate.getTime() - 14 * 24 * 60 * 60 * 1000

          if (maxDate && minDate) {
            max = ''
            min = ''
          }
        }
      }
    }
  },
  created () {
    console.log(moment().startOf('day').valueOf())
    getBatchConfigList({ pageSize: -1, pageNum: 0 }).then(res => {
      this.performbatchList = res.list
    })
    this.getList()

    this.getPerformList()
  },
  mounted () {
    this.setTableHeight()
    window.addEventListener('resize', this.setTableHeight)
  },
  methods: {
    // 清除选择
    clearSelection () {
      this.getList()
    },
    // 选择日期与场次
    currentBatch (e) {
      let newdata = JSON.parse(JSON.stringify(this.tableData))
      for (const i of newdata) {
        if (i.batchConfig.id === e.batchConfig.id) {
          for (const j of i.batchPerformList) {
            if (j && j.batch_date === e.batch_date) {
              j.selectTag = !j.selectTag
            }
          }
        }
      }
      this.tableData = newdata
      let isHave = this.batchList.some(item => item.batch_config_id === e.batchConfig.id && item.batch_date === e.batch_date)
      if (isHave) {
        this.batchList.filter((item, index) => {
          if (item.batch_config_id === e.batchConfig.id && item.batch_date === e.batch_date) {
            this.batchList.splice(index, 1)
          }
        })
      } else {
        this.batchList.push({ 'batch_config_id': e.batchConfig.id, 'batch_date': e.batch_date })
      }
    },
    getPerformList () {
      /* 经测试，参数传{}，接口返回会自动分页；需要传{ pageSize: 999 }才会让它不分页。Path: 剧院排片->统一排片 */
      list({ pageSize: 999 }).then(res => {
        this.performList = res.list
      })
    },
    // 排片按钮
    batchPerform () {
      if (this.batchList.length) {
        this.$refs.dialog.show(this.batchList)
      } else {
        this.$message.error('请先选取场次')
      }
    },
    getList () {
      this.batchList = []
      this.loading = true
      this.form.keyWords1 = moment(this.dateRange[0]).format('YYYY-MM-DD')
      this.form.keyWords2 = moment(this.dateRange[1]).format('YYYY-MM-DD')
      getBatchPerformMatrix(this.form).then(res => {
        this.tableData = res.list
        console.log('this.tableData', this.tableData)
        for (const i of this.tableData) {
          for (const j of i.batchPerformList) {
            if (j) {
              j.selectTag = false
            }
          }
        }
      }).finally(() => {
        this.loading = false
      })
    },
    setTableHeight () {
      let wrap = document.querySelector('.app-main').getBoundingClientRect()
      // let table = this.$refs['table-wrap'].getBoundingClientRect()
      this.tableMaxHeight = wrap.height - 50
    },
    handleDateChange (e) {
      this.getList()
    },
    handleEdit (data) {
    },
    // 获取时间的星期
    getDayOfWeek (theDate) {
      let dayOfWeek = new Date(theDate).getDay()
      switch (dayOfWeek) {
        case 0:
          dayOfWeek = '周日'
          break
        case 1:
          dayOfWeek = '周一'
          break
        case 2:
          dayOfWeek = '周二'
          break
        case 3:
          dayOfWeek = '周三'
          break
        case 4:
          dayOfWeek = '周四'
          break
        case 5:
          dayOfWeek = '周五'
          break
        case 6:
          dayOfWeek = '周六'
          break
        default:
          break
      }
      return dayOfWeek
    }
  }
}
</script>

<style lang="scss" scoped>
.el-table {
  ::v-deep .item-wrap {
    position: relative; overflow: hidden;

    .item {
   cursor:pointer;position: absolute; top: 0;left: 0;display: flex; width: 100%;height: 100%; flex-direction: column;  align-items: center; justify-content: center;
      .num {
        font-size: 14px;  font-weight: bold; color: $blue;
          overflow:hidden;
  display:-webkit-box;
  text-overflow:ellipsis;
  -webkit-line-clamp:2;
  -webkit-box-orient:vertical;
  white-space:normal;
      }
    }
    .item_tag{
      // border: 3px solid rgb(74,144,226);
      background: #afdfe4;
    }
    .item_close{
      position: absolute; top: 0;left: 0;display: flex; width: 100%;height: 100%; flex-direction: column;  align-items: center; justify-content: center;
            .num {
        font-size: 14px;  font-weight: bold; color: gray;;
      }
    }

    .control-btn {
      position: absolute; bottom: 0;left: 0;width: 100%; background: rgba(49, 77, 138, 0.2);transition: all .3s; transform: translateY(40px); padding: 5px 0; text-align: center;
      ::v-deep .el-button + .el-button {
        margin-left:5px;
      }
    }

    .status-icon {
      position: absolute; top: 5px; right: 5px;width: 10px; height: 10px;border-radius: 50%;
      &.active {
        background: rgb(197, 253, 183); border: 1px solid rgb(71, 185, 43);
      }
      &.inactive {
        background: rgb(184, 184, 184); border: 1px solid rgb(121, 121, 121);
      }
    }
  }

  ::v-deep .el-table__row.hover-row td {
    background: hsla(55, 92%, 75%, .2);
  }
}

</style>
