<template>
  <page-header-wrapper>
    <a-card class="table-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-if="$hasAgentEnt()" v-model:value="vdata.searchData.rid" :placeholder="'申请单号'" />
        <jeepay-text-up v-if="$hasAgentEnt()" v-model:value="vdata.searchData.infoId" :placeholder="'服务商号'" />
        <jeepay-text-up v-model:value="vdata.searchData.infoName" :placeholder="'服务商名称'" />
        <a-form-item label="" class="table-search-item">
          <!--结算状态: 1-审核中, 2-审核失败, 3-结算中, 4-结算成功, 5-结算失败-->
          <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="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>
        </a-form-item>
      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :initData="true"
        :req-table-data-func="reqTableDataFunc"
        :table-columns="tableColumns"
        :search-data="vdata.searchData"
        rowKey="rid"
        :statisticsIsShow="$access('ENT_PROFIT_CASHOUT_RECORD_COUNT')"
        :tableExportFunc="tableExportFunc"
        @btnLoadClose="vdata.btnLoading=false"
      >
        <template #statistics>
          <div class="statistics-list">
            <div v-for="(item, index) in tableCount" :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>
                <span v-if="item.isAmount">元</span>
              </div>
            </div>
          </div>
        </template>
        <template #bodyCell="{ column, record }">
          <!-- 提现类型 --> 
          <template v-if="column.key === 'settType'">
            <a-tag v-if="record.settType == 1" color="pink">佣金提现</a-tag>
          </template>

          <!-- 申请用户 --> 
          <template v-if="column.key === 'infoName'">
            {{ record.infoName }}({{ record.infoId }})
          </template>

          
          <!-- 手续费 --> 
          <template v-if="column.key === 'settFeeAmount'">
            <a-popover placement="top">
              <template #title> <b>￥手续费</b></template>
              <template #content>
                提现手续费： {{ '￥' + (record.settFeeAmount / 100).toFixed(2) }} <br>
                <template v-if="typeof record.transferPlatformMchfeeAmount == 'number'">结算手续费： {{ '￥' + (record.transferPlatformMchfeeAmount / 100).toFixed(2) }} <br></template>
                <template v-if="typeof record.transferPlatformCostAmount == 'number'">实际成本： {{ '￥' + (record.transferPlatformCostAmount / 100).toFixed(2) }} <br></template>
              </template>
              {{ '￥' + (record.settFeeAmount / 100).toFixed(2) }}
            </a-popover>
          </template>
          

          <!-- 所属系统 --> 
          <!-- <template v-if="column.key === 'infoType'">
            <span v-if="record.infoType == 'AGENT'">代理商</span>
          </template> -->

          <!-- 结算账户类型 --> 
          <template v-if="column.key === 'settAccountType'">
            <span v-if="record.settAccountType == 'WX_CASH'">个人微信</span>
            <span v-if="record.settAccountType == 'ALIPAY_CASH'">个人支付宝</span>
            <span v-if="record.settAccountType == 'BANK_CARD'">银行卡</span>
            <span v-if="record.settAccountType == 'BANK_PUBLIC'">对公</span>
            <span v-if="record.settAccountType == 'BANK_PRIVATE'">对私</span>
          </template>

          <!-- 状态 --> 
          <template v-if="column.key === 'state'">
            <a-tag v-if="record.state == 1" color="orange">审核中</a-tag>
            <a-tag v-if="record.state == 2" color="red">审核失败</a-tag>
            <a-tag v-if="record.state == 3" color="purple">结算中</a-tag>
            <a-tag v-if="record.state == 4" color="green">结算成功</a-tag>
            <a-tag v-if="record.state == 5" color="red">结算失败</a-tag>
          </template>

          <!-- 结算状态: 1-审核中, 2-审核失败, 3-结算中, 4-结算成功, 5-结算失败 -->
          <template v-if="column.key === 'operation'">
            <a-button v-if="$access('ENT_PROFIT_CASHOUT_RECORD_VIEW')" type="link" @click="detailFunc(record.rid)">详情</a-button>
            <a-button v-if="$access('ENT_PROFIT_CASHOUT_RECORD_AUDIT') && record.state == 1" type="link" @click="showAuditModalFunc(record.rid, record)">审核</a-button>
            <!-- 不存在转账应用 && 结算中  那么需要人工处理 -->
            <a-button v-if="$access('ENT_PROFIT_CASHOUT_RECORD_AUDIT') && (!record.transferMchAppId && record.state == 3)" type="link" @click="showProcessModalFunc(record.rid, record)">结算</a-button>
          </template>
        </template>
      </jeepaytable>
    </a-card>

    <!-- 详情页的组件 -->
    <InfoDetail ref="infoDetail" />


    <!-- 审核 弹层 -->
    <a-modal v-model:visible="vdata.showAuditModal" title="提现单审核" width="50%">
      <a-form layout="vertical">
        <a-descriptions title="" :column="{sm:2}" bordered>
          <a-descriptions-item label="结算金额" :span="2"> <b style="color: #0541f3">￥{{ vdata.detailData.settAmount/100 }}</b> </a-descriptions-item>
          <a-descriptions-item label="申请金额"> ￥{{ vdata.detailData.applyAmount/100 }}</a-descriptions-item>
          <a-descriptions-item label="手续费"> ￥{{ vdata.detailData.settFeeAmount/100 }}</a-descriptions-item>
          <a-descriptions-item label="手续费规则" :span="2"> {{ vdata.detailData.settFeeRule }}</a-descriptions-item>
          <a-descriptions-item label="申请单号">{{ vdata.detailData.rid }}</a-descriptions-item>
          <a-descriptions-item label="服务商号">{{ vdata.detailData.infoId }}</a-descriptions-item>
          <a-descriptions-item label="结算账户类型">
            <span v-if="vdata.detailData.settAccountType == 'WX_CASH'">微信零钱</span>
            <span v-if="vdata.detailData.settAccountType == 'ALIPAY_CASH'">支付宝转账</span>
            <span v-if="vdata.detailData.settAccountType == 'BANK_CARD'">银行卡</span>
          </a-descriptions-item>
          <a-descriptions-item label="结算账户账号">{{ vdata.detailData['settAccountNo'] }}</a-descriptions-item>
          <a-descriptions-item label="结算账户姓名">{{ vdata.detailData['settAccountName'] }}</a-descriptions-item>
          <a-descriptions-item label="结算账户联系人手机号">{{ vdata.detailData['settAccountTelphone'] }}</a-descriptions-item>
          <a-descriptions-item v-if="vdata.detailData['settAccountBank']" label="结算账户开户行名称" :span="2">{{ vdata.detailData['settAccountBank'] }}</a-descriptions-item>
          <a-descriptions-item v-if="vdata.detailData['settAccountSubBank']" label="结算账户开户行支行" :span="2">{{ vdata.detailData['settAccountSubBank'] }}</a-descriptions-item>


          <!-- <a-descriptions-item label="投诉次数">2019-04-24 18:00:00</a-descriptions-item>
          <a-descriptions-item label="投诉时间">2019-04-24 18:00:00</a-descriptions-item> -->
          <a-descriptions-item v-if="vdata.detailData['applyRemark']" label="用户提现备注" :span="2">{{ vdata.detailData['applyRemark'] }}</a-descriptions-item>
          <a-descriptions-item v-if="vdata.detailData['settCertImg']" label="申请资料" :span="2">
            <a-image v-if="vdata.detailData['settCertImg']" style="max-width: 200px;" class="img" :src="vdata.detailData['settCertImg']" />
          </a-descriptions-item>
        </a-descriptions>

        <a-divider orientation="left" :orientationMargin="0"><b>处理审核</b></a-divider>

        <div style="display: flex;">
          <div style="width: 50%;">
            <a-form-item required="true" label="审核结果：">
              <a-radio-group v-model:value="vdata.auditResult.state">
                <a-radio :value="3">审核通过</a-radio>
                <a-radio :value="2">审核驳回</a-radio>
                <!-- 
            <a-radio :value="4">结算成功（扣除钱包金额）</a-radio>
            <a-form-item v-if="vdata.auditResult.state == 4" label="打款凭证" name="transferCertImg">
              <JeepayUpload v-model:src="vdata.auditResult.transferCertImg" bizType="avatar" />
            </a-form-item>
            <a-radio :value="5">结算失败（恢复钱包金额）</a-radio>
             -->
              </a-radio-group>
            </a-form-item>

            <a-form-item v-if="vdata.auditResult.state == 2 || vdata.auditResult.state == 5" label="驳回原因：">
              <a-textarea v-model:value="vdata.auditResult.auditRemark" :rows="3" />
            </a-form-item>

            <a-form-item v-if="vdata.auditResult.state == 3 && vdata.auditResult.pageSettAppIdOrAuditSelectedVal == 'appId'" style="width: 70%;" required="true" label="选择应用：">
              <a-select v-model:value="vdata.auditResult.transferMchAppId" class="form-item-content" placeholder="选择应用" @change="changeTransferMchAppIdFunc">
                <a-select-option key="">请选择商户应用</a-select-option>
                <a-select-option v-for="(item) in vdata.platformSelfMchNoAppInfoList" :key="item.appId">{{ item.appName }} [{{ item.appId }}]</a-select-option>
              </a-select>
            </a-form-item>
          </div>
          <div v-if="vdata.auditResult.state == 3">
            <a-form-item v-if="vdata.auditResult.state == 3" required="true" label="结算方式：">
              <a-radio-group v-model:value="vdata.auditResult.pageSettAppIdOrAuditSelectedVal" @change="changePageSettAppIdOrAuditSelectedValFunc">
                <a-radio :value="'audit'">人工结算</a-radio>
                <a-radio :value="'appId'">灵活用工账户结算</a-radio>
              </a-radio-group>
              <div v-if="vdata.auditResult.pageSettAppIdOrAuditSelectedVal == 'audit'"><span class="jeepay-tip-text">选择人工结算并确认后，当前结算单将变更为<b>[结算中]</b>状态。人工结算完成后需手动修改状态为<b>[结算成功]</b>。</span></div>
            </a-form-item>

            <a-form-item v-if="vdata.auditResult.pageSettAppIdOrAuditSelectedVal == 'appId' && vdata.auditResult.transferMchAppId" required="true" label="选择转账结算账户：">
              <a-radio-group v-model:value="vdata.auditResult.transferIfCode">
                <a-radio v-for="(tifItem) in vdata.transIfCodeInfoList" :key="tifItem.ifCode" :value="tifItem.ifCode">
                  {{ tifItem.ifCodeName }}
                  <div v-if="typeof(tifItem.balance) == 'number'"><span class="jeepay-tip-text"><b>余额： ￥{{ (tifItem.balance / 100).toFixed(2) }}</b></span></div>
                </a-radio>
              </a-radio-group>
            </a-form-item>
          </div>
        </div>
      </a-form>
      <template #footer>
        <div style="display: flex;justify-content: space-between">
          <div v-if="vdata.auditResult.state == 3 && calMchfeeAndCostFee() != null">
            <span v-if="typeof calMchfeeAndCostFee().transferPlatformMchfeeAmount == 'number'">
              结算手续费： <span style="color: #2196f3; font-weight: bold;">￥{{ (calMchfeeAndCostFee().transferPlatformMchfeeAmount/ 100).toFixed(2) }}</span>
            </span>  
            <span style="margin-left: 30px;" />
            <span v-if="typeof calMchfeeAndCostFee().transferPlatformCostAmount == 'number'">
              实际成本：<span style="color: #2196f3; font-weight: bold;">￥{{ (calMchfeeAndCostFee().transferPlatformCostAmount/ 100).toFixed(2) }}</span>
            </span>   
            <span style="margin-left: 30px;" />
            <a-popover placement="top">
              <template #title><span>手续费</span></template>
              <template #content>
                <p> 1. 结算手续费：该笔结算中，自营商户使用所选转账产品产生的手续费金额。 </p>
                <p> 2. 实际成本：该笔结算中，结算手续费金额减去服务商利润后的实际成本金额。</p>
              </template>
              <question-circle-outlined />
            </a-popover>
          </div>
          <div v-else />
          <div>
            <a-button @click="vdata.showAuditModal = false">取消</a-button>
            <a-button :loading="vdata.auditConfirmLoading" type="primary" @click="auditHandleOkFunc">确定</a-button>
          </div>
        </div>
      </template>
    </a-modal>

    
    <!-- 人工处理 弹层 -->
    <a-modal v-model:visible="vdata.showProcessModal" title="结算状态变更" width="30%" :confirmLoading="vdata.processConfirmLoading" @ok="processHandleOkFunc">
      <a-form layout="vertical">
        <div>
          <a-form-item required="true" label="结算状态：">
            <a-radio-group v-model:value="vdata.processResult.state">
              <a-radio :value="4">结算完成</a-radio>
              <a-radio :value="5">结算失败</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item v-if="vdata.processResult.state == 4" label="打款凭证" name="transferCertImg">
            <JeepayUpload v-model:src="vdata.processResult.transferCertImg" bizType="avatar" />
          </a-form-item>

          <a-form-item v-if="vdata.processResult.state == 2 || vdata.processResult.state == 5" label="驳回原因：">
            <a-textarea v-model:value="vdata.processResult.auditRemark" :rows="3" />
          </a-form-item>
        </div>
      </a-form>
    </a-modal>
  </page-header-wrapper>
