<template>
  <page-header-wrapper>
    <a-card class="table-card">
      <JeepaySearchForm :searchFunc="searchFunc" :resetFunc="resetFunc">
        <JeepayDateCascadeSelection 
          :date="vdata.searchData.queryDateRange" 
          :cycleType="vdata.cycleType" 
          @changeDate="changeDateHandle" 
          @changeDateType="changeDateTypeHandle" 
        />
        <JeepaySearchInfoInput
          v-if="$access('ENT_STATISTIC_MCH')"
          v-model:value="vdata.searchData.mchNo"
          placeholder="用户号"
          :textUpStyle="true"
          :mchNoAndName="true"
          showType="MCH"
        />
        <jeepay-text-up v-if="$access('ENT_STATISTIC_AGENT')" v-model:value="vdata.searchData['agentNo']" :placeholder="'服务商号'" />
        <jeepay-text-up v-if="$access('ENT_STATISTIC_ISV')" v-model:value="vdata.searchData['isvNo']" :placeholder="'服务商号'" />
      </JeepaySearchForm>
      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :init-data="true"
        :req-table-data-func="reqTableDataFunc"
        :table-columns="tableColumns"
        :search-data="vdata.searchData"
        row-key="groupDate"
        :statisticsIsShow="true"
        :tableExportFunc="tableExportFunc"
        @btnLoadClose="btnLoading=false"
      >
        <template #headerCell="{ column }">
          <span v-if="column.tooltipTitle">
            {{ column.title }}
            <a-tooltip :title="column.tooltipTitle"><info-circle-outlined /></a-tooltip>
          </span>
        </template>
        <template #topBtnSlot>
          <a-button type="primary" @click="tableExportFunc">
            <plus-outlined />导出表格
          </a-button>
        </template>
        <template #statistics>
          <div class="statistics-list">
            <div v-for="(item, index) in count" :key="index" class="item">
              <div v-if="item.type == 'line'" class="line" />
              <div class="title">{{ item.title }}</div>
              <div v-if="item.title" class="amount" :style="{color: item.textColor}">
                <span class="amount-num">{{ item.content }}</span>
              </div>
            </div>
          </div>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'totalSuccAmt'">
            <b style="color: #15B86C;">￥{{  (record.totalSuccAmt / 100).toFixed(2) }}</b>
          </template>
          <template v-if="column.key === 'totalFinalAmt'">
            <b style="color: #15B86C;">￥{{ (record.totalFinalAmt / 100).toFixed(2) }}</b>
          </template>
          <template v-if="column.key === 'totalEntryAmt'">
            <b style="color: #15B86C;">￥{{ (record.totalEntryAmt / 100).toFixed(2) }}</b>
          </template>
          <template v-if="column.key === 'totalFeeAmt'">
            <a-tooltip  overlayClassName="tooltip-box-name">
              <template #title>
                <span>收单手续费：￥{{ (record.totalFeeAmt / 100).toFixed(2) }}</span><br>
                <span>垫资手续费：￥{{ ( record.totalCashFee / 100).toFixed(2) }}</span>
              </template>
              <b style="color: #FF6848;">￥{{ ((record.totalFeeAmt + record.totalCashFee) / 100).toFixed(2) }}</b>
            </a-tooltip>
          </template>
          <template v-if="column.key === 'totalRefundAmt'">
            <b style="color: #15B86C;">￥{{ (record.totalRefundAmt / 100).toFixed(2)}}</b>
          </template>
          <template v-if="column.key === 'totalRefundFeeAmt'">
            <b style="color: #FF6848;">￥{{ (record.totalRefundFeeAmt / 100).toFixed(2) }}</b>
          </template>
          <template v-if="column.key === 'totalRefundNum'">
            <b style="color: #FF6848;">{{ record.totalRefundNum }}</b>
          </template>
          <template v-if="column.key === 'totalSuccNum'">
            <b style="color: #15B86C;">{{ record.totalSuccNum }}/{{ record.totalNum }}</b>
          </template>
          <template v-if="column.key === 'succRate'">
            <b style="color: #FF8800;">{{ record.succRate }}%</b>
          </template>
          <template v-if="column.key === 'operation'">
            <JeepayTableColumns>
              <a-button v-if="$access('ENT_STATISTIC_MCH')" type="link" @click="toPage('/statistic/mch', record.groupDate)">详情</a-button>
              <a-button v-if="$access('ENT_STATISTIC_AGENT')" type="link" @click="toPage('/statistic/agent', record.groupDate)">代理商详情</a-button>
              <a-button v-if="$access('ENT_STATISTIC_ISV')" type="link" @click="toPage('/statistic/isv', record.groupDate)">服务商详情</a-button>
              <a-button v-if="$access('ENT_STATISTIC_CHANNEL')" type="link" @click="toPage('/statistic/channel', record.groupDate)">通道详情</a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>
    </a-card>
  </page-header-wrapper>
</template>
<script setup lang="ts">

import { API_URL_STATISTIC, req, $exportExcel, exportExcelUrl } from '@/api/manage'
import JeepayDateCascadeSelection from './JeepayDateCascadeSelection.vue'
import router from '@/router'
import dateUtil from '@/utils/dateUtil.js'
import { message } from 'ant-design-vue'
import fileDownload from 'js-file-download'
import { ref, reactive, getCurrentInstance } from 'vue'
const { $infoBox, $access, $hasAgentEnt } = getCurrentInstance()!.appContext.config.globalProperties

