
<template>
  <div>
    <a-card class="table-card">
      <JeepaySearchForm v-if="props.showSearch" :searchFunc="searchFunc" :resetFunc="resetFunc">
        <a-form-item label="" class="table-search-item">
          <JeepayDateRangePicker
              ref="dateRangePicker"
              v-model:value="vdata.searchData['queryDateRange']"
              customDateRangeType="dateTime"
          />
        </a-form-item>
        <jeepay-text-up v-model:value="vdata.searchData['mchUserName']" v-if="props.configMode != 'mch'" :placeholder="'用户号/名称/手机号'" />
        <jeepay-text-up v-model:value="vdata.searchData['unionOrderId']" :placeholder="'订单号'" />
        <jeepay-text-up v-model:value="vdata.searchData['accountName']" :placeholder="'账户名称/账户号'" />
        <jeepay-text-up v-model:value="vdata.searchData['appId']" :placeholder="'应用ID/应用名称'" />
        <jeepay-text-up v-model:value="vdata.searchData['accountNameFq']" :placeholder="'企业支付宝名称'" />
        <jeepay-text-up v-model:value="vdata.searchData['bookId']" :placeholder="'记账本ID'" />

        <a-form-item v-if="props.showAllSearch" label="" class="table-search-item">
          <a-select v-model:value="vdata.searchData['state']" placeholder="选择状态">
            <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="4">订单关闭</a-select-option>
            <!--            <a-select-option :value="9">代发待结算</a-select-option>-->
          </a-select>
        </a-form-item>
        <!--        <a-form-item v-if="props.showAllSearch" label="" class="table-search-item">-->
        <!--          <a-select v-model:value="vdata.searchData['state']" placeholder="来源">-->
        <!--            <a-select-option value="">全部</a-select-option>-->
        <!--            <a-select-option value="PLATFORM_WEB">运营平台系统</a-select-option>-->
        <!--            <a-select-option value="AGENT_WEB">服务商系统</a-select-option>-->
        <!--            <a-select-option value="AGENT_APP">{{ $SYS_NAME_MAP.AGENT_APP }}APP</a-select-option>-->
        <!--            <a-select-option value="AGENT_LITE">{{ $SYS_NAME_MAP.AGENT_APP }}小程序</a-select-option>-->
        <!--            <a-select-option value="MCH_WEB">商户系统</a-select-option>-->
        <!--            <a-select-option value="MCH_APP">{{ $SYS_NAME_MAP.MCH_APP }}APP</a-select-option>-->
        <!--            <a-select-option value="MCH_LITE">{{ $SYS_NAME_MAP.MCH_APP }}小程序</a-select-option>-->
        <!--          </a-select>-->
        <!--        </a-form-item>-->
      </JeepaySearchForm>
      <!-- 列表渲染 -->
      <JeepayTable
          ref="infoTable"
          :init-data="false"
          :statisticsIsShow="false"
          :tableExportFunc="tableExportFunc"
          :req-table-data-func="reqTableDataFunc"
          :table-columns="tableColumns"
          row-key="hid"
      >

        <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 #topBtnSlot>
          <div>
            <a-button    type="primary"   class="mg-b-30"  @click="addFunc"  >  <plus-outlined /> 发起结算  </a-button>
          </div>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'amount'">

            <a-popover placement="top" style="background: #0c2640 !important;">
              <template #content  style="background: #ff0 !important;">
                <p>实发金额：{{ (record.amount / 100).toFixed(2) }}</p>
                <p>垫资手续费：{{ (record.mchFeeAmount / 100).toFixed(2) }}</p>
              </template>
              <b style="color: #1890ff">{{ (record.amount/100).toFixed(2) }} </b>
            </a-popover>
          </template>
          <template v-if="column.key === 'accountName'">

            <a-tooltip  overlayClassName="tooltip-box-name">

              <template #title >
                <span>企业支付宝名称：{{record.accountName}}</span><br>
                <span>企业支付宝账号：{{record.accountNo}}</span><br>
              </template>
              <div  class="my-tooltip-title-box"> {{record.accountName}}</div>
            </a-tooltip>
          </template>
          <template v-if="column.key === 'originAccountName'">

            <div  class="my-tooltip-title-box" v-if="record.transferType == 1"> {{record.bookId}}</div>
          </template>
          <template v-if="column.key === 'state'">
            <a-tag
                :key="record.state"
                :color="record.state === 0?'blue':record.state === 1?'orange':record.state === 2?'green':record.state === 4?'red':'volcano'"
            >
              {{ record.state === 0?'代打款':record.state === 1?'转账中':record.state === 2?'转账成功':record.state === 3?'转账失败':record.state === 4?'订单关闭':record.state === 6?'订单关闭':'未知' }}
            </a-tag>

            <a-tooltip  :title="record.errMsg" v-if="record.state == 3">
              <info-circle-outlined style="color: #FF0000;margin-left: 5px"/>
            </a-tooltip>
          </template>

          <template v-if="column.key === 'accountType'">
            <div v-if="record.transferType == 0">
              <a-tag
                  :key="record.accountType"
                  :color="record.accountTypeState == 4?'red':record.accountTypeState == 2?'orange':record.accountTypeState === 3?'blue':record.accountTypeState === 1?'green':'volcano'"
              >
                {{record.accountTypeStateDesc}}
              </a-tag>
            </div>
            <div v-if="record.transferType == 1">
              <a-tag
                  :key="record.accountType"
                  :color="'volcano'"
              >
                充值
              </a-tag>
            </div>

          </template>

          <template v-if="column.key === 'applyPageType'">
            <span v-if="record.applyPageType == 'PLATFORM_WEB'">运营平台系统</span>
            <span v-else-if="record.applyPageType == 'AGENT_WEB'">服务商系统</span>
            <span v-else-if="record.applyPageType == 'AGENT_APP'">{{ $SYS_NAME_MAP.AGENT_APP }}APP</span>
            <span v-else-if="record.applyPageType == 'AGENT_LITE'">{{ $SYS_NAME_MAP.AGENT_APP }}小程序</span>
            <span v-else-if="record.applyPageType == 'MCH_WEB'">商户系统</span>
            <span v-else-if="record.applyPageType == 'MCH_APP'">{{ $SYS_NAME_MAP.MCH_APP }}APP</span>
            <span v-else-if="record.applyPageType == 'MCH_LITE'">{{ $SYS_NAME_MAP.MCH_APP }}小程序</span>
            <span v-else>{{ record.applyPageType || '' }}</span>
          </template>

          <template v-if="column.key === 'operation'">

            <a-button  type="link" v-if="record.transferType == 0 &&  record.state == 2 && !record.applicationFileId" @click="applicationFunc(record)">回单申请</a-button>
            <a-button  type="link" v-if="record.transferType == 0 && record.applicationFileId" @click="applicationDownloadFunc(record)">回单查询</a-button>
          </template>
        </template>
      </JeepayTable>
    </a-card>
  </div>



  <SybSettleAddOrEdit class="modal-div-box" :configMode="props.configMode" ref="sybSettleAddOrEditRef"  :callbackFunc="getCallbackFunc" />