</template>

<script setup lang="ts">

import { API_URL_CASHOUT_RECORD, req, $exportExcel, exportExcelUrl, $cashoutAudit, $cashoutCount, $queryPlatformSelfMchNoAppInfos, $cashoutProcess } from '@/api/manage'
import { ref, reactive, getCurrentInstance, onMounted } from 'vue'
import InfoDetail from './Detail.vue'
import fileDownload from 'js-file-download'

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

// 主表格
const infoTable = ref()
const dateRangePicker = ref()
const infoDetail = ref()
let tableCount:any = ref([]) // 数据统计数组

let tableColumns = reactive([
  { key: 'rid', title: '申请单号', dataIndex: 'rid', fixed: 'left', },
  { key: 'infoName', title: '申请用户' },
  { key: 'settType', title: '申请类型',  },
  { key: 'applyAmount', title: '申请金额', dataIndex: 'applyAmount', customRender: ({text}) => '￥' + (text / 100).toFixed(2),  },
  { key: 'settFeeAmount', title: '手续费', dataIndex: 'settFeeAmount', customRender: ({text}) => '￥' + (text / 100).toFixed(2),  },
  { key: 'settAmount', title: '入账金额', dataIndex: 'settAmount', customRender: ({text}) => '￥' + (text / 100).toFixed(2),   },
  { key: 'settAccountType', title: '结算账户类型',  },
  { key: 'applyRemark', title: '申请备注', dataIndex: 'applyRemark' },
  { key: 'state', title: '状态',   },
  { key: 'createdAt', title: '申请日期', dataIndex: 'createdAt',   },
  { key: 'operation', title: '操作', fixed: 'right',   align: 'center'}
])


