<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="date" />
        </a-form-item>
        <jeepay-text-up v-model:value="vdata.searchData.batchNo" :placeholder="'对账批次号'" />
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="vdata.searchData.ifCode" placeholder="支付接口">
            <a-select-option value="">全部</a-select-option>
            <a-select-option v-for="item in vdata.ifCodeList" :key="item.ifCode" :value="item.ifCode">{{ item.ifName }}</a-select-option>
          </a-select>
        </a-form-item>
        <jeepay-text-up v-model:value="vdata.searchData.orderId" :placeholder="'订单号'" />
        <JeepaySelect ref="diffTypeRef" placeholder="差异类型" :reset="isReset">
          <a-select v-model:value="vdata.searchData.diffType" @change="diffTypeRef.textupHandle()">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="local">本地多帐</a-select-option>
            <a-select-option value="channel">渠道多帐</a-select-option>
            <a-select-option value="order">订单差异</a-select-option>
          </a-select>
        </JeepaySelect>
        <JeepaySelect ref="handleStateRef" placeholder="差异处理状态" :reset="isReset">
          <a-select v-model:value="vdata.searchData.handleState" @change="handleStateRef.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>
        </JeepaySelect>
      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :initData="false"
        :reqTableDataFunc="reqTableDataFunc"
        :tableColumns="tableColumns"
        :searchData="vdata.searchData"
        rowKey="id"
        @btnLoadClose="vdata.btnLoading=false"
      >
        <template #topBtnSlot>
          <a-button v-if="$access('ENT_MCH_INFO_ADD')" type="primary" @click="ignoreDiffFunc(null, 'filter')">
            <minus-outlined />根据筛选条件忽略差异
          </a-button>
        </template>
        
        <template #bodyCell="{column,record}">
          <template v-if="column.key == 'ifCode'">
            <span>{{ record.ifName + " (" + record.ifCode + ")" }}</span>
          </template>

          <template v-if="column.key == 'billType'">
            <a-badge :color="record.billType == 'pay'?'green':'geekblue'" :text="record.billType == 'pay'?'支付':'退款'" />
          </template>

          <template v-if="column.key == 'diffType'">
            <a-badge 
              :color="record.diffType == 'local'?'gold':record.diffType == 'channel'?'red':record.diffType == 'order'?'geekblue':'volcano'"
              :text="record.diffType == 'local'?'本地多帐':record.diffType == 'channel'?'渠道多帐':record.diffType == 'order'?'订单差异':'未知'"
            />
          </template>

          <template v-if="column.key === 'amountTemplate'">
            <div class="order-list">
              <div v-if="record.amount">
                <a-tag color="blue">平台</a-tag>
                <span>￥{{ (record.amount/100).toFixed(2) }}</span>
              </div>

              <div v-if="record.channelAmount" style="padding-top: 5px;">
                <a-tag color="purple">渠道</a-tag>
                <span>￥{{ (record.channelAmount/100).toFixed(2) }}</span>
              </div>
            </div>
          </template>

          <template v-if="column.key == 'state'">
            <div v-if="record.orderState">
              <a-tag :color="record.orderState === 0?'blue':record.orderState === 1?'orange':record.orderState === 2?'green':record.orderState===5?'geekblue':record.orderState === 6?'default':'volcano'">
                平台：{{ record.orderState === 0?'订单生成':record.orderState === 1?'支付中':record.orderState === 2?'支付成功':record.orderState === 3?'支付失败':record.orderState === 4?'已撤销':record.orderState === 5?'已退款':record.orderState === 6?'订单关闭':'未知' }}
              </a-tag>
            </div>

            <div v-if="record.channelState" style="padding-top: 5px;">
              <a-tag :color="record.channelState === 2 ? 'green' : record.channelState === 5 ? 'geekblue':'volcano'">
                渠道：{{ record.channelState === 2?'支付成功':record.channelState === 5?'退款成功':'未知' }}
              </a-tag>
            </div>
          </template>

          <template v-if="column.key == 'handleState'">
            <a-badge 
              :color="record.handleState==0?'red':record.handleState==1?'orange':record.handleState==2?'green':record.handleState==3?'geekblue':'purple'"
              :text="record.handleState==0?'未处理':record.handleState==1?'挂账':record.handleState==2?'已处理':record.handleState==3?'已忽略':'其他'"
            />
          </template>

          <!-- <template v-if="column.key === 'orderNo'">
            <div class="order-list">
              <div v-if="record.orderId">
                <a-tag color="blue">平台</a-tag>
                <span>{{ record.orderId }}</span>
              </div>
              <div v-if="record.channelOrderNo">
                <a-tag color="purple">渠道</a-tag>
                <span v-if="record.channelOrderNo.length > record.orderId.length">{{ changeStr2ellipsis(record.channelOrderNo, record.orderId.length) }}</span>
                <span v-else style="font-weight: normal;">{{ record.channelOrderNo }}</span>
              </div>
            </div>
          </template> -->

          <template v-if="column.key == 'op'">
            <!-- 操作列插槽 -->
            <a-button v-if="$access('ENT_CHECK_DIFF_VIEW')" type="link" @click="detailFunc(record.id)">详情</a-button>
            <a-button v-if="$access('ENT_CHECK_DIFF_REISSUE') && record.diffType=='channel' && record.isNeedReissue==1 && (record.handleState==0 || record.handleState==1)" type="link" @click="reissueFunc(record.id)">订单同步</a-button>
            <a-button v-if="$access('ENT_CHECK_DIFF_IGNORE') && (record.handleState==0 || record.handleState==1)" type="link" style="color: red;" @click="ignoreDiffFunc(record.id, 'single')">忽略</a-button>
          </template>
        </template>
      </JeepayTable>
    </a-card>
    
    <!-- 详情页面组件  -->
    <InfoDetail ref="infoDetail" />
    <!-- 补单页面组件  -->
    <ReissueDetail ref="reissueDetail" :callback-func="searchFunc" />
  </page-header-wrapper>