const infoTable = ref()
let tableColumns = reactive([
  { key: 'groupDate', title: '日期', dataIndex: 'groupDate', agentEntCol: true, },
  { key: 'totalSuccAmt', title: '成交金额', tooltipTitle: '支付成功的订单金额，包含部分退款及全额退款的订单', dataIndex: 'totalSuccAmt', },
  { key: 'totalRefundAmt', title: '退款金额', dataIndex: 'totalRefundAmt'},
  { key: 'totalRefundNum', title: '退款笔数', tooltipTitle: '实际退款订单笔数，若一笔已成交订单退款多次，则计多次', dataIndex: 'totalRefundNum'},
  { key: 'totalFeeAmt', title: '手续费', tooltipTitle: '成交订单所产生的交易手续费和垫资手续费', dataIndex: 'totalFeeAmt'},
  { key: 'totalEntryAmt', title: '入账金额', tooltipTitle: '扣除已退款金额及手续费，入账金额为商户实际到账金额', dataIndex: 'totalEntryAmt'},
  { key: 'totalSuccNum', title: '成交笔数/总交易笔数', dataIndex: 'totalSuccNum', },
  { key: 'succRate', title: '成功率', tooltipTitle: '成交笔数与总订单笔数除得的百分比', dataIndex: 'succRate'},
  { key: 'operation', title: '操作', fixed: 'right', align: 'center', }
])

  let btnLoading = ref(false)
  let count:any = ref([]) // 数据统计数组

  const vdata : any = reactive({
    searchData: { method : 'transaction', queryDateType: 'day' }
  })

  // 请求table接口数据
  function reqTableDataFunc(params: any) {
    params.method = 'transaction'
    reqTableCountFunc(params)
    return req.list(API_URL_STATISTIC, params)
  }
  function searchFunc () { // 点击【查询】按钮点击事件
    if(vdata.searchData['queryDateType'] === 'day' && vdata.dateSpan && (vdata.dateSpan.days > 30 || vdata.dateSpan.months > 0)) {
      message.error('相隔天数最多为30天！')
    } else if(vdata.searchData['queryDateType'] === 'month' && vdata.dateSpan && (vdata.dateSpan.months > 12 || vdata.dateSpan.years > 0)) {
      message.error('相隔月数最多为12个月！')
    } else {
      infoTable.value.refTable(true)
    }
  }

  // 请求table接口数据
  function reqTableCountFunc(params: any) {
    req.list(API_URL_STATISTIC + '/total', params).then(res => {
    count.value = [
      {title: '总成交金额', symbol: 'add', textColor: '#1A66FF', content: ((res.totalSuccAmt) / 100).toFixed(2)},
      {type: 'line'},
      {title: '总成交笔数', content: (res.totalSuccNum)},
      {type: 'line'},
      {title: '总退款金额', symbol: 'sub', content: ((res.totalRefundAmt) / 100).toFixed(2)},
      {type: 'line'},
      {title: '总退款笔数', content: (res.totalRefundNum)},
      // {type: 'line'},
      // {title: '支付成功率', content: (res.succRate) + '%'},
      ]
    })
  }

  function resetFunc(){ 
    vdata.searchData = {} 
    vdata.cycleType = 'date'
  }

  function tableExportFunc(){
    return $exportExcel(exportExcelUrl.statistic, Object.assign({}, vdata.searchData, {})).then(res => {
        fileDownload(res.data, '交易报表.xlsx')
    }).catch ((error) =>{console.log(error)} )
  }

  function toPage(path, groupDate) {
    let queryString = dateUtil.getMonthRangeQueryString(groupDate)
    if(vdata.searchData.queryDateType === 'day') {
      queryString = dateUtil.getDayRangeQueryString(groupDate)
    } else if(vdata.searchData.queryDateType === 'month') {
      queryString = dateUtil.getMonthRangeQueryString(groupDate)
    } else {
      queryString = dateUtil.getYearRangeQueryString(groupDate)
    }
    router.push({
      path: path,
      query: { queryDate: queryString }
    })
  }

  function dateDiff(startDate, endDate) {
      let flag = [1, 3, 5, 7, 8, 10, 12, 4, 6, 9, 11, 2]
      let start = new Date(startDate)
      let end = new Date(endDate)
      let year = end.getFullYear() - start.getFullYear()
      let month = end.getMonth() - start.getMonth()
      let day = end.getDate() - start.getDate()

      if (month < 0) {
        year--
        month = end.getMonth() + (12 - start.getMonth())
      }

      if (day < 0) {
        month--
        let index = flag.findIndex((temp) => { return temp === start.getMonth() + 1 })
        let monthLength = 0
        if (index <= 6) {
          monthLength = 31
        } else if (index > 6 && index <= 10) {
          monthLength = 30
        } else {
          monthLength = 28
        }
        day = end.getDate() + (monthLength - start.getDate())
      }
      let result = { years: year, months: month, days: day }
      return result
  }

  // 时间选择
  function changeDateHandle(e) {
    vdata.dateSpan = dateDiff(e.startDate, e.endDate)
    vdata.dateObject = { startDate: e.startDate, endDate: e.endDate }

    if(vdata.searchData['queryDateType'] === 'day') {
      if(vdata.dateSpan.days > 30 || vdata.dateSpan.months > 0) {
        message.error('相隔天数最多为30天！')
      }
    } else if(vdata.searchData['queryDateType'] === 'month') {
      if(vdata.dateSpan.months > 12 || vdata.dateSpan.years > 0) {
        message.error('相隔月数最多为12个月！')
      }
    }
    vdata.searchData['queryDateRange'] = e.timeParams
  }
  // 周期选择
  function changeDateTypeHandle(e) {
    if(e === 'date') {
      vdata.searchData['queryDateType'] = 'day'
    } else {
      vdata.searchData['queryDateType'] = e
    }
    vdata['cycleType'] = e
  }
</script>
