<!--
 * @Description: 财务管理 => 对账单
 * @Author: Rockery
 * @Date: 2021-07-28 15:14:06
 * @LastEditors: gcz
 * @LastEditTime: 2024-08-01 16:53:36
 * @FilePath: \great_webui\src\views\finance\Statements\StatementsIndex.vue
 * @Copyright: Copyright (c) 2016~2021 Rockery(1113269755@qq.com)
-->

<template>
  <div class="app-container app-container-scheduling">
    <div class="app-container_flex_auto">
      <div class="app-container_form app-container-queryform" v-show="showSearch">
        <!-- 页面查询表单 Start -->
        <el-form :model="queryParams" ref="queryForm" :rules="rules" :inline="true" label-width="68px">
          <el-form-item label="业务订单号" prop="orderNo" label-width="85px" v-if="queryShow.orderNo">
            <el-input v-model="queryParams.orderNo" placeholder="请输入业务单号" clearable size="small"
              @keyup.enter.native="handleQuery" />
            <span @click="clearQuery('orderNo')" class="query_clear"><i class="el-icon-circle-close"></i></span>
          </el-form-item>
          <el-form-item label="支付单号" prop="trackId" v-if="queryShow.trackId">
            <el-input v-model="queryParams.trackId" placeholder="请输入支付单号" clearable size="small"
              @keyup.enter.native="handleQuery" />
            <span @click="clearQuery('trackId')" class="query_clear"><i class="el-icon-circle-close"></i></span>
          </el-form-item>
          <el-form-item label="购票渠道" prop="source" v-if="queryShow.source">
            <el-select v-model="queryParams.source" placeholder="请选择购票渠道" clearable>
              <el-option v-for="dict in dict.type.order_form_type" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
            <span @click="clearQuery('source')" class="query_clear"><i class="el-icon-circle-close"></i></span>
          </el-form-item>
          <el-form-item label="支付时间" v-if="queryShow.dateRange">
            <el-date-picker v-model="queryParams.dateRange" size="small" style="width: 350px"
              value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="-" start-placeholder="开始时间"
              end-placeholder="结束时间"></el-date-picker>
            <span @click="clearQuery('dateRange')" class="query_clear"><i class="el-icon-circle-close"></i></span>
          </el-form-item>
          <el-form-item label="支付方式" prop="payWay" v-if="queryShow.payWay">
            <el-select v-model="queryParams.payWay" placeholder="请选择支付方式" clearable>
              <el-option v-for="dict in dict.type.pay_way_type" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
            <span @click="clearQuery('payWay')" class="query_clear"><i class="el-icon-circle-close"></i></span>
          </el-form-item>
          <el-form-item v-if="queryShow.performDate" label="场次时间" label-width="80px">
            <el-date-picker style="width: 250px;" v-model="queryParams.performDate" @change="pagePerformTimeListFun"
              type="daterange" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
            <span @click="clearQuery('performDate')" class="query_clear"><i class="el-icon-circle-close"></i></span>
          </el-form-item>
          <el-form-item label="场次" label-width="60px" v-if="!multiPerformDate && queryShow.performDate">
            <el-select v-model="queryParams.performTimeId" placeholder="场次" clearable style="width: 100%">
              <el-option v-for="dict in pagePerformTimeList" :key="dict.id"
                :label="dict.timeSnapshot + '(' + dict.performTimeStart + '-' + dict.performTimeEnd + ')'"
                :value="dict.id" />
            </el-select>
            <span @click="clearQuery('performDate')" class="query_clear"><i class="el-icon-circle-close"></i></span>
          </el-form-item>
          <el-form-item>
            <el-dropdown @command="openQuery">
              <el-button size="mini" type="primary" icon="el-icon-plus"></el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="orderNo">业务订单号</el-dropdown-item>
                <el-dropdown-item command="trackId">支付单号</el-dropdown-item>
                <el-dropdown-item command="source">购票渠道</el-dropdown-item>
                <el-dropdown-item command="payWay">支付方式</el-dropdown-item>
                <!-- <el-dropdown-item command="payType">交易类型</el-dropdown-item> -->
                <el-dropdown-item command="dateRange">支付时间</el-dropdown-item>
                <el-dropdown-item command="performDate">场次时间/场次</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-button style="margin-left: 10px;" 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>
        <!-- 页面查询表单 End -->
      </div>
      <div class="app-container_table app-container-main" :class="showSearch ? 'mt15' : ''">
        <!-- 页面批量操作按钮 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['financeMr:statements:StatementsIndexNew:download']" type="warning" plain
              icon="el-icon-download" size="mini" :disabled="tableDataList.length < 1" @click="handleExport"
              v-loading.fullscreen.lock="handleExportLoading" element-loading-text="正在拼命生成数据中..."
              element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.5)">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="initData"></right-toolbar>
        </el-row>

        <div class="app-container_table_main">
          <!-- 页面表格数据区域 Start -->
          <el-table 
            v-loading="loading" 
            ref="statementsTableRef" 
            :data="tableDataList" 
            border 
            row-key="orderNo" 
            class="cust-table"
            height="100%"
            >
              <el-table-column label="业务订单号" align="center" width="200" fixed="left">
                <template slot-scope="scope">
                  <div style="display: inline-block">{{ scope.row.id }}</div>
                </template>
              </el-table-column>
              <el-table-column label="支付单号" align="center" width="200" prop="paymentId" fixed="left" />
              <el-table-column label="银联单号" align="center" width="200" prop="trackId" fixed="left" />
              <el-table-column label="演出日期" align="center" width="200" prop="performDate" />
              <el-table-column label="演出时段" align="center" width="200" prop="performTime" />
              <el-table-column label="交易总额(元)" align="center" width="200" prop="orderPrice" />
              <el-table-column label="核销金额(元)" align="center" width="200" prop="usePriceTotal" />
              <el-table-column label="应到账金额(元)" align="center" width="200" prop="realPrice" />
              <el-table-column label="分销金额(元)" align="center" width="200" prop="retailPriceTotal" />
              <el-table-column label="费率(%)" align="center" width="200" prop="withdrawRate" />
              <el-table-column label="手续费(元)" align="center" width="200" prop="proceMoney" />
              <el-table-column label="退款金额(元)" align="center" width="200" prop="refundPriceTotal" />
              <el-table-column label="下单时间" align="center" width="200" prop="createTime" />
              <el-table-column label="支付时间" align="center" width="200" prop="payTime" />
              <el-table-column label="支付渠道" align="center" width="200" prop="payWay">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.pay_way_type" :value="scope.row.payWay" />
                </template>
              </el-table-column>
              <el-table-column label="提现状态" align="center" width="200" prop="orderWithdrawStatus">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.order_withdraw_status" :value="scope.row.orderWithdrawStatus" />
                </template>
              </el-table-column>
              <el-table-column label="提现金额(元)" align="center" width="200" prop="orderWithdrawRealPrice" />
              <el-table-column label="提现账户" align="center" width="200" prop="orderWithdrawAccount" />
              <el-table-column label="分销状态" align="center" width="200" prop="personWithdrawStatus">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.person_withdraw_status" :value="scope.row.personWithdrawStatus" />
                </template>
              </el-table-column>
              <el-table-column label="分销税率(%)" align="center" width="200" prop="personRetailRate" />
              <el-table-column label="分销提现金额(元)" align="center" width="200" prop="personWithdrawRealPrice" />
              <el-table-column label="分销账户" align="center" width="200" prop="personUnionMid" />
            </el-table>
            <!-- 页面表格数据区域 End -->
        </div>
      </div>
      <div class="app-container_table_page">
        <PaginationNew 
          :total="total" 
          :page.sync="queryParams.pageNum" 
          :limit.sync="queryParams.pageSize"
          @pagination="initData" />
      </div>
    </div>
  </div>
