<template>
  <div
    class="boxWrap"
    id="boxWrap">
    <el-form
      class="search-box"
      inline>
      <div class="block-title">
        查询条件
      </div>
      <el-form-item
        label="售票员"
        prop="keyWords2"
      >
        <el-select v-model="form.keyWords2">
          <el-option
            label="全部"
            value=""></el-option>
          <el-option
            v-for="item in salesList"
            :key="item.id"
            :label="item.nickName"
            :value="item.nickName">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="景点选择"
        prop="keyWords3"
      >
        <el-select
          v-model="form.keyWords3"
          placeholder="请选择">
          <el-option
            value=""
            label="全部">
          </el-option>
          <el-option
            v-for="item in allScenicList"
            :key="item.id"
            :value="item.id"
            :label="item.name">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="售票时间">
        <el-date-picker
          type="datetime"
          v-model="form.startDate"
          placeholder="选择日期时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="至">
        <el-date-picker
          default-time="23:59:59"
          type="datetime"
          v-model="form.endDate"
          placeholder="选择日期时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="交班时间">
        <el-date-picker
          type="datetime"
          v-model="form.startDate1"
          placeholder="选择日期时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="至">
        <el-date-picker
          default-time="23:59:59"
          type="datetime"
          v-model="form.endDate1"
          placeholder="选择日期时间"
        ></el-date-picker>
      </el-form-item>
      <div class="btn-wrap">
        <el-button
          :disabled="loading"
          type="primary"
          @click="getData"
        >
          查询
        </el-button>
        <el-button
          :disabled="loading"
          type="primary"
          @click="reportExport">
          导出
        </el-button>
      </div>
    </el-form>
    <div
      class="table-box"
      id="table-box"
      style="margin-bottom:0"
      ref="table-wrap">
      <el-tabs v-model="activeName">
        <el-tab-pane
          label="售票员统计"
          name="售票员统计">
          <span slot="label">
            售票员统计
            <!-- <Tip msg="仅包含窗口的门票销售数据，不包含线上门票的销售数据。"></Tip> -->
          </span>
          <el-table
            border
            class="spanTable"
            v-loading="loading"
            v-if="tableMaxHeight"
            :max-height="tableMaxHeight"
            :data="tableData"
            :span-method="arraySpanMethod"
            :cell-class-name="handleCellStyle"
            :header-cell-class-name="handleCellStyle"
            :row-class-name="totalRowClassName"
            :row-click="(row, column, event)=>{console.log(row)}"
          >
            <!-- :row-class-name="totalRowClassName" -->
            <el-table-column
              prop="ticket_spot_name"
              label="售票点"
              min-width="100"
            >
            </el-table-column>
            <el-table-column
              prop="manager_name"
              label="售票员"
              min-width="100"
            ></el-table-column>
            <el-table-column
              v-if="1"
              prop="payChannel"
              label="支付方式"
              min-width="100"
            ></el-table-column>
            <el-table-column
              prop="ticketTypeName"
              label="票种"
            ></el-table-column>
            <el-table-column
              prop="memberTypeName"
              label="会员类型"
            ></el-table-column>
            <el-table-column
              prop="price"
              label="单价"
            ></el-table-column>
            <el-table-column
              prop="sum_count"
              label="销售数量"
            ></el-table-column>
            <el-table-column
              prop="sum_people"
              label="销售人数"
            ></el-table-column>
            <el-table-column
              prop="sum_price"
              label="销售金额"
            ></el-table-column>
            <el-table-column
              prop="cancel_count"
              label="退款数量"
            ></el-table-column>
            <el-table-column
              prop="cancel_people"
              label="退款人数"
            ></el-table-column>
            <el-table-column
              prop="cancelPrice"
              label="退款金额"
            ></el-table-column>
            <el-table-column
              prop="actual_count"
              label="实售数量"
            ></el-table-column>
            <el-table-column
              prop="actual_people"
              label="实售人数"
            ></el-table-column>
            <el-table-column
              prop="actual_price"
              label="实售金额"
            ></el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane
          label="财务汇总统计"
          name="财务汇总统计">
          <span slot="label">
            财务汇总统计
            <!-- <Tip msg="仅包含窗口的门票销售数据，不包含线上门票的销售数据。"></Tip> -->
          </span>
          <el-table
            border
            class="spanTable"
            v-loading="loading"
            v-if="tableMaxHeight"
            :max-height="tableMaxHeight"
            :data="financialData"
            :span-method="arraySpanMethod"
            :cell-class-name="handleCellStyle"
            :header-cell-class-name="handleCellStyle"
            :row-class-name="totalRowClassName"
            :row-click="(row, column, event)=>{console.log(row)}"
          >
            <!-- :row-class-name="totalRowClassName" -->
            <el-table-column
              prop="ticket_spot_name"
              label="售票点"
              min-width="100"
            >
            </el-table-column>
            <el-table-column
              prop="manager_name"
              label="售票员"
              min-width="100"
            ></el-table-column>
            <el-table-column
              prop="payChannel"
              label="支付方式"
              min-width="100"
            ></el-table-column>
            <el-table-column
              prop="ticketTypeName"
              label="票种"
            ></el-table-column>
            <el-table-column
              prop="memberTypeName"
              label="会员类型"
            ></el-table-column>
            <el-table-column
              prop="price"
              label="单价"
            ></el-table-column>
            <el-table-column
              prop="sum_count"
              label="销售数量"
            ></el-table-column>
            <el-table-column
              prop="sum_people"
              label="销售人数"
            ></el-table-column>
            <el-table-column
              prop="sum_price"
              label="销售金额"
            ></el-table-column>
            <el-table-column
              prop="cancel_count"
              label="退款数量"
            ></el-table-column>
            <el-table-column
              prop="cancel_people"
              label="退款人数"
            ></el-table-column>
            <el-table-column
              prop="cancelPrice"
              label="退款金额"
            ></el-table-column>
            <el-table-column
              prop="actual_count"
              label="实售数量"
            ></el-table-column>
            <el-table-column
              prop="actual_people"
              label="实售人数"
            ></el-table-column>
            <el-table-column
              prop="actual_price"
              label="实售金额"
            ></el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane
          label="收款统计"
          name="收款统计">
          <span slot="label">
            收款统计
            <Tip msg="仅包含窗口的门票和会员的销售收款数据。"></Tip>
          </span>
          <el-table
            stripe
            border
            v-if="tableMaxHeight"
            :max-height="tableMaxHeight"
            class="spanTable"
            v-loading="loading"
            :data="cashData"
            :span-method="cashSpanMethod"
            :row-class-name="totalRowClassName">
            <el-table-column
              label="售票点"
              prop="ticket_spot_name">
            </el-table-column>
            <el-table-column
              label="售票员"
              prop="manager_name">
            </el-table-column>
            <el-table-column
              v-for="channel in channelList"
              :key="channel"
              :label="channel"
              :prop="channel"></el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>
