<template>
  <div>
    <a-card title="查询条件">
      <a-form-model
        class="search-box"
        :model="form"
        layout="inline"
        @submit.native.prevent="getOrderList"
      >
        <a-form-model-item
          label="渠道"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-select
            style="width: 195px"
            v-model="form.channel"
          >
            <a-select-option
              key=""
            >
              全部
            </a-select-option>
            <a-select-option
              v-for="item in salesChannel"
              :key="item.name"
            >
              {{ item.description }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item
          label="景点"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-select
            style="width: 195px"
            v-model="form.scenic_id"
          >
            <a-select-option
              key=""
            >
              全部
            </a-select-option>
            <a-select-option
              v-for="scenic in scenicList"
              :key="scenic.id"
            >
              {{ scenic.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item
          label="票种"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-select
            style="width: 195px"
            v-model="form.ticket_type_id"
          >
            <a-select-option
              key=""
            >
              全部
            </a-select-option>
            <a-select-option
              v-for="ticket in ticketTypeList"
              :key="ticket.id"
            >
              {{ ticket.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item
          label="场次"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-select
            style="width: 195px"
            v-model="form.batch_type_id"
          >
            <a-select-option
              key=""
            >
              全部
            </a-select-option>
            <a-select-option
              v-for="ticket in batchList"
              :key="ticket.id"
            >
              {{ ticket.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item
          label="开始时间"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-date-picker
            :show-time="{defaultValue: moment('2017-09-09 00:00:00')}"
            v-model="form.start"
            placeholder="选择时间"
          />
        </a-form-model-item>

        <a-form-model-item
          label="结束时间"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-date-picker
            :show-time="{defaultValue: moment('2017-09-09 23:59:59')}"
            v-model="form.end"
            placeholder="选择时间"
          />
        </a-form-model-item>

        <a-form-model-item
          label="游玩开始时间"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-date-picker
            style="width:195px"
            placeholder="选择时间"
            v-model="form.play_start"
          />
        </a-form-model-item>

        <a-form-model-item
          label="游玩截止时间"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-date-picker
            style="width:195px"
            placeholder="选择时间"
            v-model="form.play_end"
          />
        </a-form-model-item>

        <a-form-model-item
          label="导游"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-select
            style="width: 195px"
            v-model="form.guide_id"
          >
            <a-select-option
              key=""
            >
              全部
            </a-select-option>
            <a-select-option
              v-for="ticket in batchList"
              :key="ticket.id"
            >
              {{ ticket.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <div class="bottomItem">
          <a-form-model-item label="分组字段">
            <a-checkbox-group v-model="groupKeyArray">
              <a-checkbox value="channel">
                渠道
              </a-checkbox>
              <a-checkbox value="scenic">
                景点
              </a-checkbox>
              <a-checkbox value="pay_way">
                支付方式
              </a-checkbox>
              <a-checkbox value="secondary_pay_way">
                支付来源
              </a-checkbox>
              <a-checkbox value="batch_type">
                场次
              </a-checkbox>
            </a-checkbox-group>
          </a-form-model-item>
        </div>

        <div class="btn-wrap">
          <a-button
            type="primary"
            @click="exportData"
            :loading="exportLoading"
          >
            导出
          </a-button>
          <a-button
            type="primary"
            html-type="submit"
          >
            搜索
          </a-button>
        </div>
      </a-form-model>
    </a-card>
    <a-card title="售票统计">
      <a-spin :spinning="loading">
        <a-table
          bordered
          :rowClassName="handleClassName"
          :columns="columns"
          :data-source="orderList"
          :pagination="false"
          :row-key="record => Math.random()"
        >
          <template
            slot="pay_way"
            slot-scope="text, record"
          >
            {{ payMap[record.pay_way] || '' }}
          </template>
        </a-table>
      </a-spin>
    </a-card>
  </div>
</template>

<script>
import { getOrderStatisticsByType, exportOrderStatisticsByType } from '@/api/orderSetting/order'
import { getSalesChannel } from '@/api/ticketSetting/channel'
import { getScenic } from '@/api/ticketSetting/scenic'
import { getTicketType } from '@/api/ticketSetting/ticket'

import moment from 'moment'

const payMap = {
  'ALI': '支付宝',
  'WEIXIN': '微信',
  'USERBALANCE': '余额',
  'ZHONGHANG': '中行',
  'ZFBA': '支付宝',
  'WEIX': '微信',
  'UMSOFFLINE': '银联刷卡',
  'UMSONLINE': '银联全民付',
  'NONE': '无'
}
const channelMap = {
  'WEIXIN': '微信',
  'TERM': '自助机',
  'APP': '官网',
  'TRAVELAGENCY': '旅行社',
  'THIRDPARTYTEST': '第三方测试',
  'NANTONGBAITONG': '南通百通',
  'WXMINI': '微信小程序'
}
const titleMap = {
  pay_way: {
    name: '支付方式'
  },
  secondary_pay_way: {
    name: '支付来源'
  },
  scenic: {
    name: '景点'
  },
  channel: {
    name: '渠道'
  },
  batch_type: {
    name: '场次',
    width: 250
  },
  ticket_type: {
    name: '票种',
    width: 250
  },
  ticket_type_price: {
    name: '价格'
  }
}

function getColumns (groupKey) {
  const colData = groupKey.slice(0, -1).map((key, idx) => {
    return {
      title: titleMap[key].name,
      dataIndex: key,
      key: key,
      width: titleMap[key].width,
      customRender: (value, row, index) => {
        const obj = {
          children: (key === 'pay_way' || key === 'secondary_pay_way') ? (payMap[value] || value) : (key === 'channel' ? (channelMap[value] || value) : value),
          attrs: {}
        }
        obj.attrs.rowSpan = row['rowSpan' + (idx + 1)]
        return obj
      }
    }
  })
  return colData.concat([
    {
      title: '价格',
      dataIndex: 'ticket_type_price',
      key: 'ticket_type_price'
    },
    {
      title: '售票张数',
      dataIndex: 'total_ticket_num',
      key: 'total_ticket_num'
    },
    {
      title: '售票金额',
      dataIndex: 'total_ticket_amount',
      key: 'total_ticket_amount'
    },
    {
      title: '检票张数',
      dataIndex: 'checked_ticket_num',
      key: 'checked_ticket_num'
    },
    {
      title: '检票金额',
      dataIndex: 'checked_ticket_amount',
      key: 'checked_ticket_amount'
    },
    {
      title: '退票张数',
      dataIndex: 'refunded_ticket_num',
      key: 'refunded_ticket_num'
    },
    {
      title: '退票金额',
      dataIndex: 'refunded_ticket_amount',
      key: 'refunded_ticket_amount'
    }
  ])
}

export default {
  name: 'StatisticsByType',
  created () {
    this.setDefaultReservationStatus() // 免费游设置默认预约票
    this.getSalesChannel()
    this.getScenicList()
    this.getTicketTypeList()
    this.getOrderList()
  },
  computed: {
    batchList () {
      return this.$store.state.app.batchList
    }
  },
  data () {
    return {
      columns: [],
      exportLoading: false,
      groupKeyArray: ['channel', 'scenic', 'pay_way', 'secondary_pay_way', 'ticket_type'],
      orderList: [],
      loading: true,
      salesChannel: [],
      scenicList: [],
      ticketTypeList: [],
      loopIndex: 0,
      groupKey: [],
      project_name: localStorage.mgt_project,
      is_reservation: 0, // 非台州项目默认不是预约票，params不加此字段。
      form: {
        batch_type_id: '',
        channel: '',
        end: moment().endOf('day'),
        start: moment().startOf('day'),
        play_start: '',
        play_end: moment().endOf('day'),
        scenic_id: '',
        ticket_type_id: ''
      },
      payMap
    }
  },
  methods: {
    moment,
    setDefaultReservationStatus () {
      // 主要目的是请求票种时加入是否是预约票字段
      const taizhouProjectName = 'mianfeiyoutaizhou'
      if (['demo', taizhouProjectName].includes(this.project_name)) {
        this.is_reservation = 1 // 免费游台州则初始化是否是预约票为1
      }
    },
    exportData () {
      this.exportLoading = true

      const params = Object.assign({}, this.form)

      params.start = this.form.start && this.form.start.format('YYYY-MM-DD HH:mm:ss')
      params.end = this.form.end && this.form.end.format('YYYY-MM-DD HH:mm:ss')
      params.play_start = this.form.play_start && this.form.play_start.format('YYYY-MM-DD')
      params.play_end = this.form.play_end && this.form.play_end.format('YYYY-MM-DD')

      exportOrderStatisticsByType(params, this.groupKey).then(res => {
        const _this = this
        this.$confirm({
          content: '导出成功，是否前往下载？',
          onOk () {
            _this.$router.push({ name: 'exportReport' })
          }
        })
      }).finally(() => {
        this.exportLoading = false
      })
    },
    getOrderList () {
      this.loading = true

      this.groupKey = [
        'channel',
        'scenic',
        'pay_way',
        'secondary_pay_way',
        'batch_type'
      ]

      this.groupKey = this.groupKey.filter(k => {
        return this.groupKeyArray.indexOf(k) > -1
      })

      this.groupKey.push('ticket_type')
      this.groupKey.push('ticket_type_price')

      this.columns = getColumns(this.groupKey)

      this.groupKey.forEach((g, i) => {
        this['groupIndexList' + (i + 1)] = []
      })

      const params = Object.assign({}, this.form)

      params.start = this.form.start && this.form.start.format('YYYY-MM-DD HH:mm:ss')
      params.end = this.form.end && this.form.end.format('YYYY-MM-DD HH:mm:ss')
      params.play_start = this.form.play_start && this.form.play_start.format('YYYY-MM-DD')
      params.play_end = this.form.play_end && this.form.play_end.format('YYYY-MM-DD')

      getOrderStatisticsByType(params, this.groupKey).then(res => {
        const data = res.extraInfo
        const tableData = []
        const totalLine = { scenic: '', ticket_type: '', ...data.details }

        data.children.forEach((child, index) => {
          this.formatTableData(tableData, child, data, index)
        })

        tableData.push(totalLine)

        tableData.forEach((row, rowIdx) => {
          if (row['ticket_type_price'] === '小计') {
            row.className = 'rowBg5'
          }
          for (let i = 1; i <= this.groupKey.length; i++) {
            if (!this['groupIndexList' + i]) return
            this['groupIndexList' + i].forEach((idx, index) => {
              const start = idx
              const end = this['groupIndexList' + i][index + 1]

              if (rowIdx === start) {
                row['rowSpan' + i] = end - start
              }

              if (rowIdx > start && rowIdx < end) {
                row['rowSpan' + i] = 0
              }

              if (row[this.groupKey[i - 1]] === '小计') {
                row.className = 'rowBg' + i
              }
            })
          }
        })

        tableData[tableData.length - 1][this.groupKey[0]] = '总计'
        tableData[tableData.length - 1].className = 'rowBg1'

        this.orderList = tableData

        this.loading = false
      })
    },
    formatTableData (list, data, father, index) {
      const item = { ...data.details }

      const idx = this.groupKey.findIndex(i => i === data.group_name) + 1

      if (idx <= this.groupKey.length) {
        this['groupIndexList' + idx].push(list.length)

        data[data.group_name] = data.group_value

        this.groupKey.forEach(key => {
          father[key] && (data[key] = father[key])
        })

        data.children.forEach((child, cidx) => {
          this.formatTableData(list, child, data, cidx)
        })

        this.groupKey.forEach(key => {
          data[key] && (item[key] = data[key])
        })

        item[data.group_name] = data.group_value

        if (idx < this.groupKey.length) {
          item[this.groupKey[idx]] = '小计'
        }

        list.push(item)

        if (idx !== this.groupKey.length) {
          if (index === father.children.length - 1 || father.children.length === 1) {
            for (let i = idx; i < this.groupKey.length; i++) {
              this['groupIndexList' + i].push(list.length)
            }
          }
        }
      }
    },
    getSalesChannel () {
      getSalesChannel().then(res => {
        this.salesChannel = res.extraInfo.list
      })
    },
    getScenicList () {
      getScenic({}).then(res => {
        const getSenicList = res.extraInfo.list.filter(e => e.id !== 9999)
        this.scenicList = getSenicList
      })
    },
    getTicketTypeList () {
      const params = { pageSize: 9999 }
      if (this.is_reservation === 1) {
        params.is_reservation = this.is_reservation
      }
      getTicketType(params).then(res => {
        this.ticketTypeList = res.extraInfo.list
      })
    },
    startChange (date) {
      this.form.start = date ? moment(date).format('YYYY-MM-DD HH:mm:ss') : ''
    },
    endChange (date) {
      this.form.end = date ? moment(date).format('YYYY-MM-DD HH:mm:ss') : ''
    },
    playStartChange (date) {
      this.form.play_start = date ? moment(date).format('YYYY-MM-DD') : ''
    },
    playEndChange (date) {
      this.form.play_end = date ? moment(date).format('YYYY-MM-DD') : ''
    },
    handleClassName (record, index) {
      return record.className || ''
    }
  }
}
</script>

<style lang="scss" scoped>
.title {
  margin-bottom: 15px; font-size: 14px; position: relative; padding-left: 80px;
  b {
    margin-right: 10px; position: absolute; left: 0; top: 0;
  }
}
.ant-form-item {
  width: 320px;
}
.bottomItem{
  .ant-form-item{
    width: 100%;
  }
  ::v-deep .ant-form-item-label{
    width: 106px;
  }
}
::v-deep .rowBg1 td{
  background: rgb(122,190,194) !important;
}
::v-deep .rowBg2 td{
  background: rgb(143,201,204) !important;
}
::v-deep .rowBg3 td{
  background: rgb(164,212,215) !important;
}
::v-deep .rowBg4 td{
  background: rgb(186,224,226) !important;
}
::v-deep .rowBg5 td{
  background: rgb(207,235,237) !important;
}

::v-deep .rowBg6 td{
  background: rgb(220, 241, 243) !important;
}

::v-deep .ant-table-tbody > tr:hover:not(.ant-table-expanded-row) > td {
    background: #ffface;
}
</style>
