<template>
  <div class="form-wrap">
    <el-form
      class="search-box"
      ref="form"
      :model="form"
      :inline="true"
      label-width="100px">
      <div class="block-title">
        查询条件
      </div>
      <el-form-item
        label="起始时间"
        prop="startDate">
        <el-date-picker
          v-model="form.startDate"
          type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item
        label="截止时间"
        prop="endDate">
        <el-date-picker
          default-time="23:59:59"
          v-model="form.endDate"
          type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item
        label="票种列表"
        prop="keyList1"
      >
        <el-select
          v-model="form.keyList1"
          multiple
          collapse-tags
          filterable
          clearable
          placeholder="请选择"
          @change="selectAll">
          <el-option
            :value="0"
            label="全部票种">
          </el-option>
          <el-option
            v-for="item in ticketTypeList"
            :key="item.id"
            :value="item.id"
            :label="item.name">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="售票员"
        prop="keyList7">
        <el-select
          multiple
          v-model="form.keyList7">
          <el-option
            v-for="item in salesList"
            :key="item.id"
            :label="item.nickName"
            :value="item.nickName">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="景点"
        prop="keyWords4">
        <el-select v-model="form.keyWords4">
          <el-option
            value=""
            label="全部"></el-option>
          <el-option
            v-for="item in userScenic"
            :key="item.id"
            :value="item.id"
            :label="item.name">
          </el-option>
        </el-select>
      </el-form-item>

      <template>
        <el-form-item
          label="游玩开始时间"
          prop="keyWords5">
          <el-date-picker
            v-model="form.keyWords5"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item
          label="游玩截止时间"
          prop="keyWords6">
          <el-date-picker
            default-time="23:59:59"
            v-model="form.keyWords6"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item
          label="类型"
          prop="keyList3"
        >
          <el-select
            v-model="form.keyList3"
            multiple
            collapse-tags
            clearable
            placeholder="请选择"
            @change="selectAllCate">
            <el-option
              :value="0"
              label="全部">
            </el-option>
            <el-option
              v-for="item in ticketCategory"
              :key="item.id"
              :value="item.id"
              :label="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="票种归类标签"
          prop="keyList4">
          <el-select
            v-model="form.keyList4"
            multiple
            filterable
            clearable>
            <el-option-group
              v-for="group in ticketTagList"
              :key="group.name"
              :label="group.name">
              <el-option
                v-for="item in group.children"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item
          label="最低价格"
          prop="keyWords8">
          <el-input v-model.number="form.keyWords8"></el-input>
        </el-form-item>

        <el-form-item
          label="最高价格"
          prop="keyWords9">
          <el-input v-model.number="form.keyWords9"></el-input>
        </el-form-item>

        <el-form-item
          label="是否取票"
          prop="keyWords11">
          <el-select
            v-model="form.keyWords11"
            clearable
            placeholder="请选择"
          >
            <el-option
              label="全部"
              value=""></el-option>
            <el-option
              label="是"
              :value="1"
            >
            </el-option>
            <el-option
              label="否"
              :value="0"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="销售渠道"
          prop="keyList5"
        >
          <el-select
            v-model="form.keyList5"
            placeholder="请选择"
            multiple
            clearable
          >
            <el-option
              v-for="(item,idx) in saleChannel"
              :key="idx"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="票状态列表"
          prop="keyList2">
          <el-select
            v-model="form.keyList2"
            multiple
            collapse-tags
            clearable
            placeholder="请选择">
            <el-option
              v-for="item in ticketStatusDic"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="支付方式"
          prop="keyList6">
          <el-select
            v-model="form.keyList6"
            filterable
            multiple
            clearable>
            <el-option
              v-for="item in payChannelOptions"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="售票点"
          prop="keyList8"
        >
          <el-select
            v-model="form.keyList8"
            multiple>
            <el-option
              v-for="item in ticketSpotList"
              :key="item.id"
              :value="item.id"
              :label="item.name"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="添加取票统计"
          prop="keyWords13"
        >
          <el-switch
            v-model="form.keyWords13"
            :active-value="1"
            :inactive-value="0"
          >
          </el-switch>
        </el-form-item>

        <!-- <el-form-item
          label="分组筛选"
          style="width:100%">
          <el-checkbox-group
            v-model="selectKeys"
            :min="1"
            :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> -->
      </template>

      <div class="btn-wrap">
        <!-- <el-button
          @click="reportExport">
          导出
        </el-button> -->
        <el-button
          @click="reset">
          重置
        </el-button>
        <el-button
          :disabled="loading"
          type="primary"
          @click="getSaleStatistic">
          搜索
        </el-button>
      </div>
    </el-form>

    <div class="table-box">
      <el-table
        border
        stripe
        :key="tableIndex"
        v-loading="loading"
        :data="tableData"
        :row-class-name="totalRowClassName">
        <el-table-column
          prop="ticketTypeName"
          label="售票金额">
        </el-table-column>

        <el-table-column
          v-for="(item) in columns"
          :key="item"
          :prop="item"
          :label="item">
          <template slot-scope="scope">
            {{ scope.row[item] || 0 }}
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
/* eslint-disable vue/no-unused-components */
import { getScenic, getTicketTypeList } from '@/api/ticketType'
import { getOrderStatistics } from '@/api/order.js'
import { getTicketTypeTagList } from '@/api/ticketTypeTag'
import { exportOrderStatistics } from '@/api/queryReport'
import { ticketStatusDic } from '@/assets/staticData'
import { getTicketSpotList } from '@/api/ticketSpot'
// import draggable from 'vuedraggable'
import Tip from '@/components/Tip'
import moment from 'moment'
import NP from 'number-precision'

