<template>
  <page-header-wrapper>
    <a-card>
      <JeepaySearchForm :searchFunc="searchFunc" :resetFunc="onReset">
        <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.mchExtNo" :placeholder="'商户名称/商户号'" />

        <jeepay-text-up v-model:value="vdata.searchData.ifCode" :placeholder="'支付通道'" />
        <jeepay-text-up v-model:value="vdata.searchData.isvNo" :placeholder="'渠道名称/渠道号'" />
        <jeepay-text-up v-model:value="vdata.searchData.appid" :placeholder="'应用名称/应用ID'" />
<!--        <jeepay-text-up v-model:value="vdata.searchData.nameAndNo" :placeholder="'结算姓名/结算卡号'" />-->
<!--        <a-form-item label="" class="table-search-item">-->
<!--          <a-select v-model:value="vdata.searchData.ifCode" placeholder="支付通道">-->
<!--            <a-select-option  v-for="item in vdata.payDefines" :key="item.ifCode" :value="item.ifCode">{{ item.ifName }}</a-select-option>-->
<!--          </a-select>-->
<!--        </a-form-item>-->
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="vdata.searchData.settleType" placeholder="结算类型">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="D0">D0</a-select-option>
            <a-select-option value="D1">D1</a-select-option>
            <a-select-option value="T1">T1</a-select-option>
<!--            <a-select-option value="4">定时结算</a-select-option>-->
          </a-select>
        </a-form-item>

        <a-form-item 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="-1">结算失败</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="5">退票</a-select-option>
            <a-select-option value="98">待查看</a-select-option>
            <a-select-option value="99">其他</a-select-option>
          </a-select>
        </a-form-item>
      </JeepaySearchForm>

      <!-- 列表渲染 -->

      <!--          :statisticsIsShow="$access('ENT_ORDER_COUNT')"-->
      <JeepayTable
          ref="infoTable"
          :initData="true"
          :reqTableDataFunc="reqTableDataFunc"
          :tableColumns="tableColumns"
          :searchData="vdata.searchData"
          rowKey="payOrderId"
          :tableRowCrossColor="true"
          :statisticsIsShow="true"
          :tableExportFunc="tableExportFunc"
          @btnLoadClose="vdata.btnLoading=false"
      >
        <template #statistics>
          <div class="statistics-list">
            <div v-for="(item, index) in orderCountList" :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 v-if="item.count >= 0" class="detail">
                <span>{{ item.count + '笔' }}</span>
              </div>
            </div>
          </div>
        </template>

        <template #headerCell="{ column }">
          <template v-if="column.key === 'settleType'">
            <Tooltip color="#3b4146">
              <template #title>
                <div style="color: #ffffff">提示内容</div>
              </template>
              <div style="cursor: pointer; width: 100%">
                结算类型
                <a-tooltip>
                  <template #title>
                    <p>T1：工作日次日到账，交易资金于周末和法定节假日次日的6点-12点自动结算至银行卡</p>
                    <p>D1：自然日次日到账，全年365天（不分节假日）的交易资金于自然日的次日6点-12点自动结算至银行卡</p>
                    <p>D0：实时到账，全年365天24小时（不分节假日）的交易资金笔笔实时秒到至银行卡，更放心更快捷</p>
                    <p>定时结算，在一天24个整点时辰，根据入账需求选择结算范围，可任意指定一个或多个结算时间点</p>
                  </template>
                  <question-circle-outlined style="padding-left: 10px"/>
                </a-tooltip>
              </div>
            </Tooltip>
          </template>
        </template>
        <template #bodyCell="{column,record}">
          <template v-if="column.key === 'appid'">
            <a-tooltip  class="my-tooltip" overlayClassName="tooltip-box-name">
              <template #title>
                <span>应用名称：{{record.appName}}</span><br>
                <span>应用ID：{{record.appid}}</span>
              </template>
              <div class="my-tooltip-title-box"> {{record.appName}}</div>
            </a-tooltip>
          </template>

          <template v-if="column.key === 'agentName'">
            <a-tooltip  class="my-tooltip" overlayClassName="tooltip-box-name">
              <template #title>
                <span>服务商名称：{{record.agentName}}</span><br>
                <span>服务商号：{{record.agentNo}}</span>
              </template>
              <div class="my-tooltip-title-box"> {{record.agentName}}</div>
            </a-tooltip>
          </template>
          <template v-if="column.key === 'mchUserName'">
            <a-tooltip  class="my-tooltip" overlayClassName="tooltip-box-name">
              <template #title>
                <span>用户名称：{{record.mchUserName}}</span><br>
                <span>用户手机号：{{record.mchUserPhone}}</span>
              </template>
              <div class="my-tooltip-title-box"> {{record.mchUserName}}</div>
            </a-tooltip>
          </template>
          <template v-if="column.key === 'mchName'">
            <a-tooltip  class="my-tooltip" overlayClassName="tooltip-box-name">
              <template #title>
                <span>商户名称：{{record.mchName}}</span><br>
                <span>商户号：{{record.mchExtNo}}</span>
              </template>
              <div class="my-tooltip-title-box"> {{record.mchName}}</div>
            </a-tooltip>
          </template>
          <template v-if="column.key === 'isvNo'">
            <a-tooltip  class="my-tooltip" overlayClassName="tooltip-box-name">
              <template #title>
                <span>渠道名称：{{record.isvName}}</span><br>
                <span>渠道号：{{record.isvNo}}</span>
              </template>
              <div class="my-tooltip-title-box"> {{record.isvName}}</div>
            </a-tooltip>
          </template>
          <template v-if="column.key == 'state'">
            <a-tag
                :key="record.state"
                :color="record.state === -1?'red':record.state === 1?'orange':record.state === 2?'green':record.state === 6?'':'volcano'"
            >
              {{ record.state === -1?'结算失败':record.state === 0?'待结算':record.state === 1?'结算中':record.state === 2?'结算成功':record.state === 3?'暂缓':record.state === 4?'冻结':record.state === 5?'退票':record.state === 98?'待查看':record.state === 99?'待查看':'--' }}

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


            <a-tooltip :title="record.remark" v-if="record.state == 98 && record.settleType == 'D0'">
              <question-circle-outlined  style="padding-left: 5px"/>
            </a-tooltip>
            <a-tooltip  v-if="record.state == -1" :title="record.remark">
              <info-circle-outlined style="font-size: 16px; padding-left: 5px;color: #FF0000"/>
            </a-tooltip>