const vdata :any = reactive({
  btnLoading: false, // 列表的搜索按钮 
  searchData: {},  // 搜索数据

  detailData: {}, 
  showAuditModal: false,  // 是否显示弹层
  auditConfirmLoading: false, // 审核loading
  auditResult: {}, //审核结果

  platformSelfMchNoAppInfoList: [], // 提现选择 灵活用工渠道时， 查询当前配置的自营商户的应用信息
  transIfCodeInfoList: [], // 依赖上一个选择项， 当选择应用后会缓存渠道列表信息

  showProcessModal: false,  // 是否[人工打款]显示弹层
  processConfirmLoading: false, // 审核loading
  processResult: {}, //审核结果

})

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

// 数据统计
const getTableCount = () => {

  if(!$access('ENT_PROFIT_CASHOUT_RECORD_COUNT')){
    return false
  }

  $cashoutCount(vdata.searchData).then( res => {
    tableCount.value = [ 
      {title: '申请金额', symbol: 'add', isAmount: true, textColor: '#1A66FF', content: (res.applyAmount / 100).toFixed(2)},
      {type: 'line'},
      {title: '手续费', symbol: 'add', isAmount: true, textColor: '#1A66FF', content: (res.settFeeAmount / 100).toFixed(2)},
      {type: 'line'},
      {title: '入账金额', symbol: 'add', isAmount: true, textColor: '#1A66FF', content: (res.settAmount / 100).toFixed(2)},
    ]
  })
}

