<template>
  <div class="form-wrap">
    <el-form
      class="search-box"
      ref="form"
      :model="form"
      :inline="true"
      label-width="70px">
      <div class="block-title">
        查询条件
      </div>
      <el-form-item
        label="订单号"
        prop="keyWords1">
        <el-input v-model="form.keyWords1"></el-input>
      </el-form-item>
      <el-form-item
        label="票号"
        prop="keyWords2">
        <QRReader v-model="form.keyWords2"></QRReader>
      </el-form-item>
      <el-form-item
        label="游客姓名"
        prop="keyWords7">
        <el-input v-model="form.keyWords7"></el-input>
      </el-form-item>
      <el-form-item
        label="游客手机"
        prop="keyWords6">
        <el-input v-model="form.keyWords6"></el-input>
      </el-form-item>
      <el-form-item
        label="身份证号"
        prop="keyWords5">
        <ReaderInput
          type="ID"
          v-model="form.keyWords5"></ReaderInput>
      </el-form-item>
      <el-form-item
        label="起始时间"
        prop="startDate">
        <el-date-picker
          v-model="form.startDate"
          type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="截止时间"
        prop="endDate">
        <el-date-picker
          default-time="23:59:59"
          v-model="form.endDate"
          type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="票状态"
        prop="keyWords4">
        <el-select
          v-model="form.keyWords4"
          clearable
          placeholder="请选择">
          <el-option
            label="全部"
            value=""></el-option>
          <el-option
            v-for="item in ticketStatusDic"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="票种"
        prop="keyWords3">
        <el-select
          v-model="form.keyWords3"
          clearable
          placeholder="请选择">
          <el-option
            label="全部"
            value=""></el-option>
          <el-option
            v-for="item in ticketTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="分销商"
        prop="keyWords11">
        <el-input v-model="form.keyWords11"></el-input>
      </el-form-item>
      <el-form-item
        label="分组筛选"
        style="width:100%">
        <el-checkbox-group
          v-model="selectKeys"
          :min="1"
          :max="4">
          <draggable :list="groupKeys">
            <el-checkbox
              :key="item.value"
              :label="item.value"
              v-for="(item) in groupKeys"
            >
              {{ item.label }}
            </el-checkbox>
          </draggable>
        </el-checkbox-group>
        （可拖拽排序）
      </el-form-item>
      <div class="btn-wrap">
        <el-button
          @click="reset">
          重置
        </el-button>
        <el-button
          :disabled="loading"
          type="primary"
          @click="getList">
          搜索
        </el-button>
        <el-button
          type="primary"
          @click="exportStatist">
          导出
        </el-button>
      </div>
    </el-form>

    <div class="table-box">
      <!-- <div class="block-title">
        统计信息
      </div> -->
      <el-table
        border
        stripe
        :key="tableIndex"
        v-loading="loading"
        :data="tableData"
        :span-method="objectSpanMethod"
        :row-class-name="totalRowClassName">
        <el-table-column
          v-for="(item) in finalGroup"
          :key="item.value"
          :prop="item.prop||item.value"
          :label="item.label">
        </el-table-column>
        <el-table-column
          prop="sum_people"
          label="取票人数">
        </el-table-column>
        <el-table-column
          prop="sum_count"
          label="取票张数">
        </el-table-column>
        <el-table-column
          prop="sum_price"
          label="取票金额">
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { getTicketPrintStatistics } from '@/api/printOnlineTicket'
import { getTicketTypeList } from '@/api/ticketType'
import { ticketStatusDic } from '@/assets/staticData'
import { exportTicketPrintStatistics } from '@/api/queryReport'
import draggable from 'vuedraggable'
import { totalRowClassName } from '@/utils'

import ReaderInput from '@/components/ReaderInput'