<script>
import { getHandOverBySpotTicketType } from '@/api/systemSetting/manager'
import { exportSaleStatisticsByTicketSpot } from '@/api/queryReport'
import Tip from '@/components/Tip'
import VueScrollTo from 'vue-scrollto'
import moment from 'moment'

export default {
  name: 'handOverStatistics',
  components: {
    Tip
  },
  computed: {
    salesList () {
      return this.$store.state.user.salesList
    },
    allScenicList () {
      return this.$store.state.app.scenicList
    }
  },
  data () {
    return {
      firstTimeIn: true,
      form: {
        startDate: new Date(moment().format('YYYY-MM-DD') + ' 00:00:00'),
        endDate: new Date(moment().format('YYYY-MM-DD') + ' 23:59:59'),
        startDate1: new Date(moment().format('YYYY-MM-DD') + ' 00:00:00'),
        endDate1: new Date(moment().format('YYYY-MM-DD') + ' 23:59:59'),
        keyWords2: '', // 售票员名称
        keyWords3: ''
      },
      spotStarts: [],
      sellerStarts: [],
      rowSpanArray: [],
      ticketTypeArray: [],
      tableData: [],
      financialData: [],
      cashData: [],
      activeName: '售票员统计',
      channelList: [],
      cashRules: [],
      loading: false,
      tableMaxHeight: 0
    }
  },
  created () {
    this.getData()
  },
  mounted () {
    this.setTableHeight()
    window.addEventListener('resize', this.setTableHeight)
  },
  methods: {
    totalRowClassName ({ row, rowIndex }) {
      if (row.ticket_spot_name === '总计') {
        return 'table-total-row'
      }

      if (row.manager_name === '售票点小计' && row.payChannel === '售票员小计' && row.ticketTypeName === '小计') {
        return 'table-total-row table-total-row1'
      }

      if (row.payChannel === '售票员小计' && row.ticketTypeName === '小计') {
        return 'table-total-row table-total-row2'
      }

      if (row.ticketTypeName === '小计') {
        return 'table-total-row table-total-row3'
      }
    },
    setTableHeight () {
      let wrap = document.querySelector('.app-main').getBoundingClientRect()
      // let table = this.$refs['table-wrap'].getBoundingClientRect()
      this.tableMaxHeight = wrap.height - 50
    },
    findAllIndex (input, method) {
      if (!Array.isArray(input)) return []
      let output = []
      for (let i = 0; i < input.length; i++) {
        let item = input[i]
        if (item && method(item)) {
          output.push(i)
        } else if (!item) {
          console.log(input)
        }
      }
      return output
    },

    getData () {
      this.loading = true
      this.colunmSpan0 = null
      getHandOverBySpotTicketType(this.form).then(res => {
        this.tableData = res.data.filter((item) => item.ticket_spot_name !== '总计')
        this.financialData = res.data.filter((item) => item.ticket_spot_name === '总计')
        this.cashData = res.cash_data
        this.channelList = res.pay_channel_list

        // 第一次进入页面不滚动
        if (this.firstTimeIn) {
          this.firstTimeIn = false
          return
        }
        this.$nextTick(() => {
          VueScrollTo.scrollTo('#table-box', 1000, { container: '.app-main .el-scrollbar__wrap' })
        })
      }).finally(() => {
        this.loading = false
      })
    },
    handleCellStyle ({ row, column, rowIndex, columnIndex }) {
      if (columnIndex > 5 && columnIndex <= 8) {
        if (columnIndex === 8) {
          return 'greenBg boldBorder'
        }
        return 'greenBg'
      }

      if (columnIndex > 8 && columnIndex <= 11) {
        if (columnIndex === 11) {
          return 'redBg boldBorder'
        }
        return 'redBg'
      }

      if (columnIndex > 11) {
        if (columnIndex === 11) {
          return 'blueBg boldBorder'
        }
        return 'blueBg'
      }

      if (columnIndex === 5) {
        return 'boldBorder'
      }
    },
    reportExport () {
      exportSaleStatisticsByTicketSpot(this.form).then(() => {
        this.$message.success('导出成功。')
        this.goToDownload()
      }, () => {
        this.$message.success('导出失败。')
      })
    },
    arraySpanMethod ({ row, column, rowIndex, columnIndex }) {
      // const isMember = this.tableData[rowIndex].hasOwnProperty('memberTypeName')

      if (!this.colunmSpan0) {
        this.colunmSpan0 = this.getSpanArrayByRepeat(this.tableData, 'ticket_spot_name')
      }

      let lastSpan = this.colunmSpan0[this.colunmSpan0.length - 1]

      if (columnIndex === 0) {
        if (rowIndex === lastSpan[0]) {
          return [lastSpan[1] - lastSpan[0] + 1, 2]
        }
        return this.getRowSpanByRepeat(this.colunmSpan0, rowIndex)
      }

      if (columnIndex === 1) {
        if (rowIndex >= lastSpan[0]) {
          return [0, 0]
        }
        return this.getRowSpan(this.tableData, ['payChannel', '售票员小计'], rowIndex, true)
      }

      if (columnIndex === 2) {
        if (this.tableData[rowIndex].payChannel === '售票员小计' && this.tableData[rowIndex].ticketTypeName === '小计') {
          return [1, 2]
        }
        return this.getRowSpan(this.tableData, ['ticketTypeName', '小计'], rowIndex, true)
      }

      if (columnIndex === 3) {
        if (this.tableData[rowIndex].payChannel === '售票员小计' && this.tableData[rowIndex].ticketTypeName === '小计') {
          return [0, 0]
        }
      }
      return [1, 1]
    },
    cashSpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === this.cashData.length - 1) return [1, 1]
      if (columnIndex === 0) {
        return this.getRowSpan(this.cashData, ['manager_name', '售票点小计'], rowIndex, true)
      }
    },
    getSpanArrayByRepeat (data, tag) {
      let indexArray = []
      data.forEach((item, index) => {
        if (index > 0) {
          if (item[tag] !== data[index - 1][tag]) {
            indexArray.push(index)
          }
        }
      })
      if (!indexArray.length) {
        indexArray = [data.length]
      }

      let rowSpanArray = indexArray.map((i, index) => {
        if (index === 0) {
          return [0, i - 1]
        } else {
          return [indexArray[index - 1], i - 1]
        }
      })
      if (indexArray.length > 0) {
        rowSpanArray.push([indexArray[indexArray.length - 1], data.length - 1])
      }
      return rowSpanArray
    },
    getRowSpanByRepeat (spanArray, rowIndex) {
      let span = spanArray.find(i => {
        return rowIndex >= i[0] && rowIndex <= i[1]
      })
      if (!span || (span[1] === span[0])) {
        return [1, 1]
      }

      if (rowIndex === span[0]) {
        return [span[1] - span[0] + 1, 1]
      } else {
        return [0, 0]
      }
    },
    /**
     * @tag 合并单元格标识数组，如[‘manager_name’,'售票点小计']
     * @rowIndex 行序号
     * @flag 是否合并边界
     */
    getRowSpan (data, tag, rowIndex, flag) {
      let totalIndex = data.map((item, index) => {
        if (item[tag[0]] === tag[1]) {
          return index
        } else {
          return null
        }
      }).filter(Boolean)

      let rowSpanArray = totalIndex.map((i, index) => {
        if (index === 0) {
          return [0, i]
        } else {
          return [totalIndex[index - 1] + 1, i]
        }
      })

      let span = rowSpanArray.find(i => {
        return rowIndex >= i[0] && rowIndex <= i[1]
      })

      if (!span) {
        return [1, 1]
      }

      if (rowIndex === span[0]) {
        return [span[1] - span[0] + (flag ? 1 : 0), 1]
      } else if (rowIndex === span[1]) {
        return flag ? [0, 0] : [1, 1]
      } else {
        return [0, 0]
      }
    }
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.setTableHeight)
  }
}
</script>
<style lang="scss" scoped>
// .boxWrap {
//   position: absolute;top: 0;left: 0;width: 100%;height: 100%; overflow: hidden;
// }
::v-deep .el-table--border{
  .boldBorder{
    border-right-width: 5px
  }
  td.greenBg{
    background: rgba(0, 128, 0, 0.07) !important;
  }
  td.redBg{
    background: rgba(255, 0, 0, 0.07) !important;
  }
  td.blueBg{
    background: rgba(0, 0, 255, 0.07) !important;
  }
}

::v-deep .el-table {
  .table-total-row.border3 td{
    border-bottom-width: 4px;
  }
  .table-total-row.border2 td{
    border-bottom-width: 3px;
  }
  .table-total-row.border1 td{
    border-bottom-width: 2px;
  }
}

::v-deep .el-table--enable-row-hover .el-table__body tr:hover > td{
    background: rgba(248, 237, 117, 0.561) !important;
}

::v-deep .el-table--border {
  td,th{
    border-color: rgba(48, 77, 121, 0.5);
  }
}
.table-box {
  border: 0;
   ::v-deep .el-tabs__nav-wrap {
    padding: 0 24px;
  }
}

</style>

<style lang="scss">
.spanTable {
  tr td:first-child .cell,tr th:first-child .cell {
    padding-left: 10px;
  }
}
</style>