</template>
<script setup lang="ts">
import { API_URL_CHECK_DIFF_LIST, API_URL_IFDEFINES_LIST, req } from '@/api/manage'
import { reactive, ref, getCurrentInstance, onMounted } from 'vue'
import InfoDetail from './Detail.vue'
import ReissueDetail from './Reissue.vue'
import { useRoute } from 'vue-router'
const { $access,$infoBox } = getCurrentInstance()!.appContext.config.globalProperties

const tableColumns = reactive([
  { key: 'orderId', title: '订单号', dataIndex: 'orderId', minWidth: 160, width: 160, maxWidth: 220, fixed: 'left' },
  { key: 'ifCode', title: '支付接口', dataIndex: 'ifCode', width: 140, minWidth: 140, maxWidth: 170 },
  { key: 'diffType', title: '差异类型', width: 100, minWidth: 100, maxWidth: 150 },
  { key: 'billType', title: '账单类型', dataIndex: 'billType', width: 100, minWidth: 100, maxWidth: 250 },
  { key: 'state', title: '交易状态', dataIndex: 'channelState', width: 120, minWidth: 120, maxWidth: 250 },
  { key: 'amountTemplate', title: '交易金额', ellipsis: true, width: 108, minWidth: 108 },
  { key: 'handleState', title: '处理状态', width: 108, minWidth: 108 },
  { key: 'batchNo', title: '对账批次号', dataIndex: 'batchNo', width: 200, minWidth: 200, maxWidth: 240},
  // { key: 'createdAt', title: '创建时间', dataIndex: 'createdAt', width: 180, minWidth: 180, maxWidth: 230 },
  { key: 'op', title: '操作', width: '160px', fixed: 'right', align: 'center' }
])

const infoTable = ref()
const diffTypeRef = ref()
const handleStateRef = ref()
const infoDetail = ref()
const reissueDetail = ref()
const dateRangePicker = ref()

onMounted(() => {
  vdata.searchData.batchNo = useRoute().query.batchNo
  if (vdata.searchData.batchNo) {
    vdata.searchData.queryDateRange = ''
  }

  searchFunc()

  req.list(API_URL_IFDEFINES_LIST, { 'state': 1, 'isSupportCheckBill': 1 }).then(res => { // 通道下拉选择列表
    vdata.ifCodeList = res
  })
})

const vdata = reactive ({
  ifCodeList: [] as any,
  tableColumns: tableColumns,
  searchData: {queryDateRange: 'yesterday'} as any,
  btnLoading: false
})

// 请求table接口数据
function reqTableDataFunc(params){
  return req.list(API_URL_CHECK_DIFF_LIST, params)
}

function searchFunc () { // 点击【查询】按钮点击事件
  vdata.btnLoading = true // 打开查询按钮上的loading
  infoTable.value.refTable(true)
}

function detailFunc(recordId) { // 业务通用【详情】 函数
  infoDetail.value.show(recordId)
}
function reissueFunc(recordId) { // 补单
  reissueDetail.value.show(recordId)
}
function ignoreDiffFunc(recordId, ignoreType) { // 忽略
  vdata.searchData.ignoreType = ignoreType

  $infoBox.confirmDanger('确定忽略账单差异？', '', () => {
    req.updateById(API_URL_CHECK_DIFF_LIST + '/ignore', ignoreType == 'single' ? recordId : -99, vdata.searchData).then(res => {
      infoTable.value.refTable(true)
      $infoBox.message.success('操作成功！')
    })
  })
}

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

function onReset(){
  isReset.value++ // 下拉搜索框重置
  //重置搜索内容
  dateRangePicker.value.returnSelectModel()
  vdata.searchData = { queryDateRange: 'yesterday' }
}

</script>