const groupKeys = [
  { value: 'otaSourceName', label: 'OTA 名称' },
  { value: 'batch_config_id', label: '场次名', prop: 'batchConfigName' },
  { value: 'managerId', label: '售票员', prop: 'manager_name' },
  { value: 'ticketTypeId', label: '票种', prop: 'ticketTypeName' },
  { value: 'payChannel', label: '支付方式' },
  { value: 'price_plan_id', label: '价格方案', prop: 'price_plan_name' },
  { value: 'unit_price', label: '单价' }
]

export default {
  computed: {
    ticketCategory () {
      return this.$store.state.app.ticketCategory
    },
    salesList () {
      return this.$store.state.user.salesList
    },
    saleChannel () {
      return this.$store.state.app.saleChannel
    },
    payChannelOptions () {
      return this.$store.getters.payChannelOptions
    },
    userScenic () {
      return this.$store.state.app.account.managerScenicMatrix ? this.$store.state.app.account.managerScenicMatrix : this.scenicList
    }
  },
  components: {
    Tip
  },
  data () {
    return {
      finalGroup: [{ value: 'ticketTypeId', label: '票种', prop: 'ticketTypeName' }],
      selectKeys: ['ticketTypeId', 'payChannel'],
      ticketStatusDic,
      ticketTypeList: [],
      oldTicketTypeOptions: [[]],
      oldTicketCateOptions: [[]],
      scenicList: [],
      ticketSpotList: [],
      groupKeys,
      form: {
        startDate: process.env.NODE_ENV === 'development' ? new Date('2021-10-31 00:00:00') : new Date(moment().startOf('day').format('YYYY-MM-DD HH:mm:ss')),
        endDate: new Date(moment().endOf('day').format('YYYY-MM-DD HH:mm:ss')),
        keyWords2: '', // 票种id
        keyWords4: '', // 景点
        keyWords5: '',
        keyWords6: '',
        keyWords7: '',
        keyWords8: '',
        keyWords9: '',
        keyWords11: '',
        keyWords13: 0,
        keyList1: [],
        keyList2: [],
        keyList3: [],
        keyList4: [],
        keyList5: [], // 渠道id
        keyList6: [],
        keyList7: [], // 售票员id
        keyList8: [],
        keyGroupBy: ['ticketTypeId', 'payChannel']
      },
      columns: [],
      tableData: [],
      loading: false,
      ticketTagList: [],
      OrderIndexArr: [],
      index: 0,
      tableIndex: 1
    }
  },
  created () {
    const searchParams = JSON.parse(sessionStorage.getItem('统计表-票种收入统计-查询条件'))
    if (searchParams) {
    // 如果存在查询条件，则设置到组件的数据中
      this.form = searchParams // 记住上次搜索条件
    }
    this.getTicketTypeList()
    this.getScenicList()
    this.getSaleStatistic()
    this.getTicketTagList()
    this.getTicketSpotList()
  },
  methods: {
    getTicketTagList () {
      getTicketTypeTagList({}).then(res => {
        this.ticketTagList = res.children
      })
    },
    getTicketSpotList () {
      return getTicketSpotList({
        pageNum: 1,
        pageSize: 10000
      }).then(res => {
        let list = res.list
        this.ticketSpotList = list
      })
    },
    selectAll (val) {
      let allValues = this.ticketTypeList.map(i => i.id)

      allValues.unshift(0) // 添加全部
      // 用来储存上一次的值，可以进行对比
      const oldVal = this.oldTicketTypeOptions.length === 1 ? [] : this.oldTicketTypeOptions[1]

      // 若是全部选择
      if (val.includes(0)) this.form.keyList1 = allValues

      // 取消全部选中  上次有 当前没有 表示取消全选
      if (oldVal.includes(0) && !val.includes(0)) this.form.keyList1 = []

      // 点击非全部选中  需要排除全部选中 以及 当前点击的选项
      // 新老数据都有全部选中
      if (oldVal.includes(0) && val.includes(0)) {
        const index = val.indexOf(0)
        val.splice(index, 1) // 排除全选选项
        this.form.keyList1 = val
      }

      // 全选未选 但是其他选项全部选上 则全选选上 上次和当前 都没有全选
      if (!oldVal.includes(0) && !val.includes(0)) {
        if (val.length === allValues.length - 1) this.form.keyList1 = [0].concat(val)
      }

      // 储存当前最后的结果 作为下次的老数据
      this.oldTicketTypeOptions[1] = this.form.keyList1
    },
    selectAllCate (val) {
      let allValues = this.ticketCategory.map(i => i.id)

      allValues.unshift(0) // 添加全部
      // 用来储存上一次的值，可以进行对比
      const oldVal = this.oldTicketCateOptions.length === 1 ? [] : this.oldTicketCateOptions[1]

      // 若是全部选择
      if (val.includes(0)) this.form.keyList3 = allValues

      // 取消全部选中  上次有 当前没有 表示取消全选
      if (oldVal.includes(0) && !val.includes(0)) this.form.keyList3 = []

      // 点击非全部选中  需要排除全部选中 以及 当前点击的选项
      // 新老数据都有全部选中
      if (oldVal.includes(0) && val.includes(0)) {
        const index = val.indexOf(0)
        val.splice(index, 1) // 排除全选选项
        this.form.keyList3 = val
      }

      // 全选未选 但是其他选项全部选上 则全选选上 上次和当前 都没有全选
      if (!oldVal.includes(0) && !val.includes(0)) {
        if (val.length === allValues.length - 1) this.form.keyList3 = [0].concat(val)
      }

      // 储存当前最后的结果 作为下次的老数据
      this.oldTicketCateOptions[1] = this.form.keyList3
    },
    reset () {
      this.$refs.form.resetFields()
    },
    reportExport () {
      exportOrderStatistics(this.form).then(() => {
        this.$message.success('导出成功。')

        this.goToDownload()
      }, () => {
        this.$message.success('导出失败。')
      })
    },
    // 获取票种列表
    getTicketTypeList () {
      return getTicketTypeList({
        pageNum: 1,
        pageSize: 999
      }).then(res => {
        this.ticketTypeList = res.list
      })
    },
    // 获取景点列表
    getScenicList () {
      return getScenic().then(res => {
        this.scenicList = res?.data.children.map(item => item.data)
      })
    },
    // 获取表格数据
    getSaleStatistic () {
      this.loading = true

      this.tableIndex++

      //   let groupArray = []
      //   let orderIndexArr = []

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

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

      getOrderStatistics(this.form).then(res => {
        const originData = res.data

        const payChannelArray = []
        const tableData = []

        originData.forEach(i => {
          const existType = tableData.find(t => t.ticketTypeName === i.ticketTypeName)
          if (!existType) {
            tableData.push({
              ticketTypeName: i.ticketTypeName,
              [i.payChannel || '空']: i.actual_price
            })
          } else {
            existType[i.payChannel || '空'] = i.actual_price
          }

          if (payChannelArray.indexOf(i.payChannel || '空') < 0 && i.payChannel !== '小计') {
            payChannelArray.push(i.payChannel || '空')
          }
        })

        this.tableData = tableData

        this.columns = payChannelArray.concat('小计')

        const realData = this.tableData.concat([]).slice(0, -1)
        const lastRow = this.tableData[this.tableData.length - 1]
        this.columns.forEach(col => {
          lastRow[col] = realData.reduce((i, v) => {
            return NP.plus(i, (v[col] || 0))
          }, 0)
        })
      }).finally(() => {
        this.loading = false
        sessionStorage.setItem('统计表-票种收入统计-查询条件', JSON.stringify(this.form)) // 下次记住
        // 目前不需要记忆selectKeys，因为现在分组的功能是注释了的
      })
    },
    totalRowClassName ({ row, rowIndex }) {
      for (let key in row) {
        if (row[key] === '小计') {
          return 'table-total-row table-total-row2'
        }
        if (row[key] === '总计') {
          return 'table-total-row'
        }
      }
    },
    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
                }
              }
            }
          }
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