</template>

<script>
import { listStatements, exportStatements } from '@/api/financeMr/StatementsNew';
import { exportExcel } from '@/utils/exportexcel';
import { pagePerformTimeList } from "@/api/schedulingMr/schedulingMr"
import moment from "moment"
export default {
  name: 'Statements',
  dicts: ['order_form_type', 'pay_way_type', 'transaction_type', 'order_withdraw_status', 'person_withdraw_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 购票渠道格式化
      sourceOptions: [],
      // 支付渠道格式化
      payWayOptions: [],
      // 交易类型格式化
      tranTypeOptions: [],
      // 交易日期范围
      dateRange: [],
      rules: {},
      exportType: 1,
      // 总条数
      total: 0,
      // 表格数据
      tableDataList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: undefined,
        trackId: undefined,
        payWay: undefined,
        payType: undefined,
        source: undefined,
        performTimeId: undefined,
        performDate: [],
        dateRange: [],
      },
      queryShow: {
        orderNo: true,
        trackId: true,
        source: true,
        payWay: true,
        payType: true,
        dateRange: true,
        performDate: true,
      },
      oweTotalObj: {},
      // 导出数据状态
      handleExportLoading: false,
      summary: '',
      otherSummary: [],
      pagePerformTimeList: [],
      multiPerformDate: false,
    };
  },
  async created() {
    let params = this.$route.query
    console.log(this.$route)
    if (params && JSON.stringify(params) != '{}') {
      this.$set(this.queryParams, 'performDate', params.performDate ? [params.performDate, params.performDate] : [])
      if (params.performDate) {
        await this.pagePerformTimeListFun([params.performDate, params.performDate])
      }
      this.$set(this.queryParams, 'performTimeId', params.performTimeId ? params.performTimeId : '')
      this.$set(this.queryShow, 'performDate', true)
    } else {
      this.$set(this.queryParams, 'performDate', [moment().subtract(1, 'days').format("yyyy-MM-DD"), moment().subtract(1, 'days').format("yyyy-MM-DD")])
      if (this.queryParams.performDate) {
        await this.pagePerformTimeListFun(this.queryParams.performDate)
      }
    }
    this.initData();
  },
  methods: {
    /** 初始化数据 */
    async initData() {
      this.loading = true;
      // this.getRevenueReportOwetotal();
      this.getList();
    },
    /** 查询列表信息 */
    getList() {
      this.loading = true;
      listStatements(this.formatDateRange(this.queryParams, this.dateRange))
        .then((response) => {
          this.tableDataList = response?.data?.rows || [];
          this.total = response?.data?.total ?? 0;
          this.loading = false;
        })
        .catch(() => {
          this.tableDataList = [];
          this.total = 0;
          this.loading = false;
        });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.$refs?.['queryForm']?.validate?.((valid) => {
        if (valid) {
          this.loading = true;
          this.$refs.statementsTableRef?.clearSort?.();
          this.queryParams = {
            ...this.queryParams,
            pageNum: 1,
            sortField: undefined,
            sortOrder: undefined,
            payBeginTime: undefined,
            payEndTime: undefined
          };

          // 初始化表格数据
          this.tableDataList = [];
          this.total = 0;

          this.$nextTick(() => {
            // 重新加载表格数据
            this.initData();
          });
        }
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {}
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.handleQuery();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$confirm(`确定要导出对账明细的数据吗？`, '提示', {
        confirmButtonText: '确定 ',
        cancelButtonText: '取消 ',
        type: 'warning'
      })
        .then(() => {
          // 开启导出遮护罩
          this.handleExportLoading = true;

          // 排除不需要的属性
          let { pageNum, pageSize, ...otherObj } = this.formatDateRange(this.queryParams, this.dateRange);
          let handleExportReq = { ...otherObj };
          // 发送导出请求
          exportStatements(handleExportReq)
            .then((response) => {
              exportExcel(response, '对账明细_' + moment().format('yyyy_MM_DD'), '.xlsx');

              // 关闭导出遮护罩
              this.handleExportLoading = false;
            })
            .catch(() => {
              this.$message.error('导出异常！');
              // 关闭导出遮护罩
              this.handleExportLoading = false;
            });
        })
        .catch(() => {
          this.$message.info('您已取消导出！');
          // 关闭导出遮护罩
          this.handleExportLoading = false;
        });
    },
    /**
     * 格式参数数据
     */
    formatDateRange(params) {
      var search = JSON.parse(JSON.stringify(params));
      if (search.dateRange && search.dateRange.length > 0) {
        search['payBeginTime'] = search.dateRange[0];
        search['payEndTime'] = search.dateRange[1];
      } else {
        search['payBeginTime'] = undefined;
        search['payEndTime'] = undefined;
      }
      if (search.performDate && search.performDate.length > 0 && !search.performTimeId) {
        search['performStartDate'] = search.performDate[0];
        search['performEndDate'] = search.performDate[1];
      } else {
        search['performStartDate'] = undefined;
        search['performEndDate'] = undefined;
      }
      delete search.performDate
      delete search.dateRange
      return search;
    },
    /**
     * 当表格的排序条件发生变化的时候会触发该事件
     */
    handleSortChang({ column, prop, order }) {
      this.loading = true;
      this.queryParams = {
        ...this.queryParams,
        pageNum: 1,
        sortField: prop,
        sortOrder: order == 'descending' ? 'desc' : 'asc'
      };
      this.initData();
    },
    clearQuery(key) {
      this.$set(this.queryShow, key, false)
      this.$set(this.queryParams, key, '')
      if (key == 'performDate') {
        this.$set(this.queryParams, 'performTimeId', '')
      }
    },
    openQuery(key) {
      this.$set(this.queryShow, key, true)
    },
    async pagePerformTimeListFun(value) {
      // console.log('value',value);
      try {
        this.pagePerformTimeList = []
        this.$set(this.queryParams, 'performTimeId', null)
        if (!value) {
          return
        }
        if (value.length == 2 && value[0] == value[1]) {
          this.multiPerformDate = false
        } else {
          this.multiPerformDate = true
          return
        }
        let { data, code } = await pagePerformTimeList({
          performDate: value[0],
          pageNum: 1,
          pageSize: 999
        })
        this.pagePerformTimeList = [].concat(data.rows)
      } catch (error) {

      }
    },
  }
};
</script>

<style lang="scss" scoped>
::v-deep {
  .pagination-container {
    text-align: center;

    .el-pagination {
      position: initial;
    }
  }
}

.cust-table {
  .statements-column-orderNo {
    color: #337ab7;
    text-decoration: none;
    cursor: pointer;

    &:hover {
      color: #409eff;
      text-decoration: underline;
    }
  }
}

.statements-total {
  .til {
    font-weight: bold;
    margin-bottom: 2px;
    margin-top: 10px;
  }

  .summary {
    ::v-deep span {
      color: blue;
    }
  }

  .other-summary {
    ::v-deep span {
      color: #f5bb00;
    }
  }
}

.app-container-scheduling ::v-deep .el-select__tags {
  flex-wrap: inherit !important;
  overflow-x: auto !important;
}

.app-container-scheduling ::v-deep .el-form-item__content {
  position: relative;
}

.app-container-scheduling ::v-deep .el-form-item__content .query_clear {
  position: absolute;
  top: -15px;
  right: -10px;
  display: none;
  cursor: pointer;
  z-index: 99;
}

.app-container-scheduling ::v-deep .el-form-item__content:hover .query_clear {
  display: block;
}
</style>
