<template>
  <page-header-wrapper>
    <a-card class="table-card">
      <JeepaySearchForm :searchFunc="searchFunc" :resetFunc="resetFunc">
        <a-form-item label="" class="table-search-item">
          <JeepayDateRangePicker
            v-if="vdata.showDateTimeRage"
            ref="dateRangePicker"
            v-model:value="vdata.searchData['queryDateRange']"
            customDateRangeType="date"
          />
        </a-form-item>
        <JeepaySelect ref="deviceTypeRef" placeholder="设备类型" :reset="isReset">
          <a-select v-model:value="vdata.searchData.deviceType" @change="deviceTypeRef.textupHandle()">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="0">电子码牌</a-select-option>
            <a-select-option value="1">实体码牌</a-select-option>
            <a-select-option value="2">实体立牌</a-select-option>
            <a-select-option value="3">云音响码牌</a-select-option>
            <a-select-option value="scan_pos">扫码POS</a-select-option>
            <a-select-option value="auto_pos">智能POS</a-select-option>
            <a-select-option value="cash_plugin">收银插件</a-select-option>
          </a-select>
        </JeepaySelect>
        <jeepay-text-up v-model:value="vdata.searchData.deviceNo" :placeholder="'设备号'" />
        <jeepay-text-up v-model:value="vdata.searchData.deviceName" :placeholder="'设备名称'" />
<!--        <jeepay-text-up v-model:value="vdata.searchData.storeId" :placeholder="'门店ID'" />-->
      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :init-data="false"
        :req-table-data-func="reqTableDataFunc"
        :table-columns="tableColumns"
        :search-data="vdata.searchData"
        row-key="ifCode"
        :statisticsIsShow="true"
        :tableExportFunc="tableExportFunc"
        @btnLoadClose="btnLoading=false"
        @handleTableChange="handleChange"
      >
        <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 === 'totalEntryAmt'">
            <b style="color: #15B86C;">￥{{ (record.totalEntryAmt / 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 === 'totalRefundAmt'">
            <b style="color: #15B86C;">￥{{ (record.totalRefundAmt / 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 === '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 === 'deviceType'">
            <a-tag v-if="record.deviceType != 'qr_code'" :color="record.deviceType == 'qr_code' ? '#2db7f5' : record.deviceType == 'scan_pos' ? '#87d068' : record.deviceType == 'auto_pos' ? '#531dab' : record.deviceType == 'cash_plugin' ? '#f50' : ''">
              {{ record.deviceType == 'qr_code' ? '码牌' : record.deviceType == 'scan_pos' ? '扫码POS' : record.deviceType == 'auto_pos' ? '智能POS' : record.deviceType == 'cash_plugin' ? '收银插件' : '其他' }}
            </a-tag>
            <a-tag v-else :color="record.deviceType == 'qr_code' ? '#2db7f5' : record.deviceType == 'scan_pos' ? '#87d068' : record.deviceType == 'auto_pos' ? '#531dab' : record.deviceType == 'cash_plugin' ? '#f50' : ''">
              {{ record.qrcType == 0 ? '电子码牌' : record.qrcType == 1 ? '实体码牌' : record.qrcType == 2 ? '实体立牌' : record.qrcType == 3 ? '云音响码牌' : '其他' }}
            </a-tag>
          </template>
        </template>
      </JeepayTable>
    </a-card>
  </page-header-wrapper>
</template>
<script setup lang="ts">

import { API_URL_STATISTIC, req, $exportExcel, exportExcelUrl } from '@/api/manage'
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import fileDownload from 'js-file-download'
import dateUtil from '@/utils/dateUtil.js'

const deviceTypeRef = ref()
const infoTable = ref()
let tableColumns = reactive([
  { key: 'deviceType', title: '设备类型', dataIndex: 'deviceType', },
  { key: 'deviceNo', title: '设备号', dataIndex: 'deviceNo', },
  { key: 'deviceName', title: '设备名称', dataIndex: 'deviceName',  },
  { 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', },
])

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

  const vdata : any = reactive({
    searchData: { method : 'device', queryDateRange: 'today', sortField: 'totalSuccAmt', sortOrder: 'descend' },
    showDateTimeRage: false
  })

  onMounted(() => {
    if(useRoute().query.queryDate) {
      vdata.searchData['queryDateRange'] = dateUtil.parseQueryStringByRange(useRoute().query.queryDate)
    }
    searchFunc()
    vdata.showDateTimeRage = true
  })

  function handleChange(sorter) {
    vdata.searchData['sortField'] = sorter.columnKey
    vdata.searchData['sortOrder'] = sorter.order
  }

  function resetFunc() {
    dateRangePicker.value.returnSelectModel()
    vdata.searchData = { method : 'device', queryDateRange: 'today', sortField: 'totalSuccAmt', sortOrder: 'descend' }
  }

  // 请求table接口数据
  function reqTableDataFunc(params: any) {
    params.method = 'device'
    
    if (!params.sortField) {
      params.sortField = 'totalSuccAmt'
      params.sortOrder = 'descend'
    }

    reqTableCountFunc(params)
    return req.list(API_URL_STATISTIC, params)
  }
  function searchFunc () { // 点击【查询】按钮点击事件
    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 tableExportFunc(){
    return $exportExcel(exportExcelUrl.statistic, Object.assign({}, vdata.searchData, {})).then(res => {
        fileDownload(res.data, '设备统计.xlsx')
    }).catch ((error) =>{console.log(error)} )
  }

  let isReset = ref(0) // 下拉搜索框是否重置

function onReset(){
  isReset.value++ // 下拉搜索框重置
  //重置搜索内容
  vdata.searchData = {}
}

</script>
