<template>
  <div class="form-wrap">
    <div class="searchBox">
      <el-form
        ref="form"
        :model="form"
        :inline="true"
        label-width="150px">
        <el-form-item
          label="起始时间"
          prop="timeBegin">
          <el-date-picker
            v-model="form.timeBegin"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="截止时间"
          prop="timeEnd">
          <el-date-picker
            v-model="form.timeEnd"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="票种"
          prop="ticketTypeIdList">
          <el-select
            filterable
            v-model="form.ticketTypeIdList"
            multiple
            clearable
            placeholder="请选择">
            <el-option
              v-for="item in ticketTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.ticketTypeId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="分销商名称"
          prop="otaSourceNameList">
          <el-select
            filterable
            multiple
            v-model="form.otaSourceNameList"
            placeholder="请选择">
            <el-option
              v-for="item in otaSourceList"
              :key="item.otaSourceCode"
              :label="item.otaSourceName"
              :value="item.otaSourceName">
            </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>
      </el-form>
      <div class="btn-wrap">
        <el-button
          @click="reset">重置</el-button>
        <el-button
          type="primary"
          @click="getOrderStatistics($event,true)">搜索</el-button>
        <el-button
          type="primary"
          @click="reportExport">导出</el-button>
      </div>
    </div>

    <div class="tableBox">
      <!-- <div class="block-title">
        查询信息
      </div> -->
      <el-table
        :data="tableData"
        stripe
        row-class-name="is-center"
        v-loading="loading"
        :span-method="objectSpanMethod">
        <el-table-column
          v-for="(item) in finalGroup"
          :key="item.value"
          :prop="item.prop || item.value"
          :label="item.label">
        </el-table-column>
        <el-table-column
          prop="otaSourceName"
          label="订单渠道">
        </el-table-column>
        <el-table-column
          prop="ticketTypeName"
          label="票种">
        </el-table-column>
        <el-table-column
          prop="unitPrice"
          label="单价">
        </el-table-column>
        <el-table-column
          prop="saleNum"
          label="售票张数">
        </el-table-column>
        <el-table-column
          prop="salePrice"
          label="售票金额">
        </el-table-column>
        <el-table-column
          prop="saleSettlementPrice"
          label="售票结算价">
        </el-table-column>
        <el-table-column
          prop="cancelNum"
          label="退票张数">
        </el-table-column>
        <el-table-column
          prop="cancelPrice"
          label="退票金额">
        </el-table-column>
        <el-table-column
          prop="cancelSettlementPrice"
          label="退票结算价">
        </el-table-column>
        <el-table-column
          prop="actualNum"
          label="实售数量">
        </el-table-column>
        <el-table-column
          prop="actualPrice"
          label="实售金额">
        </el-table-column>
        <el-table-column
          prop="actualSettlementPrice"
          label="实售结算价">
        </el-table-column>
        <!-- <el-table-column
          width="260"
          fixed="right"
          label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="showOrderInfo(scope.row)">订单详情</el-button>
            <el-button
              type="text"
              @click="$refs.ticketInfo.show(scope.row.tickets)">门票详情</el-button>
            <el-button
              type="text"
              @click="showGuestInfo(scope.row)">游客信息</el-button>
            <el-button
              type="text"
              v-if="checkRefundVisible(scope.row)&&canCancel"
              @click="showOrderInfo(scope.row,'cancel')">退订单</el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <el-pagination
        background
        :current-page.sync="form.pageNum"
        @current-change="getOrderStatistics"
        layout="total, prev, pager, next"
        :total="total">
      </el-pagination>
    </div>

    <ElDialog
      :title="type==='cancel'?'退单':'订单详情'"
      width="760px"
      v-model="orderDialogVisible"
    >
      <OrderDialog
        :current-item="currentItem"
        :can-cancel="canCancel"
        @updateList="getOrderStatistics"
        :type="type"></OrderDialog>
    </ElDialog>
    <ElDialog
      title="游客信息"
      width="760px"
      v-model="guestDialogVisible">
      <GuestDialog
        :current-item="currentItem"></GuestDialog>
    </ElDialog>

    <TicketInfo ref="ticketInfo"></TicketInfo>
  </div>
</template>
<script>
import { getOrderStatistics, getOtaSourceList } from '@/api/order'
import { getTicketTypeList } from '@/api/ticketType'
import ElDialog from '@/components/Dialog'
import OrderDialog from './orderList/OrderDialog'
import GuestDialog from './orderList/GuestDialog'
import TicketInfo from './orderList/TicketInfo'
import { orderStatus } from '@/const'
import moment from 'moment'