<!--            <reload-outlined v-if="$access('ENT_SETTLE_SYNC') && record.state < 2"  @click="getReload(record)" style="color: #1890ff;margin-left: 5px"  />-->


          </template>
          <template v-if="column.key == 'accountName'">
            <!-- 操作列插槽 -->
<!--            <a-tooltip >-->
<!--              <template #title>-->
<!--                卡号：-->
<!--              </template>-->
<!--              -->
<!--            </a-tooltip>-->
            {{record.accountName}}<br>
            {{record.accountNo}}
          </template>
          <template v-if="column.key == 'settleAmt'">
            <!-- 操作列插槽 -->
            <a-tooltip >
              <template #title>
                <div v-if="record.state == 1 || record.state == 0">
                  <p>预付金额：数据同步中</p>
                  <p>交易手续费：数据同步中</p>
                  <p>垫资手续费：数据同步中</p>
                  <p>结算金额：数据同步中</p>
                </div>
                <div v-else>
                  <p>预付金额：{{(record.planAmt / 100).toFixed(2)}}</p>
                  <p>交易手续费：{{(record.fee / 100).toFixed(2)}}</p>
                  <p>垫资手续费：{{(record.cashFee / 100).toFixed(2)}}</p>
                  <p>结算金额：{{(record.settleAmt / 100).toFixed(2)}}</p>
                </div>
              </template>
              <b style="color: #1890ff">￥{{ (record.settleAmt / 100).toFixed(2)}} </b>
            </a-tooltip>
          </template>

          <template v-if="column.key == 'transactionAmount'">
            ￥{{ (record.transactionAmount / 100).toFixed(2)}}
          </template>
          <template v-if="column.key == 'fee'">
            ￥{{ (record.fee / 100).toFixed(2)}}
          </template>
          <template v-if="column.key == 'cashFee'">
            ￥{{ (record.cashFee / 100).toFixed(2)}}
          </template>
          <template v-if="column.key == 'settleName'">
            <!-- 操作列插槽 -->
             --
          </template>
          <template v-if="column.key == 'op'">
            <!-- 操作列插槽 -->

           </template>
        </template>
      </JeepayTable>
    </a-card>
  </page-header-wrapper>

