<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="keyList12">
        <el-select
          v-model="form.keyList12"
          multiple
          collapse-tags
          filterable
          placeholder="请选择"
        >
          <el-option
            v-for="item in userScenic"
            :disabled="form.keyList12.length===1&&form.keyList12.includes(item.id)"
            :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="reset">
          重置
        </el-button>
        <el-button
          :disabled="loading"
          type="primary"
          @click="getSaleStatistic">
          搜索
        </el-button>
        <el-button
          type="primary"
          @click="reportExport">
          导出
        </el-button>
      </div>
    </el-form>

    <div class="table-box">
      <el-table
        border
        stripe
        :key="tableIndex"
        v-loading="loading"
        :data="tableData"
        :span-method="objectSpanMethod"
        :row-class-name="totalRowClassName">
        <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="partPrice"
          label="景点售票金额">
        </el-table-column>
        <el-table-column
          prop="cancel_partPrice"
          label="景点退票金额">
        </el-table-column>
        <el-table-column
          prop="actual_partPrice"
          label="景点实售金额">
        </el-table-column>
        <el-table-column
          prop="sum_count"
          label="售票张数">
        </el-table-column>
        <el-table-column
          prop="actual_count"
          label="实售张数">
        </el-table-column>
        <el-table-column
          prop="sum_cancel"
          label="退票张数">
        </el-table-column>
        <el-table-column
          prop="sum_people"
          label="售票人数">
        </el-table-column>
        <el-table-column
          prop="actual_people"
          label="实售人数">
        </el-table-column>
        <el-table-column
          prop="cancel_people"
          label="退票人数">
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { getScenic, getTicketTypeList } from '@/api/ticketType'
import { getOrderScenicSaleStatistics, exportOrderScenicSaleStatistics } from '@/api/order.js'
import { ticketStatusDic } from '@/assets/staticData'
import draggable from 'vuedraggable'
import moment from 'moment'

const groupKeys = [
  { value: 'ticketTypeName', label: '票种' },
  { value: 'scenic_name', label: '景点' },
  { 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: {
    draggable
  },
  data () {
    return {
      finalGroup: [{ value: 'ticketTypeName', label: '票种', prop: 'ticketTypeName' }],
      selectKeys: ['ticketTypeName'],
      ticketStatusDic,
      ticketTypeList: [],
      oldTicketTypeOptions: [[]],
      oldTicketCateOptions: [[]],
      scenicList: [],
      ticketSpotList: [],
      groupKeys,
      form: {
        startDate: 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')),
        keyGroupBy: ['ticketTypeName']
      },
      tableData: [],
      loading: false,
      ticketTagList: [],
      OrderIndexArr: [],
      index: 0,
      tableIndex: 1
    }
  },
  created () {
    this.getTicketTypeList()
    this.getScenicList()
    this.getSaleStatistic()
    this.form.keyList12 = this.userScenic.map(v => v.id)
  },
  mounted () { // 解决刷新不能赋值的情况
    setTimeout(() => {
      this.form.keyList12 = this.userScenic.map(v => v.id)
    }, 1000)
  },
  methods: {

    // 单元格颜色边框设置
    handleCellStyle ({ row, column, rowIndex, columnIndex }) {
      if (columnIndex > 4 && columnIndex <= 8) {
        if (columnIndex === 8) {
          return 'greenBg boldBorder'
        }
        return 'greenBg'
      }

      if (columnIndex > 8 && columnIndex <= 12) {
        if (columnIndex === 12) {
          return 'redBg boldBorder'
        }
        return 'redBg'
      }
      if (columnIndex === 4) {
        return 'boldBorder'
      }
    },
    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 () {
      exportOrderScenicSaleStatistics(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.tableData = []

      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)

      getOrderScenicSaleStatistics(this.form).then(res => {
        this.tableData = res?.data

        this.finalGroup.forEach(i => {
          groupArray.push({})
        })

        groupArray.forEach((group, index) => {
          const keyName = this.finalGroup[index].prop || this.finalGroup[index].value

          this.tableData.forEach((el, index) => {
            if (el[keyName] === '小计') {
              this.index++
            }

            !group[el[keyName] + '_' + this.index] && (group[el[keyName] + '_' + this.index] = [])
            group[el[keyName] + '_' + this.index].push(index)
          })

          const arr = []
          for (let k in group) {
            if (group[k].length > 1) {
              arr.push(group[k])
            }
          }
          orderIndexArr.push(arr)
        })

        this.OrderIndexArr = orderIndexArr
      }).finally(() => {
        this.loading = false
        sessionStorage.setItem('统计表-自定义售票统计-查询条件', JSON.stringify(this.form)) // 下次记住
        sessionStorage.setItem('统计表-自定义售票统计-查询条件-selectKeys', JSON.stringify(this.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>
@import './handOverStatistics/style.scss';
</style>
