<template>
  <div>
    <a-card style="width: 100%; margin-bottom: 20px">
      <div class="title">
        <p>佣金钱包</p>
      </div>
      <div class="items">
        <div class="item">
          <div style="display: flex">
            <p class="item-title">钱包余额（元）</p>
            <!-- <a-tooltip class="tooltip">
              <template #title></template>
              <i class="bi bi-info-circle" />
            </a-tooltip> -->
          </div>
          <p class="item-detail">{{ vdata.balanceAmountShow }}</p>
        </div>
        <div class="item">
          <div style="display: flex">
            <p class="item-title">在途利润（元）</p>
            <a-tooltip class="tooltip">
              <template #title>处于结算周期中的实际利润金额。</template>
              <i class="bi bi-info-circle" />
            </a-tooltip>
          </div>
          <p class="item-sub">{{ vdata.auditProfitAmount }}</p>
        </div>
        <div class="item">
          <div style="display: flex">
            <p class="item-title">提现中金额（元）</p>
            <a-tooltip class="tooltip">
              <template #title>处于提现中状态下的金额</template>
              <i class="bi bi-info-circle" />
            </a-tooltip>
          </div>
          <p class="item-sub">{{ vdata.unAmountShow }}</p>
        </div>
        <div class="item">
          <div style="display: flex">
            <p class="item-title">冻结金额（元）</p>
            <a-tooltip class="tooltip">
              <template #title>
                <span>
                  冻结金额为不可提现金额，当前可提现金额为：{{ vdata.allowTakeAmount }} 元。
                </span>
                <span v-if="vdata.detailData.freezeDesc"><br>冻结原因：【{{ vdata.detailData.freezeDesc }}】，请尽快处理。</span>
              </template>
              <i class="bi bi-info-circle" />
            </a-tooltip>
          </div>
          <p class="item-sub">{{ vdata.freezeAmount }}</p>
        </div>
        <div class="item operate" @click="withdrawFunc">
          <a-button type="primary">提现</a-button>
        </div>
      </div>
    </a-card>
    <a-card class="table-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>
        <jeepay-text-up
          v-model:value="vdata.searchData['rid']"
          :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="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>
      <!-- 提现弹出框 -->
      <withdraw-modal ref="withdrawModalInfo" :callbackFunc="refreshTable" />
      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :init-data="true"
        :req-table-data-func="reqTableDataFunc"
        :table-columns="tableColumns"
        :search-data="vdata.searchData"
        row-key="rid"
        :statisticsIsShow="$access('ENT_CASHOUT_RECORD_COUNT')"
        @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-count">{{ 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 #topBtnSlot>
          <a-button type="primary" @click="withdrawFunc()">
            <plus-outlined />发起提现
          </a-button>
        </template>
        <template #bodyCell="{ column, record }">
          <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>
          <template v-if="column.key == 'applyAmount'">
            <span>{{ record.applyAmount / 100 }}</span>
          </template>
          <template v-if="column.key == 'settAmount'">
            <span>{{ record.settAmount / 100 }}</span>
          </template>
          <template v-if="column.key == 'settFeeAmount'">
            <span>{{ record.settFeeAmount / 100 }}</span>
          </template>
          <template v-if="column.key === 'op'">
            <a-button type="link" @click="detailFunc(record.rid)">详情</a-button>
            <a-button
              v-show="record.state === 2"
              type="link"
              style="color: red"
              @click="withdrawAgainFunc(record)"
            >
              重新提现
            </a-button>
          </template>
        </template>
      </JeepayTable>
    </a-card>
    <!-- 详情页面组件  -->
    <InfoDetail ref="infoDetail" :callback-func="searchFunc" />
  </div>
</template>

<script lang="ts" setup>
import { message } from 'ant-design-vue'
import withdrawModal from './WithdrawModal.vue' // 提现弹出框
import InfoDetail from './WithdrawDetail.vue'
import { API_URL_WITHDRAWALS_RECORD_LIST, $getMainUserInfo, req, $getStatistics, $cashoutCount } from '@/api/manage'
import { ref, onMounted, reactive, getCurrentInstance } from 'vue'