onMounted( () => {
  getTableCount()
})

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

// 点击【查询】按钮点击事件
function searchFunc () {
  getTableCount()

  infoTable.value.refTable(true)
}

// 申请单的详情页
function detailFunc (recordId) {
  infoDetail.value.show(recordId)
}

// 显示弹层
function showAuditModalFunc (recordId, detailObject) {
  vdata.detailData = detailObject
  vdata.auditConfirmLoading = false
  vdata.showAuditModal = true
  vdata.auditResult = { rid: recordId, pageSettAppIdOrAuditSelectedVal: 'audit' } // pageSettAppIdOrAuditSelectedVal  appId: 自动，  audit: 人工（默认）

  // 恢复默认值
  vdata.platformSelfMchNoAppInfoList = []
  vdata.transIfCodeInfoList = []

}

// 审核弹层 确认
function auditHandleOkFunc(){

  if(!vdata.auditResult.state){
    return $infoBox.message.error('请选择审核结果')
  }

  if( (vdata.auditResult.state == 2 || vdata.auditResult.state == 5) && !vdata.auditResult.auditRemark){
    return $infoBox.message.error('请填写拒绝原因')
  }

  // 自动转账
  if(vdata.auditResult.pageSettAppIdOrAuditSelectedVal == 'appId'){
    if(!vdata.auditResult.transferMchAppId){
      return $infoBox.message.error('请选择转账应用')
    }
    if(!vdata.auditResult.transferIfCode){
      return $infoBox.message.error('请选转账渠道接口')
    }
  }

  vdata.auditConfirmLoading = true
  $cashoutAudit(vdata.auditResult.rid, vdata.auditResult).then((res) => {
    vdata.showAuditModal = false
    $infoBox.message.success('处理完成')
    infoTable.value.refTable(true)
  }).finally(() => {
    vdata.auditConfirmLoading = false
  })

}