</template>
<script lang="ts" setup>
import {
  API_URL_MCH_LIST,
  API_URL_PAY_ORDER_LIST,
  API_URL_PAYWAYS_LIST,
  req,
  $exportExcel,
  exportExcelUrl,
  $payOrderCount,
  API_MCH_PAY_SETTLE_LOG, API_MCH_PAY_DEFINES, $settleOrderCount, $getPayOrderRefresh, $getSettTypeSync
} from '@/api/manage'
import {ref, onMounted, reactive, getCurrentInstance} from 'vue'
import fileDownload from 'js-file-download'
import { message } from 'ant-design-vue'

// 获取全局函数
const { $hasMemberEnt,$access } = getCurrentInstance()!.appContext.config.globalProperties

const tableColumns = reactive([
  { key: 'mchUserName', title: '用户名称', dataIndex: 'mchUserName'},
  { key: 'agentName', title: '服务商名称', dataIndex: 'agentName' },
  { key: 'mchName', title: '商户名称', dataIndex: 'mchName' },
  { key: 'ifName', title: '支付通道', dataIndex: 'ifName',},
  { key: 'isvNo', title: '所属渠道', dataIndex: 'isvNo',},
  { key: 'appid', title: '应用名称', dataIndex: 'appid' },
  { key: 'accountName', title: '结算账户',fixed: "left", dataIndex: 'accountName', align: 'center'},
  // { key: 'transactionNumber', title: '成功交易笔数', dataIndex: 'transactionNumber', align: 'center'},
  // { key: 'transactionAmount', title: '成功交易金额', dataIndex: 'transactionAmount', align: 'center'},
  // { key: 'fee', title: '交易手续费', dataIndex: 'fee', align: 'center'},
  // { key: 'cashFee', title: '垫资手续费', dataIndex: 'cashFee', align: 'center'},
  { key: 'settleAmt', title: '结算金额(元)', dataIndex: 'settleAmt', align: 'center' },
  { key: 'settleType', title: '结算类型', dataIndex: 'settleType', align: 'center'},
  // { key: 'remark', title: '附言信息', dataIndex: 'remark' },
  { key: 'updatedAt', dataIndex: 'updatedAt', title: '结算日期' },
  // { key: 'createdAt', dataIndex: 'createdAt', title: '结算日期' },
  { key: 'state', title: '结算状态',fixed: "right",},
])

const infoTable = ref()
const dateRangePicker = ref()

const vdata = reactive({
  btnLoading: false,
  tableColumns: tableColumns,
  searchData: {queryDateRange: 'today'} as any,
  visible: false,
  detailData: {} as any,
  payWayList: [] as any,
  channelList:[] as any,
  payDefines: [] as any,
  orderKeyType: 'payOrderId'
})

onMounted(()=>{
  if ($access('ENT_PAY_ORDER_SEARCH_PAY_WAY')) {
    initPayWay()
  }
})

