<!--
 * @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-queryform" v-show="showSearch">
      <!-- 页面查询表单 Start -->
      <el-form :model="queryParams" ref="queryForm" :rules="rules" :inline="true" label-width="68px">
        <el-form-item label="订单号" prop="orderNo" 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="支付方式" 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 label="交易类型" prop="payType" v-if="queryShow.payType">
          <el-select v-model="queryParams.payType" placeholder="请选择交易类型" clearable>
            <el-option
              v-for="dict in dict.type.transaction_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
          <span @click="clearQuery('payType')" 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="dateRange"
            size="small"
            style="width: 240px"
            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>
          <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-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-item>
          <el-button
            v-hasPermi="['financeMr:statements:query']"
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button
            v-hasPermi="['financeMr:statements:reset']"
            icon="el-icon-refresh"
            size="mini"
            @click="resetQuery"
            >重置</el-button
          >
        </el-form-item> -->
      </el-form>
      <!-- 页面查询表单 End -->
    </div>

    <div class="app-container-main" :class="showSearch ? 'mt15' : ''">
      <!-- 页面批量操作按钮 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <div style="border: 1px solid #dfe4ed;padding: 3px;">
            <span style="color: #ff4949">请选择导出账单记录类型：</span>
            <el-switch
              v-model="exportType"
              inactive-color="#ffba00"
              active-color="#13ce66"
              inactive-text="运营方"
              active-text="银联"
              inactive-value="1"
              active-value="2"
            ></el-switch>
          </div>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['financeMr:statements:export']"
            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>

      <el-row :gutter="10">
        <el-col :span="24">
          <!-- 页面表格数据区域 Start -->
          <el-table
            v-loading="loading"
            ref="statementsTableRef"
            :data="tableDataList"
            border
            lazy
            :load="load"
            row-key="id"
            @sort-change="handleSortChang"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            class="cust-table"
            height="400px"
          >
            <el-table-column label="订单号" align="center" :show-overflow-tooltip="true" width="200">
              <template slot-scope="scope">
                <template v-if="!scope.row.hasOwnProperty('children')">
                  <div
                    class="statements-column-orderNo"
                    @click="handleViewOrder(scope.row)"
                    style="display: inline-block"
                  >
                    {{ scope.row.orderNo }}
                  </div>
                </template>
                <template v-else>
                  <div style="display: inline-block">{{ scope.row.orderNo }}</div>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="支付单号" align="center" prop="trackId" :show-overflow-tooltip="true" />
            <el-table-column label="交易金额(元)" align="center" prop="payMoney" :show-overflow-tooltip="true" />
            <el-table-column label="手续费(元)" align="center" prop="proceMoney" :show-overflow-tooltip="true" />
            <el-table-column label="清算金额(元)" align="center" prop="clearMoney" :show-overflow-tooltip="true" />
            <el-table-column label="购票渠道" align="center" prop="source">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.order_form_type" :value="scope.row.source"/>
              </template>
            </el-table-column>
            <el-table-column label="支付方式" align="center" 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" prop="payType">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.transaction_type" :value="scope.row.payType"/>
              </template>
            </el-table-column>
            <el-table-column label="交易时间" align="center" prop="payTime" :show-overflow-tooltip="true" />
          </el-table>
          <!-- 页面表格数据区域 End -->
        </el-col>

        <el-col :span="24">
          <!-- 表格右下角数据 -->
          <div class="fl statements-total">
            <!-- <div class="til">账单数据汇总：</div> -->
            <div class="summary" v-html="summary"></div>
            <!-- <div class="til">明细如下：</div>
            <div class="other-summary" v-for="(item,index) in otherSummary" :key="index" v-html="item"></div> -->
          </div>
        </el-col>

        <el-col v-show="total > 0" :span="24" class="mb20">
          <!-- 页面分页控件 -->
          <pagination
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="initData"
          />
        </el-col>
      </el-row>
    </div>
      <!-- 详情 -->
      <details-dia ref="detailsDia" @getList="getList"></details-dia>
  </div>
</template>

<script>
import { listStatements, exportStatements, queryStatementsBillTotal } from '@/api/financeMr/Statements';
// import { indoorParkList } from '@/api/ParkingPointMgr/IndoorMgr';
import { exportExcel } from '@/utils/exportexcel';
import detailsDia from "../../order/orderMr/dialog/details";