// 导出提现记录数据
function tableExportFunc(){
  return $exportExcel(exportExcelUrl.agentCashouts, Object.assign({}, vdata.searchData, {'pageSize': -1})).then(res => {
      fileDownload(res.data, '提现记录.xlsx')
  }).catch ((error) =>{console.log(error)} )
}


// 切换： 人工 、 灵活用工
function changePageSettAppIdOrAuditSelectedValFunc(e){

  // 选择灵活用工， 需要查询自营商户的所有应用集合
  if(e.target.value == 'appId'){

    // 已经包含了， 不再查询。
    if(vdata.platformSelfMchNoAppInfoList && vdata.platformSelfMchNoAppInfoList.length > 0){
      return false
    }

    $queryPlatformSelfMchNoAppInfos(vdata.auditResult.rid).then( res => {
      if(res){
        vdata.platformSelfMchNoAppInfoList = res
      }
      
    })

  }

  // 选择人工， 需要清除数据
  if(e.target.value == 'audit'){
    delete vdata.auditResult.transferMchAppId 
    delete vdata.auditResult.transferIfCode 
  }

}

// 选择商户应用的change事件 
function changeTransferMchAppIdFunc(appId){

  vdata.transIfCodeInfoList = []

  vdata.platformSelfMchNoAppInfoList.filter(r => r.appId == appId).forEach(item => {
    vdata.transIfCodeInfoList = item.transIfCodeInfoList
  })

}


// 显示弹层 人工处理
function showProcessModalFunc (recordId, detailObject) {
  vdata.processConfirmLoading = false
  vdata.showProcessModal = true
  vdata.processResult = { rid: recordId }
}


// 人工处理 确认
function processHandleOkFunc(){

  if(!vdata.processResult.state){
    return $infoBox.message.error('请选择结算结果')
  }

  if( (vdata.processResult.state == 2 || vdata.processResult.state == 5) && !vdata.processResult.auditRemark){
    return $infoBox.message.error('请填写拒绝原因')
  }

  vdata.processConfirmLoading = true
  $cashoutProcess(vdata.processResult.rid, vdata.processResult).then((res) => {
    vdata.showProcessModal = false
    $infoBox.message.success('处理完成')
    infoTable.value.refTable(true)
  }).finally(() => {
    vdata.processConfirmLoading = false
  })

}

// 获取当前通道的手续费 和 成本费用 
function calMchfeeAndCostFee(){

  if(!vdata.transIfCodeInfoList){
    return null
  }

  let resArr = vdata.transIfCodeInfoList.filter( r=> r.ifCode == vdata.auditResult.transferIfCode)
  if(resArr && resArr.length > 0){
    return resArr[0]
  }

  return null


}


</script>
