<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.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.sales_user_id" @change="getSecondSalesUserList">
            <a-select-option key="">
              全部
            </a-select-option>
            <a-select-option v-for="ticket in salesUserList" :key="ticket.id">
              {{ ticket.name }} - {{ ticket.nick_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.second_sales_user_id">
            <a-select-option key="">
              全部
            </a-select-option>
            <a-select-option v-for="ticket in secondSalesUserList" :key="ticket.id">
              {{ ticket.name }} - {{ ticket.nick_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>
        <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 {
  getSalesOrderStatisticsByType,
  exportSalesOrderStatisticsByType
} from '@/api/orderSetting/order'
import { getTicketType } from '@/api/ticketSetting/ticket'
import { getSalesUserList } from '@/api/marketingSetting/salesUser'

import moment from 'moment'
const titleMap = {
  sales_user: {
    name: '销售人员'
  },
  second_sales_user: {
    name: '二级销售人员'
  },
  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: value,
          attrs: {}
        }
        obj.attrs.rowSpan = row['rowSpan' + (idx + 1)]
        return obj
      }
    }
  })

  return colData.concat([
    {
      title: '佣金',
      dataIndex: 'ticket_type_commission',
      key: 'ticket_type_commission'
    },
    {
      title: '售票张数',
      dataIndex: 'sales_ticket_num',
      key: 'sales_ticket_num'
    },
    {
      title: '售票金额',
      dataIndex: 'sales_ticket_amount',
      key: 'sales_ticket_amount'
    },
    {
      title: '售票总佣金',
      dataIndex: 'sales_ticket_commission',
      key: 'sales_ticket_commission'
    },
    {
      title: '分佣张数',
      dataIndex: 'wx_prorate_num',
      key: 'wx_prorate_num'
    },
    {
      title: '分佣金额',
      dataIndex: 'wx_prorate_amount',
      key: 'wx_prorate_amount'
    }
  ])
}

export default {
  name: 'StatisticsByType',
  created () {
    this.getTicketTypeList()
    this.getOrderList()
    this.getSalesUserList()
    this.getSecondSalesUserList()
  },
  data () {
    return {
      columns: [],
      exportLoading: false,
      groupKeyArray: ['sales_user'],
      orderList: [],
      loading: true,
      ticketTypeList: [],
      loopIndex: 0,
      groupKey: [],
      salesUserList: [],
      secondSalesUserList: [],
      form: {
        end: moment().endOf('day'),
        start: moment().startOf('day'),
        play_start: '',
        play_end: moment().endOf('day'),
        sales_user_id: '',
        second_sales_user_id: '',
        ticket_type_id: '',
        isSalesSell: true
      }
    }
  },
  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')

      exportSalesOrderStatisticsByType(params, this.groupKey)
        .then(res => {
          const _this = this
          this.$confirm({
            content: '导出成功，是否前往下载？',
            onOk () {
              _this.$router.push({ name: 'exportReport' })
            }
          })
        })
        .finally(() => {
          this.exportLoading = false
        })
    },
    // 获取销售人员
    getSalesUserList () {
      const params = {
        pageNum: 0,
        pageSize: 0
      }
      getSalesUserList(params).then(res => {
        this.salesUserList = res.extraInfo.list
      })
    },
    getSecondSalesUserList (id) {
      const params = {
        pageNum: 0,
        pageSize: 0,
        saleType: 2
      }

      if (id) {
        params.parent_sales_user_id = id
        this.form.second_sales_user_id = ''
      }

      getSalesUserList(params).then(res => {
        this.secondSalesUserList = res.extraInfo.list
      })
    },
    getOrderList () {
      this.loading = true

      this.groupKey = [
        'sales_user',
        'second_sales_user',
        'ticket_type',
        'ticket_type_price',
        'ticket_type_commission'
      ]

      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')

      getSalesOrderStatisticsByType(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 => {
          if (father[key] || father[key] === 0) {
            data[key] = father[key]
          }
        })

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

        this.groupKey.forEach(key => {
          if (data[key] || data[key] === 0) {
            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)
            }
          }
        }
      }
    },

    getTicketTypeList () {
      // getTicketType({ pageSize: 999, type: 'MEMBER' }).then(res => {
      // this.ticketTypeList = res.extraInfo.list.filter(
      //   i => i.is_convertible === 1
      // )
      // 票种里去掉兑换票的过滤限制
      // this.ticketTypeList = res.extraInfo.list // 曹赟：is_convertible字段若为1，表示的是兑换票，前端通过这个条件的过滤去掉吧，销售统计获取票种列表应该跟订单统计获取的票种是一致，
      // })
      /* 去除全部筛选限制，保持与销售订单的票种一致 */
      const params = {
        channel: this.currentChannel,
        scenic: this.currentScenic,
        type: '',
        pageNum: 0,
        pageSize: 0
      }
      getTicketType(params).then(res => {
        this.ticketTypeList = res.extraInfo.list
      })
    },

    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>
