<template>
  <div class="form-wrap">
    <el-form
      class="search-box"
      ref="form"
      :model="form"
      :inline="true"
    >
      <div class="block-title">
        查询条件
      </div>
      <el-form-item
        label="起始时间"
        prop="cancelTimeBegin">
        <el-date-picker
          v-model="form.cancelTimeBegin"
          type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="结束时间"
        prop="cancelTimeEnd">
        <el-date-picker
          default-time="23:59:59"
          v-model="form.cancelTimeEnd"
          type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="票种"
        prop="ticketTypeIdList">
        <el-select
          v-model="form.ticketTypeIdList"
          multiple
          clearable
          placeholder="请选择">
          <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="otaSourceNameList">
        <el-select
          v-model="form.otaSourceNameList"
          multiple
          clearable
          filterable>
          <el-option
            v-for="item in otaSourceList"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 新增分组筛选项 -->

      <el-form-item
        label="分组筛选"
        style="width:100%">
        <el-checkbox-group
          v-model="selectKeys"
          :min="0"
          :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="reportExport">
          导出
        </el-button>
      </div>
    </el-form>

    <div class="table-box">
      <!-- <div class="block-title">
        统计信息
      </div> -->
      <el-table
        border
        stripe
        v-loading="loading"
        :data="tableData"
        :row-class-name="totalRowClassName"
        :span-method="objectSpanMethod">
        <el-table-column
          v-for="(item) in finalGroup"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label">
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { getCancelOrderStatistics } from '@/api/queryReport'
import { getSaleChannelList } from '@/api/order'
import { totalRowClassName } from '@/utils'
import draggable from 'vuedraggable'
import moment from 'moment'

export default {
  name: 'refundStatistics',
  components: {
    draggable
  },
  data () {
    return {
      form: {
        cancelTimeBegin: new Date(moment().format('YYYY-MM-DD') + ' 00:00:00'),
        cancelTimeEnd: new Date(moment().format('YYYY-MM-DD') + ' 23:59:59'),
        ticketTypeIdList: [], // 票种
        otaSourceNameList: [],
        groupByList: []
      },
      groupKeys: [{ value: 'orderDateDay', label: '统计日期' }],
      finalGroup: [
        // { prop: 'orderDateDay', label: '统计日期' },
        { prop: 'otaSourceName', label: '销售渠道' },
        { prop: 'ticketTypeName', label: '票种' },
        { prop: 'unitPrice', label: '单价' },
        { prop: 'cancelCount', label: '退票数量' },
        { prop: 'cancelNum', label: '退票人数' },
        { prop: 'cancelPrice', label: '退票金额' },
        { prop: 'cancelSettlementPrice', label: '退票结算金额' }
      ],
      selectKeys: [], // 默认选中
      tableData: [],
      otaSourceList: [],
      OrderIndexArr: [],
      index: 0,
      tableIndex: 1,
      loading: false
    }
  },
  computed: {
    ticketTypeList () {
      const { ticketTypeList } = this.$store.state.app
      const { orderCategory } = this.form
      return orderCategory ? ticketTypeList.filter(item => item.category === orderCategory) : ticketTypeList
    },
    payChannelOptions () {
      return this.$store.getters.payChannelOptions
    }
  },
  created () {
    this.getSaleChannelList()
    this.getList()
  },
  methods: {
    totalRowClassName,
    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
                }
              }
            }
          }
        }
      }
    },
    getSaleChannelList () {
      getSaleChannelList().then(res => {
        this.otaSourceList = res.data
      })
    },
    reset () {
      this.$refs.form.resetFields()
    },
    setTime () {
      if (this.form.cancelTimeBegin) {
        this.form.cancelTimeBegin = moment(this.form.cancelTimeBegin).format('YYYY-MM-DD HH:mm:ss')
      } else {
        this.form.cancelTimeBegin = ''
      }

      if (this.form.cancelTimeEnd) {
        this.form.cancelTimeEnd = moment(this.form.cancelTimeEnd).format('YYYY-MM-DD HH:mm:ss')
      } else {
        this.form.cancelTimeEnd = ''
      }
    },
    reportExport () {
      this.setTime()

      if (!this.form.ticketTypeIdList) {
        this.form.ticketTypeIdList = []
      }

      if (!this.form.otaSourceNameList) {
        this.form.otaSourceNameList = []
      }
      this.$confirm(`是否要导出明细数据`, '确认提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        this.handleExport({
          ...this.form,
          export: true,
          exportDetail: true
        })
      }).catch(() => {
        this.handleExport({
          ...this.form,
          export: true,
          exportDetail: false
        })
      })
    },
    handleExport (params) {
      getCancelOrderStatistics(params).then(() => {
        this.$message.success('导出成功。')
        this.goToDownload()
      }, () => {
        this.$message.success('导出失败。')
      })
    },
    getList () {
      if (this.selectKeys.length === 0) {
        this.finalGroup = [
          { prop: 'otaSourceName', label: '销售渠道' },
          { prop: 'ticketTypeName', label: '票种' },
          { prop: 'unitPrice', label: '单价' },
          { prop: 'cancelCount', label: '退票数量' },
          { prop: 'cancelNum', label: '退票人数' },
          { prop: 'cancelPrice', label: '退票金额' },
          { prop: 'cancelSettlementPrice', label: '退票结算金额' }
        ]
      } else {
        this.finalGroup = [
          { prop: 'orderDateDay', label: '统计日期' },
          { prop: 'otaSourceName', label: '销售渠道' },
          { prop: 'ticketTypeName', label: '票种' },
          { prop: 'unitPrice', label: '单价' },
          { prop: 'cancelCount', label: '退票数量' },
          { prop: 'cancelNum', label: '退票人数' },
          { prop: 'cancelPrice', label: '退票金额' },
          { prop: 'cancelSettlementPrice', label: '退票结算金额' }
        ]
      }

      this.form.groupByList = [...this.selectKeys] || []

      this.loading = true
      this.setTime()
      getCancelOrderStatistics(this.form).then(res => {
        this.tableData = res.data || []
        console.log('tableData', this.tableData)
        console.log('finalGroup', this.finalGroup)
      }).finally(() => {
        this.loading = false
      })
    }
  }
}
</script>
