<template>
  <page-header-wrapper>
    <a-card>
      <JeepaySearchForm v-if="$access('ENT_UR_ROLE_SEARCH')" :searchConditionNum="6" :searchFunc="searchFunc" :resetFunc="() => { data.searchData= {} }">
        <a-form-item label="" class="table-search-item">
          <JeepayDateRangePicker ref="dateRangePicker" v-model:value="data.searchData['queryDateRange']" customDateRangeType="dateTime" />
        </a-form-item>
        <jeepay-text-up v-model:value="data.searchData['mchNo']" v-if="props.configMode != 'mch'" :placeholder="'用户号/名称/手机号'" />
        <jeepay-text-up v-model:value="data.searchData['applyId']" :placeholder="'商户名称/商户号'" />
        <jeepay-text-up v-model:value="data.searchData['storeId']" :placeholder="'门店名称/编号'" />
<!--        <jeepay-text-up v-model:value="data.searchData['routeId']" :placeholder="'策略名称/ID'" />-->
<!--        <a-form-item label="" class="table-search-item">-->
<!--          <a-select v-model:value="data.searchData['userType']" placeholder="状态">-->
<!--            <a-select-option value="">全部</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="4">对公账户</a-select-option>-->
<!--          </a-select>-->
<!--        </a-form-item>-->
      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable
          ref="infoTable"
          :init-data="true"
          :req-table-data-func="reqTableDataFunc"
          :statisticsIsShow="true"
          :tableExportFunc="tableExportFunc"
          :table-columns="tableColumns"
          :search-data="data.searchData"
          row-key="sysUserId"
          @btnLoadClose="data.btnLoading=false"
      >
        <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 === 'name'">
            <a-tooltip  class="my-tooltip" overlayClassName="tooltip-box-name">
              <template #title>
                <span>策略名称：{{record.name}}</span><br>
                <span>策略ID：{{record.routeId}}</span>
              </template>
              <div class="my-tooltip-title-box"> {{record.name}}</div>
            </a-tooltip>
          </template>
          <template v-if="column.key === 'applyId'">
            <a-tooltip  class="my-tooltip" overlayClassName="tooltip-box-name">
              <template #title>
                <span>商户名称：{{record.mchShortName}}</span><br>
                <span>商户号：{{record.applyId}}</span>
              </template>
              <div class="my-tooltip-title-box"> {{record.mchShortName}}</div>
            </a-tooltip>
          </template>
          <template v-if="column.key === 'storeId'">
            <a-tooltip  class="my-tooltip" overlayClassName="tooltip-box-name">
              <template #title>
                <span>门店名称：{{record.storeName}}</span><br>
                <span>门店编号：{{record.storeId}}</span>
              </template>
              <div class="my-tooltip-title-box"> {{record.storeName}}</div>
            </a-tooltip>
          </template>


          <template v-if="column.key === 'totalWxSuccAmt'">
<!--             <p>微信： {{  (record.totalWxSuccAmt / 100).toFixed(2) }} /  {{  (record.totalWxAmt / 100).toFixed(2) }} </p>-->
<!--             <p>支付宝： {{ (record.totalZfbSuccAmt / 100).toFixed(2) }} / {{  (record.totalZfbAmt / 100).toFixed(2) }} </p>-->
            <a-tooltip  class="my-tooltip" overlayClassName="tooltip-box-name">
              <template #title>
                <span>微信：{{  (record.totalWxSuccAmt / 100).toFixed(2) }} /  {{  (record.totalWxAmt / 100).toFixed(2) }} </span><br>
                <span>支付宝：{{ (record.totalZfbSuccAmt / 100).toFixed(2) }} / {{  (record.totalZfbAmt / 100).toFixed(2) }}</span>
              </template>
              <div class="my-tooltip-title-box" style="color: #15B86C;"><b>{{  (record.totalSuccAmt / 100).toFixed(2) }} / {{  (record.totalAmt / 100).toFixed(2) }}</b></div>

            </a-tooltip>
          </template>
          <template v-if="column.key === 'totalWxSuccNum'">
<!--            <p>微信：{{record.totalWxSuccNum}} / {{record.totalWxNum??0}}</p>-->
<!--            <p>支付宝：{{record.totalZfbSuccNum}} / {{record.totalZfbNum??0}}</p>-->
            <a-tooltip  class="my-tooltip" overlayClassName="tooltip-box-name">
              <template #title>
                <span>微信笔数：{{record.totalWxSuccNum}} / {{record.totalWxNum??0}}</span><br>
                <span>支付宝笔数：{{record.totalZfbSuccNum}} / {{record.totalZfbNum??0}}</span>
              </template>
              <div class="my-tooltip-title-box" style="color: #FF6848;"><b>{{  record.totalSuccNum }} / {{ record.totalNum }}</b></div>
            </a-tooltip>
          </template>
          <template v-if="column.key === 'succRate'">