const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties // 获取全局函数
const infoTable = ref()
const vdata = reactive({
  visible: false,
  searchData: {} as any,
  detailData: {} as any,
  selectedIds: [] as any,
  auditProfitAmount: '',
  balanceAmount: 0,
  balanceAmountShow: '',
  unAmountShow: '',
  unAmount: 0,
  freezeAmount: '', // 冻结金额
  allowTakeAmount: '', // 当前可提现金额
  btnLoading: false
})
let tableCount:any = ref([]) // 数据统计数组
const tableColumns = reactive([
  {
    key: 'rid',
    title: '提现单号',
    fixed: 'left',
    dataIndex: 'rid',
   
  },
  {
    key: 'applyAmount',
    title: '申请金额',
    dataIndex: 'applyAmount',
   
  },
  {
    key: 'settFeeAmount',
    title: '手续费',
    dataIndex: 'settFeeAmount',
   
  },
  {
    key: 'settAmount',
    title: '入账金额',
    dataIndex: 'settAmount',
   
  },
  {
    key: 'state',
    title: '提现状态',
    dataIndex: 'state',
   
  },
  {
    key: 'createdAt',
    title: '发起时间',
    dataIndex: 'createdAt',
    
  },
  {
    key: 'op',
    title: '操作',
    fixed: 'right',
    align: 'center',
  
  }
])
const withdrawModalInfo = ref()
const infoDetail = ref()
const dateRangePicker = ref()
// 传递的开始提现对象
const sendObject = reactive({
  amount: 0,
  agentType: '', // 代理商类型
  settAccountType: '', //账户类型
  settAccountNo: '', //结算账户
  settAccountName: '', //账户姓名
  settAccountBank: '', //开户行
  settAccountSubBank: '', //开户行支行名称
  settCertImg: '', //提现凭证
  applyRemark: '', //提现备注
  settFeeAmount: 0, //提现手续费
  contactTel: '', //联系人手机号
  contactName: '', //联系人姓名
  applyAmount: 0, //申请提现金额
  balanceAmount: 0,  // 钱包余额
  freezeAmount: 0, // 钱包冻结金额
  isAgain: false
})

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

  if(!$access('ENT_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) {
  return req.list(API_URL_WITHDRAWALS_RECORD_LIST, params)
}

function detailFunc(recordId) {
  infoDetail.value.show(recordId)
}

function resetFunc() {
  dateRangePicker.value.returnSelectModel()
  vdata.searchData = {}
}
// 获取统计数据
function getStatisticsData() {
  $getStatistics('')
    .then((res) => {
      vdata.detailData = res
      vdata.auditProfitAmount = (
        parseFloat(res.auditProfitAmount) / 100
      ).toFixed(2)
      vdata.balanceAmount = res.availableBalanceAmount / 100
      vdata.unAmount = res.unAmount / 100
      vdata.balanceAmountShow = (
        parseFloat(res.availableBalanceAmount) / 100
      ).toFixed(2)
      vdata.unAmountShow = (parseFloat(res.unAmount) / 100).toFixed(2)
      vdata.freezeAmount = (parseFloat(res.freezeAmount) / 100).toFixed(2)
      vdata.allowTakeAmount = (parseFloat(res.allowTakeAmount) / 100).toFixed(2)
    })
    .catch((err) => {
      console.log(err)
    })
}

function searchFunc() {
  getTableCount()
  
  // 点击【查询】按钮点击事件
  infoTable.value.refTable(true)
}

// 获取账户信息
function getAccountInfo() {
  $getMainUserInfo()
    .then((res) => {
      sendObject.agentType = res.agentType
      sendObject.contactTel = res.contactTel
      sendObject.contactName = res.contactName
      sendObject.settAccountName = res.settAccountName
      sendObject.settAccountNo = res.settAccountNo
      sendObject.settAccountBank = res.settAccountBank
      sendObject.settAccountType = res.settAccountType
      sendObject.settAccountSubBank = res.settAccountSubBank
    })
    .catch((err) => {
      console.log(err)
    })
}

function refreshTable() {
  infoTable.value.refTable(true)
  getStatisticsData()
}

// 打开提现弹出框
function withdrawFunc() {
  if (vdata.balanceAmount <= 0) {
    return message.error('无可提现金额')
  } else {
    if (Number(vdata.allowTakeAmount) <= 0) {
      return message.error('无可提现金额')
    }
    getAccountInfo()
    sendObject.settCertImg = ''
    sendObject.applyRemark = ''
    sendObject.amount = Number(vdata.allowTakeAmount)
    sendObject.balanceAmount = Number(vdata.balanceAmount)
    sendObject.freezeAmount = Number(vdata.freezeAmount)
    withdrawModalInfo.value.show(sendObject)
  }
}

// 重新提现
function withdrawAgainFunc(saveObject) {
  getAccountInfo()
  sendObject.isAgain = true
  sendObject.amount = vdata.balanceAmount
  sendObject.settFeeAmount = saveObject.settFeeAmount / 100
  sendObject.applyRemark = saveObject.applyRemark
  sendObject.settCertImg = saveObject.settCertImg
  sendObject.applyAmount = saveObject.applyAmount
  withdrawModalInfo.value.show(sendObject)
}
Promise.all([getStatisticsData()])
</script>
<style lang="less" scoped>
.title {
  box-sizing: border-box;
  padding: 16px 0 0px 20px;
  margin-bottom: 30px;
  border-bottom: 1px solid #e8e8e8;
  p {
    font-weight: bold;
    font-size: 14px;
    letter-spacing: 0.07em;
    color: #000;
  }
}

.items {
  display: flex;
  justify-content: space-around;
  .item {
    margin-bottom: 20px;
    p {
      font-weight: 500;
      margin: 0;
    }
    .item-title {
      font-size: 14px;
      letter-spacing: 0.05em;
      color: #737980;
    }
    .item-detail,
    .item-sub {
      font-size: 25px;
      color: var(--ant-primary-color);
    }
    .item-sub {
      color: #000000 !important;
    }
  }
  .operate {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100px;
    height: 38px;
    border-radius: 3px;
    margin-top: 15px;
    p {
      font-size: 13px;
      letter-spacing: 0.02em;
      color: #fff;
    }
  }
}
.tooltip {
  &:hover {
    cursor: pointer;
  }
}
.statistics-list .item .title-count {
    color: #808080;
    margin-bottom: 10px;
}
</style>