</template>
<script setup lang="ts">

import {
  $exportExcel,
  API_URL_STATISTIC,
  exportExcelUrl,
  req,
  reqLoad,
  API_URL_PAY_AQF_ORDER_LIST, $getAqfApiTransPage, $getAqfApplicationForm, $getAqfApplicationFormDownload
} from '@/api/manage'
import {ref, reactive, defineProps, getCurrentInstance, onMounted, nextTick, defineExpose} from 'vue'
import fileDownload from "js-file-download";
import {message} from "ant-design-vue";
const { $infoBox,$access, $hasAgentEnt,$SYS_NAME_MAP } = getCurrentInstance()!.appContext.config.globalProperties

// 定义父组件的传值
const props = defineProps({
  transChannelMchNo:{ type: String, default: '' },
  configMode: { type: String, default: '' },   // 模式  mgr 运营端
  defaultQueryCondition: { type: Object, default: () => {}  }, // 查询集合的条件
  showSearch: { type: Boolean, default: true }, //是否显示搜索面板
  showAllSearch: { type: Boolean, default: true } //是否显示搜索面板上的所有内容,如果是false，仅显示日期和流水号
})

const infoTable = ref()

const sybSettleAddOrEditRef = ref()
let count:any = ref([]) // 数据统计数组
let tableColumns = reactive([
  { key: 'transferId', title: '订单号', fixed: 'left', dataIndex: 'transferId' },
  { key: 'accountName', title: '企业信息', dataIndex: 'accountName' },
  { key: 'originAccountName', title: '记账本信息', dataIndex: 'originAccountName' },
  { key: 'amount', title: '实发金额', dataIndex: 'amount' },
  { key: 'accountType', title: '转账方式', dataIndex: 'accountType' },
  { key: 'appName', title: '所属应用', dataIndex: 'appName' },
  { key: 'state', title: '状态', dataIndex: 'state' },
  { key: 'transferDesc', title: '备注', dataIndex: 'transferDesc' },
  // { key: 'applyPageType', title: '来源', dataIndex: 'applyPageType' },
  { key: 'createdAt', title: '创建日期', dataIndex: 'createdAt' },
  { key: 'operation', title: '操作',  fixed: 'right', align: 'center'}
])
const dateRangePicker = ref()
const vdata : any = reactive({
  searchData : { queryDateRange: 'today' },
  visible:false,
})
onMounted(() => {
  Object.assign(vdata.searchData, props.defaultQueryCondition)

  infoTable.value.refTable(true)
})