import moment from 'moment'
const groupKeys = [
  { value: 'otaSourceName', label: 'OTA 名称' },
  { value: 'batch_config_id', label: '场次名', prop: 'batchConfigName' },
  { value: 'managerId', label: '售票员', prop: 'manager_name' },
  { value: 'ticketTypeId', label: '票种', prop: 'ticketTypeName' },
  { value: 'payChannel', label: '支付方式' },
  { value: 'price_plan_id', label: '价格方案', prop: 'price_plan_name' },
  { value: 'unit_price', label: '单价' }
]
export default {
  name: 'printOlStatistics',
  components: {
    ReaderInput,
    draggable
  },
  data () {
    return {
      ticketStatusDic: ticketStatusDic,
      ticketTypeList: [],
      OrderIndexArr: [],
      index: 0,
      tableIndex: 1,
      finalGroup: [{ value: 'ticketTypeId', label: '票种', prop: 'ticketTypeName' }],
      selectKeys: ['ticketTypeId'],
      groupKeys,
      form: {
        startDate: new Date(moment().startOf('day').format('YYYY-MM-DD HH:mm:ss')),
        endDate: new Date(moment().endOf('day').format('YYYY-MM-DD HH:mm:ss')),
        keyWords1: '', // 订单号
        keyWords2: '', // 票号
        keyWords3: '', // 票种id
        keyWords4: '', // 票状态
        keyWords5: '', // 游客证件号
        keyWords6: '', // 游客手机
        keyWords7: '', // 游客姓名
        keyWords11: '', // 分销商
        keyGroupBy: ['ticketTypeId']
      },
      tableData: [],
      loading: false
    }
  },
  created () {
    const searchParams = JSON.parse(sessionStorage.getItem('统计表-取票统计-查询条件'))
    if (searchParams) {
    // 如果存在查询条件，则设置到组件的数据中
      this.form = searchParams // 记住上次搜索条件
    }
    let lastSelectKeys = JSON.parse(sessionStorage.getItem('统计表-取票统计-查询条件-selectKeys')) // 加载上次记住的分组信息
    if (lastSelectKeys) {
      this.selectKeys = lastSelectKeys
    }
    this.getTicketTypeList()
    this.getList()
  },
  methods: {
    totalRowClassName,
    reset () {
      this.$refs.form.resetFields()
    },
    // 获取票种列表
    getTicketTypeList () {
      return getTicketTypeList({
        pageNum: 1,
        pageSize: 999
      }).then(res => {
        this.ticketTypeList = res.list
      })
    },
    getList () {
      this.tableIndex++
      let groupArray = []
      let orderIndexArr = []
      this.finalGroup = this.groupKeys.filter(i => {
        return this.selectKeys.includes(i.value)
      })
      this.form.keyGroupBy = this.finalGroup.map(i => i.value)
      let params = JSON.parse(JSON.stringify(this.form))

      params.keyWords1 = moment(params.keyWords1).format('YYYY-MM-DD HH:mm:ss')
      params.keyWords2 = moment(params.keyWords2).format('YYYY-MM-DD HH:mm:ss')

      this.loading = true
      getTicketPrintStatistics(this.form).then(res => {
        this.tableData = res.data
        this.finalGroup.forEach(i => {
          groupArray.push({})
        })
        groupArray.forEach((group, index) => {
          const keyName = this.finalGroup[index].prop || this.finalGroup[index].value
          this.tableData.forEach((el, index) => {
            if (el[keyName] === '小计') {
              this.index++
            }
            !group[el[keyName] + this.index] && (group[el[keyName] + this.index] = [])
            group[el[keyName] + this.index].push(index)
          })

          const arr = []
          for (let k in group) {
            if (group[k].length > 1) {
              arr.push(group[k])
            }
          }
          orderIndexArr.push(arr)
        })
        this.OrderIndexArr = orderIndexArr
      }).finally(() => {
        this.loading = false
        sessionStorage.setItem('统计表-取票统计-查询条件', JSON.stringify(this.form)) // 下次记住
        sessionStorage.setItem('统计表-取票统计-查询条件-selectKeys', JSON.stringify(this.selectKeys)) // 下次记住
      })
    },
    objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (columnIndex < this.finalGroup.length) {
        if (!(this.OrderIndexArr[columnIndex] && this.OrderIndexArr[columnIndex].length)) return

        for (let i = 0; i < this.OrderIndexArr[columnIndex].length; i++) {
          let element = this.OrderIndexArr[columnIndex][i]
          for (let j = 0; j < element.length; j++) {
            let item = element[j]
            if (rowIndex === item) {
              if (j === 0) {
                return {
                  rowspan: element.length,
                  colspan: 1
                }
              } else if (j !== 0) {
                return {
                  rowspan: 0,
                  colspan: 0
                }
              }
            }
          }
        }
      }
    },
    exportStatist () {
      let params = JSON.parse(JSON.stringify(this.form))

      params.keyWords1 = moment(params.keyWords1).format('YYYY-MM-DD HH:mm:ss')
      params.keyWords2 = moment(params.keyWords2).format('YYYY-MM-DD HH:mm:ss')
      exportTicketPrintStatistics(this.form).then(res => {
        this.$message.success('导出成功。')
        this.goToDownload()
      })
    }
  }
}
</script>

<style scoped>

</style>
