<template>
  <page-header-wrapper>
    <a-card>
      <JeepaySearchForm :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>
        <JeepaySearchInfoInput v-model:value="vdata.searchData['mchNo']" placeholder="用户号" :textUpStyle="true" :mchNoAndName="true" showType="MCH" />

        <!-- <jeepay-text-up v-model:value="vdata.searchData.receiverId" placeholder="分账接受者ID" /> -->
        <!-- <jeepay-text-up v-model:value="vdata.searchData.receiverGroupId" placeholder="分账账号组ID" /> -->
        <jeepay-text-up v-model:value="vdata.searchData.appId" placeholder="应用AppId" />
        <jeepay-text-up v-model:value="vdata.searchData.payOrderId" placeholder="支付订单号" />
        <jeepay-text-up v-model:value="vdata.searchData.accNo" placeholder="分账接收账号" />

        <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="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>
        </a-form-item>


        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="vdata.searchData.ifCode" placeholder="支付接口">
            <a-select-option value="">全部</a-select-option>
            <template v-for="(item) in vdata.ifCodeList" :key="item.ifCode">
              <a-select-option :value="item.ifCode">{{ item.ifName }}[{{ item.ifCode }}]</a-select-option>
            </template>
          </a-select>
        </a-form-item>
      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :initData="true"
        :reqTableDataFunc="reqTableDataFunc"
        :tableColumns="tableColumns"
        :searchData="vdata.searchData"
        :rowSelection="{ type: 'checkbox', selectedRowKeys: vdata.recordIdList, onChange: infoTableSelectChangeFunc }"
        rowKey="recordId"
        @btnLoadClose="vdata.btnLoading=false"
      >
        <template #topBtnSlot>
          <a-button v-if="$access('ENT_DIVISION_RECORD_RESEND')" type="primary" @click="resendBatchFunc"><redo-outlined />批量重新发起分账</a-button>
          <a-button v-if="$access('ENT_DIVISION_RECORD_RESEND')" type="primary" @click="finishBatchFunc"><redo-outlined />批量完结微信V3分账</a-button>
        </template>
        <template #bodyCell="{column,record}">
          <template v-if="column.key == 'calDivisionAmount'"><b>￥{{ record.calDivisionAmount/100 }}</b></template>

          <template v-if="column.key == 'ifCode'">
            <template v-for="(item) in vdata.ifCodeList" :key="item.ifCode">
              <label v-if="record.ifCode == item.ifCode">{{ item.ifName }}({{ item.ifCode }})</label>
            </template>
          </template>

          <template v-if="column.key == 'divisionRefundAmount'"><b>￥{{ record.refundAmount/100 }}</b></template>
          <template v-if="column.key == 'calRealAmount'"><b>￥{{ (record.calDivisionAmount - record.refundAmount)/100 }}</b></template>
          <template v-if="column.key == 'payOrderAmount'">￥{{ record.payOrderAmount/100 }}</template>
          <template v-if="column.key == 'state'">
            <a-tag v-if="record.state == 0" color="blue">待分账</a-tag>
            <a-tag v-if="record.state == 1" color="green">分账成功</a-tag>
            <a-tag v-if="record.state == 2" color="volcano">分账失败</a-tag>
            <a-tag v-if="record.state == 3" color="orange">分账处理中</a-tag>
            <a-tag v-if="record.state == 4" color="orange">分账已受理</a-tag>
          </template>
          <template v-if="column.key == 'op'">
            <!-- 操作列插槽 -->
            <a-button v-if="record.state == 2 && $access('ENT_DIVISION_RECORD_RESEND')" type="link" @click="redivFunc(record.recordId)">重试</a-button>
            <a-button v-if="$access('ENT_DIVISION_RECORD_VIEW')" type="link" @click="detailFunc(record.recordId)">详情</a-button>
          </template>
          <template v-if="column.key == 'payOrderDivisionAmount'">{{ (record.payOrderDivisionAmount / 100).toFixed(2) }}</template>
          <template v-if="column.key == 'divisionProfit'">{{ (record.divisionProfit * 100).toFixed(2) }}%</template>
        </template>
      </JeepayTable>
    </a-card>

    <Detail ref="recordDetail" />

    <ResendModal ref="resendModalRef" />
  </page-header-wrapper>