function resetFunc() {
  dateRangePicker.value.returnSelectModel()
  vdata.searchData = { queryDateRange: 'today', infoType: 'PLATFORM', opAccountType: 1 }
}

// 请求table接口数据
async function reqTableDataFunc(params: any) {
  // reqTableCountFunc(params)
  params.transfer_type = 1
  // params.transfer_type = 0
  let res =  await req.list(API_URL_PAY_AQF_ORDER_LIST, params)

  for (let i = 0; i < res.records.length; i++) {
    res.records[i].accountTypeState = 0;
    res.records[i].accountTypeStateDesc = '';
    if (res.records[i].accountType == 'C' && res.records[i].entryType == 'ZFB') {
      res.records[i].accountTypeState = 1;
      res.records[i].accountTypeStateDesc = '个人支付宝';
    } else if (res.records[i].accountType == 'B' && res.records[i].entryType == 'ZFB') {
      res.records[i].accountTypeState = 2;
      res.records[i].accountTypeStateDesc = '企业支付宝';
    } else if (res.records[i].accountType == 'C' && res.records[i].entryType == 'BANK') {
      res.records[i].accountTypeState = 3;
      res.records[i].accountTypeStateDesc = '个人银行卡';
    } else if (res.records[i].accountType == 'B' && res.records[i].entryType == 'BANK') {
      res.records[i].accountTypeState = 4;
      res.records[i].accountTypeStateDesc = '对公账户';
    }
  }
  return res
}
// 请求table接口数据
function reqTableCountFunc(params: any) {
  params.method = 'transaction'
  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)},
    ]
  })
}
function searchFunc () { // 点击【查询】按钮点击事件
  infoTable.value.refTable(true)
}
function tableExportFunc() {
  return $exportExcel(exportExcelUrl.statistic, Object.assign({}, vdata.searchData, {})).then(res => {
    fileDownload(res.data, '充值流水.xlsx')
  }).catch((error) => { console.log(error) })
}

function addFunc(){
  sybSettleAddOrEditRef.value.show()
}
function applicationFunc(record){
  $getAqfApplicationForm(record.transferId,record.transferSubjectIdFq).then((res) => {
    console.log(res,'res')
    infoTable.value.refTable(true)
  }).finally(() => {
  })
}
function applicationDownloadFunc(record){
  $getAqfApplicationFormDownload(record.transferId,record.transferSubjectIdFq).then((res) => {
    console.log(res,'res')
    switch (res.status){
      case "INIT":
        message.warning('初始化中')
        break;
      case "PROCESS":
        message.warning('处理中')
        break;
      case "FAIL":
        message.warning('初始化中')
        break;
    }
    if(res.status != 'SUCCESS'){
      return false;
    }
    console.log(res.download_url,'res.download_urlres.download_url')
    download(res.download_url)
    infoTable.value.refTable(true)
  }).finally(() => {
  })
}
function download(fileUrl){

  // 创建一个虚拟的 a 标签
  const link = document.createElement('a');
  link.href = fileUrl;
  link.target = '_blank'; // 在新窗口或标签页中打开
  link.download = 'filename'; // 下载的文件名，你可以根据需要更改

  // 将 a 标签添加到 DOM 中
  document.body.appendChild(link);

  // 模拟点击 a 标签，触发下载
  link.click();

  // 移除添加的 a 标签
  document.body.removeChild(link);
}
function getCallbackFunc(){

  infoTable.value.refTable(false)
}
function show(bookId){
  vdata.searchData.bookId = bookId
  searchFunc()
}
// 定义对外输出函数
defineExpose( { show, close } )
</script>
<style>

.modal-div-box{
  margin-top: -70px !important;

}
</style>
