<template>
    <div class="app-container">
      <el-row :gutter="20">
        <!--用户数据-->
        <el-col :span="24" :xs="24">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="时间" prop="time" label-width="40px">
                <el-date-picker
                v-model="queryParams.time"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                value-format="yyyy-MM-dd"
                end-placeholder="结束日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="订单来源" prop="ticketOrderSource">
                <el-select v-model="queryParams.ticketOrderSource" clearable placeholder="请选择订单来源">
                <el-option
                    v-for="dict in dict.type.ticket_order_source"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value">
                </el-option>
                </el-select>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
  
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                v-hasPermi="configPermi.export"
              >导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
          </el-row>
  
          <el-table v-loading="loading" border :data="tableList" :span-method="objectSpanMethod" @selection-change="handleSelectionChange">
            <el-table-column label="日期报表" align="center" key="reportDate" prop="reportDate" v-if="columns[0].visible" :show-overflow-tooltip="true" />
            <el-table-column label="订单来源" align="center" key="ticketOrderSourceName" prop="ticketOrderSourceName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
            <el-table-column label="订单张数(张)" align="center" key="orderBuyNum" prop="orderBuyNum" v-if="columns[2].visible" :show-overflow-tooltip="true" />
            <el-table-column label="订单人数(人)" align="center" key="totalPeopleNum" prop="totalPeopleNum" v-if="columns[3].visible" :show-overflow-tooltip="true" />
            <el-table-column label="销售金额(元)" align="center" key="orderPrice" prop="orderPrice" v-if="columns[4].visible" :show-overflow-tooltip="true" />
            <el-table-column label="验票金额(元)" align="center" key="usePrice" prop="usePrice" v-if="columns[5].visible" :show-overflow-tooltip="true" />
            <el-table-column label="退票人数(人)" align="center" key="backPeopleNum" prop="backPeopleNum" v-if="columns[6].visible" :show-overflow-tooltip="true" />
            <el-table-column label="退票金额(元)" align="center" key="backPrice" prop="backPrice" v-if="columns[7].visible" :show-overflow-tooltip="true" />
            <el-table-column label="实际销售金额(元)" align="center" key="realOrderPrice" prop="realOrderPrice" v-if="columns[8].visible" :show-overflow-tooltip="true" />
          </el-table>
  
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-col>
      </el-row>
    </div>
  </template>
  
  <script>
  import { 
    listTableApi, 
    delTableParamsApi, 
    addTableApi
  } from "@/api/CURD";
  import moment from "moment";
  export default {
    name: "ticketDailyReport",
    dicts: ['ticket_order_source'],
    data() {
      return {
        title: "票务日报表",// 通用标题
        configPermi: {
          export: ['statisticalReports:ticketDailyReport:export'],// 导出权限
        },
        configUrl: {
          list: '/merchant/reportTicket/daily', // 列表地址
          delect: '', // 删除地址
          upload: '',// 导入地址
          download:'', // 下载模板地址
          export: '/merchant/reportTicket/exportDailyXls',// 导出地址
          edit: '', // 编辑地址
        },
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 用户表格数据
        tableList: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        dateRange: [],
        // 控制列表是否显示
        columns: [
          { key: 0, label: `日期报表`, visible: true },
          { key: 1, label: `订单来源`, visible: true },
          { key: 2, label: `订单张数(张)`, visible: true },
          { key: 3, label: `订单人数(人)`, visible: true },
          { key: 4, label: `销售金额(元)`, visible: true },
          { key: 6, label: `验票金额(元)`, visible: true },
          { key: 7, label: `退票人数(人)`, visible: true },
          { key: 8, label: `退票金额(元)`, visible: true },
          { key: 9.5, label: `实际销售金额(元)`, visible: true },
        ],
        mergeObj: {}, // 用来记录需要合并行的下标
        mergeArr: ['reportDate'] // 表格中的列名
      };
    },
    created() {
      this.$set(this.queryParams,'time',[moment().format('yyyy-MM-DD'),moment().format('yyyy-MM-DD')])
      this.getList();
    },
    methods: {
      // 默认接受四个值 { 当前行的值, 当前列的值, 行的下标, 列的下标 }
      objectSpanMethod({ row, column, rowIndex, columnIndex }) {
          // 判断列的属性
          if(this.mergeArr.indexOf(column.property) !== -1) { 
              // 判断其值是不是为0 
              if(this.mergeObj[column.property][rowIndex]) { 
                  return [this.mergeObj[column.property][rowIndex], 1]
              } else {
                  // 如果为0则为需要合并的行
                  return [0, 0]; 
              }
          }
      },
      // getSpanArr方法
      getSpanArr(data) {
          this.mergeArr.forEach((key, index1) => {
              let count = 0; // 用来记录需要合并行的起始位置
              this.mergeObj[key] = []; // 记录每一列的合并信息
              data.forEach((item, index) => {
                  // index == 0表示数据为第一行，直接 push 一个 1
                  if(index === 0) {
                      this.mergeObj[key].push(1); 
                  } else {
                      // 判断当前行是否与上一行其值相等 如果相等 在 count 记录的位置其值 +1 表示当前行需要合并 并push 一个 0 作为占位
                      if(item[key] === data[index - 1][key]) { 
                          this.mergeObj[key][count] += 1;
                          this.mergeObj[key].push(0);
                      } else {
                          // 如果当前行和上一行其值不相等 
                          count = index; // 记录当前位置 
                          this.mergeObj[key].push(1); // 重新push 一个 1
                      }
                  }
              })
          })
      },
      /** 查询用户列表 */
      getList() {
        if(!this.queryParams.time || this.queryParams.time.length == 0){
          this.$modal.msgError(`请选择时间!!!`);
          this.tableList = []
          this.total = 0
          return
        }
        this.loading = true;
        let params = JSON.parse(JSON.stringify({
            ...this.queryParams,
            beginTime: this.queryParams.time&&this.queryParams.time[0]?this.queryParams.time[0]:null,
            endTime: this.queryParams.time&&this.queryParams.time[1]?this.queryParams.time[1]:null,
            ticketOrderSource: this.queryParams.ticketOrderSource ? this.queryParams.ticketOrderSource.join(','):''
        }))
        delete params.time;
        listTableApi(
          this.configUrl.list,
          this.addDateRange(
            params, 
            this.dateRange)).then(response => {
              this.tableList = response.rows;
              this.getSpanArr(this.tableList)
              this.total = response.total;
              this.loading = false;
          }
        ).catch (error=>{
          console.error('获取列表失败!!!!',error)
          this.tableList = [];
          this.total = 0;
          this.loading = false
        }) 
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
        }
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        if(this.$refs.addAndEdit) {
          this.$refs.addAndEdit.initData(this.title + '新增', "ADD",{})
        }
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        if(this.$refs.addAndEdit) {
          this.$refs.addAndEdit.initData(this.title + '编辑', "EDITInit",{...row})
        }
      },
      handleDetails(row){
        if(this.$refs.detailsBox) {
          this.$refs.detailsBox.initData(this.title + '详情',"DEATILSInit", row)
        }
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除数据项？').then( () => {
          return delTableParamsApi(this.configUrl.delect,{
            id: ids
          });
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch((e) => {
          console.error("删除失败====",e)
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        if(!this.queryParams.time || this.queryParams.time.length == 0){
          this.$modal.msgError(`请选择时间!!!`);
          return
        }
        let params = JSON.parse(JSON.stringify({
            ...this.queryParams,
            beginTime: this.queryParams.time&&this.queryParams.time[0]?this.queryParams.time[0]:null,
            endTime: this.queryParams.time&&this.queryParams.time[1]?this.queryParams.time[1]:null,
            ticketOrderSource: this.queryParams.ticketOrderSource ? this.queryParams.ticketOrderSource.join(','):''
        }))
        delete params.time;
        delete params.pageNum
        delete params.pageSize
        this.downloadGet(this.configUrl.export, {
          ...params
        }, `${this.title }_${new Date().getTime()}.xlsx`)
      },
      /** 导入按钮操作 */
      handleImport() {
        if(this.$refs.upload) {
          this.$refs.upload.initData({
            width: '400px',
            // 弹出层标题（用户导入）
            title: this.title + "导入",
            // 下载模板地址
            importTemplate: this.configUrl.download,
            // 上传的地址
            url: this.configUrl.upload
          })
        }
      },
      /** 开/闭 园 */
      openAttraction(row) {
        console.log("row======",row)
        this.$modal.confirm(`是否确认${row.status == 2 ? '关闭' : '打开'} ${row.name}景点吗？`).then( () => {
          return addTableApi(this.configUrl.edit,{
            ...row,
            status: row.status == 1 ? 2 : 1
          });
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess(`${row.status == 1 ? '打开' : '关闭'}成功`);
        }).catch((e) => {
          console.error("失败====",e)
        });
      },
    }
  };
  </script>
  