</template>
<script lang="ts" setup>
import { API_URL_PAY_ORDER_DIVISION_RECORD_LIST, req, API_URL_IFDEFINES_LIST, $finsihDivision } from '@/api/manage'
import Detail from './Detail.vue'
import ResendModal from './ResendModal.vue'
import { reactive, ref,getCurrentInstance, provide, onMounted } from 'vue'


const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties
// eslint-disable-next-line no-unused-vars

const tableColumns = reactive([
  { key: 'calDivisionAmount', title: '分账金额（首次）' },
  { key: 'divisionRefundAmount', title: '回退金额' },
  { key: 'calRealAmount', title: '实际入账金额' },
  { key: 'mchNo', title: '用户号', dataIndex: 'mchNo' },
  { key: 'mchName', title: '用户名称', dataIndex: 'mchName' },
  { key: 'batchOrderId', title: '分账批次号', dataIndex: 'batchOrderId', defaultHidden: true },
  { key: 'payOrderId', title: '支付订单号', dataIndex: 'payOrderId' },
  { key: 'ifCode', title: '支付接口' },
  { key: 'payOrderAmount', title: '订单金额' },
  { key: 'payOrderDivisionAmount', dataIndex: 'payOrderDivisionAmount', title: '分账基数', defaultHidden: true  },
  { key: 'receiverAlias', title: '账号别名', dataIndex: 'receiverAlias', defaultHidden: true },
  { key: 'accNo', title: '接收账号', dataIndex: 'accNo' },
  { key: 'accName', title: '账号姓名', dataIndex: 'accName' },
  { key: 'relationTypeName', title: '分账关系类型', dataIndex: 'relationTypeName', defaultHidden: true },
  { key: 'divisionProfit', dataIndex: 'divisionProfit', title: '分账比例'},
  { key: 'state', title: '分账状态', scopedSlots: { customRender: 'stateSlot' } },
  { key: 'createdAt', dataIndex: 'createdAt', title: '创建日期' },
  { key: 'op', title: '操作', width: '180px', fixed: 'right', align: 'center' }
])

    const recordDetail = ref()
    const resendModalRef = ref()
    const infoTable = ref()
    const dateRangePicker = ref()
    const vdata : any = reactive({
      btnLoading: false,
      searchData: { queryDateRange: 'today' } as any,
      visible:false,
      ifCodeList: [],
      recordIdList: [] as any, // 多选ID集合
    })

// 注入搜索函数
provide('searchFunc', searchFunc)


onMounted(() => {
  if($access('ENT_PC_IF_DEFINE_LIST')){
    req.list(API_URL_IFDEFINES_LIST, {state:1}).then((res) => {
        vdata.ifCodeList = res
      })
    }
})

function resetFunc() {
  dateRangePicker.value.returnSelectModel()
  vdata.searchData = { queryDateRange: 'today' }
}


// 请求table接口数据
function  reqTableDataFunc(params){
  return req.list(API_URL_PAY_ORDER_DIVISION_RECORD_LIST, params)
}
function  searchFunc() { // 点击【查询】按钮点击事件
  infoTable.value.refTable(true)
}
function  detailFunc (recordId) {
  recordDetail.value.show(recordId)
}

// 表格多选
function infoTableSelectChangeFunc(selectedRowKeys, selectedRows) {
  vdata.recordIdList = selectedRowKeys
  if (selectedRows && selectedRows.length > 0) {
    selectedRows.forEach(e => {
      if (e.state != 2) {
        $infoBox.message.warn('重新发起分账只针对分账失败的订单有效，建议通过筛选条件缩小范围，再批量重试分账')
        throw new Error('包含非分账失败状态的')
      }
    })
  }
}

// 重新发起分账
function redivFunc(recordId) {
  resendModalRef.value.show([recordId])
}

// 批量重试分账
function resendBatchFunc() {
  if (vdata.recordIdList.length <= 0) {
    $infoBox.message.error('请选择分账记录')
    return
  }

  resendModalRef.value.show(vdata.recordIdList)
}

// 批量完结分账
function finishBatchFunc() {
  if (vdata.recordIdList.length <= 0) {
    $infoBox.message.error('请选择分账记录')
    return
  }

  $infoBox.confirmDanger('确认调用完结分账？', '', () => {
    console.log(123)
    $finsihDivision(vdata.recordIdList.join(',')).then(res => {

      $infoBox.message.success('调用成功')
      if(searchFunc){
        searchFunc() 
      }

    }).finally(() => {
      vdata.btnLoading = false
    })
  })
}

</script>
