<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-input v-model="form.agency_name"></a-input>
        </a-form-model-item>

        <a-form-model-item
          label="导游名称"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 13 }"
        >
          <a-input v-model="form.guide_name"></a-input>
        </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>

        <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 { agencyOrderStatistics, exportAgencyOrderStatistics } 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': '无'
}

function getColumns (groupKey) {
  const colData = [
    {
      title: '旅行社名称',
      dataIndex: 'agency_name',
      key: 'agency_name'
    },
    {
      title: '导游名称',
      dataIndex: 'guide_name',
      key: 'guide_name'
    }
  ]
  return colData.concat([
    {
      title: '售票数量',
      dataIndex: 'sum_count',
      key: 'sum_count'
    },
    {
      title: '售票金额',
      dataIndex: 'sum_price',
      key: 'sum_price'
    },
    {
      title: '退票张数',
      dataIndex: 'sum_cancel_count',
      key: 'sum_cancel_count'
    },
    {
      title: '退票金额',
      dataIndex: 'sum_cancel_price',
      key: 'sum_cancel_price'
    }
  ])
}

export default {
  name: 'StatisticsByType',
  created () {
    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: [],
      form: {
        agency_name: '',
        guide_name: '',
        end: moment().endOf('day'),
        start: moment().startOf('day')
      },
      payMap
    }
  },
  methods: {
    moment,
    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')

      exportAgencyOrderStatistics(params, ['agency_name']).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')

      agencyOrderStatistics(params).then(res => {
        this.orderList = res.extraInfo

        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 () {
      getTicketType({ pageSize: 9999 }).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>