export default {
  name: 'Statements',
  components: {
    detailsDia,
    'parkingrecord-pagination-select': () => import('@/components/CustPaginationSelect') // 支持分页搜索功能的[el-select]下拉框
  },
  dicts: ['order_form_type', 'pay_way_type','transaction_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 购票渠道格式化
      sourceOptions: [],
      // 支付渠道格式化
      payWayOptions: [],
      // 交易类型格式化
      tranTypeOptions: [],
      // 交易日期范围
      dateRange: [],
      rules: {
        orderNo: [
          {
            pattern: /^[+]{0,1}(\d+)$/,
            message: '订单号必须为纯数字',
            trigger: 'blur'
          }
        ],
        // trackId: [
        //   {
        //     pattern: /^[+]{0,1}(\d+)$/,
        //     message: '支付单号必须为纯数字',
        //     trigger: 'blur'
        //   }
        // ]
      },
      exportType: 1,
      exportTypeObj: {
        1: '运营方账单记录',
        2: '银联账单记录'
      },
      // 总条数
      total: 0,
      // 表格数据
      tableDataList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: undefined,
        trackId: undefined,
        payWay: undefined,
        payType: undefined,
        source: undefined,
      },
      queryShow: {
        orderNo: true,
        trackId: true,
        source: true,
        payWay: true,
        payType: false,
        dateRange: false,
      },
      oweTotalObj: {},
      // 导出数据状态
      handleExportLoading: false,
      summary:'',
      otherSummary:[],
    };
  },
  created() {
    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?.result?.rows|| [];
          this.total = response?.data?.result?.total ?? 0;
          this.summary = response?.data?.summary || '';
          this.otherSummary = response?.data?.otherSummary || [];
          this.loading = false;
        })
        .catch(() => {
          this.tableDataList = [];
          this.total = 0;
          this.loading = false;
        });
    },
    getRevenueReportOwetotal() {
      let { pageNum, pageSize, sortField, sortOrder, ...otherObj } = this.formatDateRange(
        this.queryParams,
        this.dateRange
      );
      queryStatementsBillTotal(otherObj).then((response) => {
        this.oweTotalObj = response?.data || {};
      });
    },
    /** 搜索按钮操作 */
    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.dateRange = [];
      this.resetForm('queryForm');
      this.handleQuery();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$confirm(`确定要导出“${this.exportTypeObj[this.exportType] || ''}”的数据吗？`, '提示', {
        confirmButtonText: '确定 ',
        cancelButtonText: '取消 ',
        type: 'warning'
      })
        .then(() => {
          // 开启导出遮护罩
          this.handleExportLoading = true;

          // 排除不需要的属性
          let { pageNum, pageSize, ...otherObj } = this.formatDateRange(this.queryParams, this.dateRange);
          let handleExportReq = { ...otherObj, exportType: this.exportType };
          // 发送导出请求
          exportStatements(handleExportReq)
            .then((response) => {
              exportExcel(response, this.exportTypeObj[this.exportType] || '', '.xlsx');

              // 关闭导出遮护罩
              this.handleExportLoading = false;
            })
            .catch(() => {
              this.$message.error('导出异常！');
              // 关闭导出遮护罩
              this.handleExportLoading = false;
            });
        })
        .catch(() => {
          this.$message.info('您已取消导出！');
          // 关闭导出遮护罩
          this.handleExportLoading = false;
        });
    },
    /**
     * 格式参数数据
     */
    formatDateRange(params, dateRange) {
      var search = params;
      if (null != dateRange && '' != dateRange) {
        search['payBeginTime'] = dateRange[0];
        search['payEndTime'] = dateRange[1];
      } else {
        search['payBeginTime'] = undefined;
        search['payEndTime'] = undefined;
      }

      return search;
    },
    /**
     * 当表格的排序条件发生变化的时候会触发该事件
     */
    handleSortChang({ column, prop, order }) {
      this.loading = true;
      this.queryParams = {
        ...this.queryParams,
        pageNum: 1,
        sortField: prop,
        sortOrder: order == 'descending' ? 'desc' : 'asc'
      };
      this.initData();
    },
    load(tree, treeNode, resolve) {
      console.log('tree',tree);
      resolve(tree.orderList);
    },
    /**
     * 查看原订单
     */
    handleViewOrder(row) {
      console.log('handleViewOrder row',row);
      this.$refs["detailsDia"].openDialog("详情", row);
      return
      // orderNo不存在
      if (!row?.orderNo) return;

      if (row.businessType != '2') {
        // 保存当前路由信息
        this.$store.dispatch('PushCurrRouteInfo', {
          name: 'OwnerinfoBillingDetails',
          metaTitle: `查看原订单【${row?.orderNo}】`,
          key: `OwnerinfoBillingDetails_${row?.orderNo}`
        });
        // 跳转详情页面
        if (Number(row.orderType) === 1) {
          this.$router.push(`/ownerinfobilling/details/${row?.orderNo}&type=parking`);
        } else {
          this.$router.push(`/ownerinfobilling/details/${row?.orderNo}`);
        }
      } else {
        // 保存当前路由信息
        this.$store.dispatch('PushCurrRouteInfo', {
          name: 'MonthlyVehicleDetails',
          metaTitle: `查看原订单【${row?.orderNo}】`,
          key: `MonthlyVehicleDetails_${row?.orderNo}`
        });

        // 跳转详情页面
        this.$router.push(`/monthlyvehicle/details/${row?.orderNo}`);
      }
    },
    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)
    }
  }
};
</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 {
  margin-top: 15px;
  .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>