let orderCountList:any = ref([]) // 数据统计数组
let countDetailList: any = ref([]) // 数据统计明细数组
// 数据统计
const getOrderCount = () => {
  $settleOrderCount(vdata.searchData).then( res => {
    orderCountList.value = [
      {title: '成功交易金额',symbol: 'add', textColor: '#1A66FF', content: ((res.successAmount) / 100).toFixed(2), count: res.successAll},
      {type: 'line'},
      {title: '交易手续费',symbol: 'add',textColor: '#1A66FF', content: (res.feeAmount / 100).toFixed(2), count: res.feeAll},
      {type: 'line'},
      {title: '垫资手续费',symbol: 'add',textColor: '#1A66FF', content: (res.cashFeeAmount / 100).toFixed(2), count: res.cashFeeAll},
      {type: 'line'},
      {title: '结算金额', symbol: 'add',textColor: '#1A66FF', content: (res.allAmount / 100).toFixed(2), count: res.allSettle},
      {type: 'line'},
      {title: '待结算金额',symbol: 'add',textColor: '#1A66FF', content: (res.waitAmount / 100).toFixed(2), count: res.waitAll},
    ]
  })
}
getOrderCount() // 进入页面时调用一次
getChannelList()

payFefines();
//通道
function  payFefines() {
  req.list(API_MCH_PAY_DEFINES,{ 'pageSize': -1 }).then(res => {
    vdata.payDefines = res
  })
}

// 请求table接口数据
function reqTableDataFunc(params){
  return req.list(API_MCH_PAY_SETTLE_LOG, params)
}
function  searchFunc(){ // 点击【查询】按钮点击事件
  infoTable.value.refTable(true)
  getOrderCount() // 数据统计函数
}
// 打开退款弹出框
function  openFunc (record, recordId) {
  if (record.refundState === 2) {
    return message.error('订单无可退款金额')
  }
}
function  detailFunc(recordId) {

  req.getById(API_MCH_PAY_SETTLE_LOG, recordId).then(res => {
    vdata.detailData = res
  })
  vdata.visible = true
}
function  onClose () {
  vdata.visible = false
}
function  initPayWay () {
  req.list(API_URL_PAYWAYS_LIST, { 'pageSize': -1 }).then(res => { // 支付方式下拉列表
    vdata.payWayList = res.records
  })
}
function  changeStr2ellipsis (orderNo, baseLength) {
  const halfLengh = baseLength / 2
  return orderNo.substring(0, halfLengh - 1) + '...' + orderNo.substring(orderNo.length - halfLengh, orderNo.length)
}

function tableExportFunc(){
  return $exportExcel(exportExcelUrl.settleOrder as any, Object.assign({}, vdata.searchData, {'pageSize': -1})).then(res => {
    fileDownload(res.data, '结算订单列表.xlsx')
  }).catch ((error) =>{console.log(error)} )
}

function onReset(){
  //重置搜索内容
  dateRangePicker.value.returnSelectModel()
  vdata.searchData = { queryDateRange: 'today' }
}

function orderKeyTypeChangeFunc() {
  vdata.searchData.payOrderId = ''
  vdata.searchData.mchOrderNo = ''
  vdata.searchData.channelOrderNo = ''
  vdata.searchData.platformMchOrderNo = ''
  vdata.searchData.platformOrderNo = ''
}

function getChannelList(){
  // req.list(API_URL_MCH_APP, { 'pageSize': -1 }).then(res => { // 支付方式下拉列表
  //   vdata.channelList = res.records
  // })
}
function  getReload(data) {
  $getSettTypeSync(data.settleNo).then(res => {
    message.success('同步成功')
    infoTable.value.refTable(true)
  })
}

</script>
<style lang="less" scoped>

.order-list {
  -webkit-text-size-adjust:none;
  font-size: 12px;
  display: flex;
  flex-direction: column;

  p {
    white-space:nowrap;
    span {
      display: inline-block;
      font-weight: 800;
      height: 16px;
      line-height: 16px;
      width: 35px;
      border-radius: 5px;
      text-align: center;
      margin-right: 2px;
    }
  }
}
</style>