const groupKeys = [
  { value: 'orderDateDay', label: '日期' }
]

export default {
  name: 'salesReport',
  components: {
    ElDialog,
    OrderDialog,
    GuestDialog,
    TicketInfo
  },
  data () {
    return {
      groupKeys,
      ticketTypeList: [],
      otaSourceList: [],
      projectName: localStorage.getItem('otaProject'),
      totalObj: {},
      type: '', // 操作状态 cancel退订单
      form: {
        timeBegin: moment().startOf('day'),
        timeEnd: moment().endOf('day'),
        ticketTypeIdList: [], // 票种名称
        otaSourceNameList: [], // 订单渠道
        export: false,
        pageNum: 1,
        pageSize: 10,
        groupByList: []
      },
      selectKeys: [],
      finalGroup: [],
      tableIndex: 1,
      OrderIndexArr: [],
      orderStatusDic: orderStatus,
      loading: false,
      tableData: [],
      total: 0,
      currentItem: {},
      orderDialogVisible: false,
      guestDialogVisible: false
    }
  },
  created () {
    this.getTicketTypeList()
    this.getOtaSourceList()
    this.getOrderStatistics()
  },
  computed: {
    canCancel () {
      return this.$store.state.user.permissionList.includes('orders:cancel')
    },
    queryClear () {
      return this.$store.state.user.permissionList.includes('stats:clearwx_query')
    },
    otaList () {
      const list = JSON.parse(localStorage.getItem('otaList'))
      return this.projectName === 'YINXIANGMAZU' && !this.queryClear ? list.filter(item => item.otaSourceCode !== 'CLEARWX') : list
    }
  },
  methods: {
    checkRefundVisible (item) {
      if (item.status !== 'CANCELED') return true
      if (item.status === 'CANCELED') {
        if (item.tickets.some(i => i.status !== 'CANCELED')) {
          return true
        } else {
          return false
        }
      }
      return false
    },
    reset () {
      this.$refs.form.resetFields()
    },
    getTicketTypeList () {
      getTicketTypeList({
        pageNum: 1,
        pageSize: -1
      }).then(res => {
        this.ticketTypeList = res.data.records || []
      })
    },
    getOtaSourceList () {
      getOtaSourceList({
        pageNum: 1,
        pageSize: -1
      }).then(res => {
        this.otaSourceList = res.data.records || []
      })
    },
    getOrderStatistics (e, goFirst) {
      if (goFirst) { this.form.pageNum = 1 }

      if (!this.form.timeBegin || !this.form.timeEnd) {
        this.$message.error('请选择起始时间和截止时间')
        return
      }

      this.form.timeBegin = moment(this.form.timeBegin).format('YYYY-MM-DD HH:mm:ss')
      this.form.timeEnd = moment(this.form.timeEnd).format('YYYY-MM-DD HH:mm:ss')

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

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

      this.finalGroup = this.groupKeys.filter(i => {
        return this.selectKeys.includes(i.value)
      })

      this.form.groupByList = this.finalGroup.map(i => i.value)

      this.loading = true
      getOrderStatistics(this.form).then(res => {
        this.tableData = res.data
        this.loading = false
      })
    },
    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
                }
              }
            }
          }
        }
      }
    },
    showOrderInfo (item, type) {
      if ((item.otaSourceCode === 'CLEARWX' || item.otaSourceCode === 'CLEARWXDEV') && type === 'cancel') return this.$message.info('自营平台订单请到自营后台办理退票')
      this.currentItem = item
      this.type = type
      this.orderDialogVisible = true
    },
    showGuestInfo (item) {
      this.currentItem = item
      this.guestDialogVisible = true
    },
    reportExport () {
      this.$confirm(`是否要导出明细数据`, '确认提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        this.handelExport({
          ...this.form,
          export: true,
          exportDetail: true
        })
      }).catch(() => {
        this.handelExport({
          ...this.form,
          export: true,
          exportDetail: false
        })
      })
    },
    handelExport (params) {
      getOrderStatistics(params).then(res => {
        this.$confirm('导出成功，是否去下载页', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$router.push('/queryReport/reportExport')
        }).catch(() => {})
      }, () => {
        this.$notify.error({
          title: '提示',
          message: '导出失败'
        })
      })
    }
  }
}
</script>

<style scoped>

</style>