<!--            <p>微信：{{record.wxRate}}</p>-->
<!--            <p>支付宝：{{record.zfbRate}}</p>-->
            <a-tooltip  class="my-tooltip" overlayClassName="tooltip-box-name">
              <template #title>
                <span>微信成功率：{{ record.wxRate }}%</span><br>
                <span>支付宝成功率：{{ record.zfbRate }}%</span>
              </template>
              <div class="my-tooltip-title-box" style="color: #FF8800;"><b>{{  record.succRate }}%</b></div>
            </a-tooltip>
          </template>
          <template v-if="column.key === 'op'">
            <!-- 操作列插槽 -->
            <JeepayTableColumns>
              <a-button  type="link" @click="storeFunc(record)">路由管理</a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>
    </a-card>


  </page-header-wrapper>
</template>
<script setup lang="ts">
import {
  API_URL_PAY_ORDER_ROUTE_DATA,
  req,
  reqLoad,
  $exportExcel,
  exportExcelUrl,
  API_URL_PAY_ORDER_ROUTE_DATA_COUNT
} from '@/api/manage'
import {reactive, ref, getCurrentInstance, onMounted} from 'vue'
import fileDownload from "js-file-download";
import {message} from "ant-design-vue";
import { useRouter, useRoute } from 'vue-router'
const router = useRouter() //这是全部路由

const props = defineProps({
  configMode: { type: String, default: '' },   // 模式
})

const { $infoBox, $access, $hasAgentEnt } = getCurrentInstance()!.appContext.config.globalProperties


const tableColumns = reactive([
  {key:'applyId', title: '商户信息',   dataIndex: 'applyId' },
  {key:'storeId', title: '门店信息', dataIndex: 'storeId' },
  {key:'name', title: '策略名称', dataIndex: 'name', },
  {key:'totalWxSuccAmt', title: '成交金额/总交易金额', tooltipTitle: '微信跟支付宝成功的金额', dataIndex: 'totalWxSuccAmt',align: 'center' },
  {key:'totalWxSuccNum', title: '成交笔数/总交易笔数', tooltipTitle: '微信跟支付宝成功的笔数', dataIndex: 'totalWxSuccNum',align: 'center' },
  {key:'succRate', title: '成功率', dataIndex: 'succRate',align: 'center' },
  {key:'createdAt', title: '时间', dataIndex: 'createdAt', },
  {key: 'op',title: '操作',   fixed: 'right',align: 'center' }
  // {key: 'op',title: '操作',   fixed: 'right',align: 'center' }
])

const infoTable = ref()

let data : any = reactive ({
  tableColumns: tableColumns,
  searchData: {queryDateRange: ""  } as any,
  btnLoading: false
})

let count:any = ref([]) // 数据统计数组
let vdata : any = reactive({
  storeList:[] as any,
  mchApplyList:[] as any,
  filteredMchApplyList:[] as any,
  filteredStoreInfoList:[] as any,
  saveObject:{} as any,
  userAddTitle:"",
  visible:false,
  showRechargeModal:false,
  rechargeModalLoading: false,  // loading
  rechargeObject: {}, // 预审核结果

  showPreRouteModal: false,  // 是否显示预审核弹层
  preRouteModalLoading: false,  // loading
  preRouteResult: {}, // 预审核结果
})

// 请求table接口数据
async function reqTableDataFunc(params){
  reqTableCountFunc(params)
  var res = await  req.list(API_URL_PAY_ORDER_ROUTE_DATA, params)
  for (var i=0;i<res.records.length;i++){
    res.records[i].wxRate = calculatePercentage(res.records[i].totalWxSuccNum,res.records[i].totalWxNum)
    res.records[i].zfbRate = calculatePercentage(res.records[i].totalZfbSuccNum,res.records[i].totalZfbNum)
  }
  return  res
}

function calculatePercentage(part, whole) {
  if (whole === 0) {
    return 0; // 避免除以零
  }
  let percentage = (part / whole) * 100;
  return Math.round(percentage); // 四舍五入
}
function reqTableCountFunc(params: any) {
  params.method = 'transaction'
  req.list(API_URL_PAY_ORDER_ROUTE_DATA_COUNT, 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)},
    ]
  })
}
function searchFunc() { // 点击【查询】按钮点击事件
  data.btnLoading = true // 打开查询按钮的loading
  infoTable.value.refTable(true)
}
onMounted(() => {

  if(useRoute().query.storeId !== undefined){
    data.searchData['storeId'] = useRoute().query.storeId
    setTimeout(()=>{
      searchFunc()
    },500)
  }

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


function storeFunc(record,type=0) { // 点击【查询】按钮点击事件
  router.push({
    path:'/tradeRouteList',
    query:{storeId:record.storeId}
  })

}
</script>
