<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.term_user_id"
            allowClear
          >
            <a-select-option
              key=""
            >
              全部
            </a-select-option>
            <a-select-option
              v-for="item in termList"
              :key="item.id"
            >
              {{ item.nickname || item.mac }}
            </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
            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
            v-model="form.end"
            placeholder="选择时间"
          />
        </a-form-model-item>

        <div class="bottomItem">
          <a-form-model-item label="分组字段">
            <a-checkbox-group v-model="groupKeyArray">
              <a-checkbox value="term_user">
                自助机
              </a-checkbox>
              <a-checkbox value="term_pickup_ticket_date">
                取票时间
              </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()"
        >
        </a-table>
      </a-spin>
    </a-card>
  </div>
</template>

<script>
import { getOrderStatisticsByTerm, exportOrderStatisticsByTerm, getTermManager } from '@/api/saleChannel/term'
import moment from 'moment'

const channelMap = {
  'WEIXIN': '微信',
  'TERM': '自助机',
  'APP': '官网',
  'TRAVELAGENCY': '旅行社',
  'THIRDPARTYTEST': '第三方测试',
  'NANTONGBAITONG': '南通百通'
}
const titleMap = {
  term_pickup_ticket_date: {
    name: '取票时间'
  },
  term_user: {
    name: '自助机名称'
  }
}

function getColumns (groupKey) {
  const colData = groupKey.map((key, idx) => {
    return {
      title: titleMap[key].name,
      dataIndex: key,
      key: key,
      width: titleMap[key].width,
      customRender: (value, row, index) => {
        const obj = {
          children: (key === 'term_user' ? (channelMap[value] || value) : value),
          attrs: {}
        }
        obj.attrs.rowSpan = row['rowSpan' + (idx + 1)]
        return obj
      }
    }
  })
  return colData.concat([
    {
      title: '取票张数',
      dataIndex: 'term_pickup_ticket_num',
      key: 'term_pickup_ticket_num'
    }
  ])
}

export default {
  name: 'StatisticsByType',
  created () {
    this.getTermManagerList()
    this.getOrderList()
  },
  computed: {

  },
  data () {
    return {
      columns: [],
      exportLoading: false,
      groupKeyArray: ['term_user', 'term_pickup_ticket_date'],
      orderList: [],
      loading: true,
      termList: [],
      loopIndex: 0,
      groupKey: [],
      form: {
        end: moment().endOf('day'),
        start: moment().startOf('day'),
        term_user_id: ''
      }
    }
  },
  methods: {
    moment,
    getTermManagerList () {
      const params = {
        pageNum: 1,
        pageSize: 999,
        status: ['active', 'inactive']
      }
      getTermManager(params).then(res => {
        this.termList = res.extraInfo.list
      })
    },
    exportData () {
      this.exportLoading = true
      const params = Object.assign({}, this.form)
      params.start = this.form.start && this.form.start.format('YYYY-MM-DD')
      params.end = this.form.end && this.form.end.format('YYYY-MM-DD')
      exportOrderStatisticsByTerm(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 = [
        'term_user',
        'term_pickup_ticket_date'
      ]

      this.groupKey = this.groupKey.filter(k => {
        return this.groupKeyArray.indexOf(k) > -1
      })
      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')
      params.end = this.form.end && this.form.end.format('YYYY-MM-DD')

      getOrderStatisticsByTerm(params, this.groupKey).then(res => {
        const data = res.extraInfo
        const tableData = []
        const totalLine = { term_pickup_ticket_date: '', ...data.details }
        data.children.forEach((child, index) => {
          this.formatTableData(tableData, child, data, index)
        })
        tableData.push(totalLine)
        tableData.forEach((row, rowIdx) => {
          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 && i !== 2) {
                row['rowSpan' + i] = end - start
              }
              if (rowIdx > start && rowIdx < end && i !== 2) {
                row['rowSpan' + i] = 0
              }
              if (row[this.groupKey[i - 1]] === '小计') {
                row.className = 'rowBg' + (i + 2)
              }
            })
          }
        })

        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)
            }
          }
        }
      }
    },
    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>
