<template>
  <a-drawer
    v-model:visible="vdata.visible"
    :mask-closable="false"
    :title=" vdata.isAgain ? '重新提现' : '发起提现' "
    width="40%"
    @close="onClose"
  >
    <a-form v-if="vdata.visible" ref="infoFormModel" :model="vdata.saveObject" layout="vertical" :rules="vdata.rules">
      <a-row justify="space-between" type="flex">
        <a-col :span="14">
          <a-form-item :label="'提现金额(最多可提现：' + vdata.amount + '元)'" name="amount">
            <a-input-number
              v-model:value="vdata.saveObject.amount"
              placeholder="请输入提现金额"
              style="width:70%;"
              min="0.01"
              :max="vdata.amount"
              addon-after="元"
            />
            <span class="jeepay-tip-text">钱包余额：{{ vdata.detailData.balanceAmount }}元，冻结金额：{{ vdata.detailData.freezeAmount }} 元</span>
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label=" " name="">
            <a-button type="dashed" style="color: #1f8cf5; background-color: #e6f2fd;" :loading="vdata.btnLoading" @click="handleTakeAllFunc">
              <PayCircleOutlined />
              全部提现
            </a-button>
          </a-form-item>
        </a-col>
        <a-col :span="6" />
      </a-row>
      <a-row justify="space-between" type="flex">
        <a-col :span="10">
          <a-form-item label="请输入联系人姓名：" name="contactName">
            <a-input v-model:value="vdata.saveObject.contactName" placeholder="请输入结算账户姓名" />
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <a-form-item label="结算账户联系人手机号：" name="contactTel">
            <a-input v-model:value="vdata.saveObject.contactTel" placeholder="结算账户联系人手机号" />
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <a-form-item label="提现备注：" name="applyRemark">
            <a-input
              v-model:value="vdata.saveObject['applyRemark']"
              placeholder="请输入提现备注"
            />
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <div class="ant-upload-preview">
            <div>
              <a-form-item label="申请资料" name="settCertImg" />
              <img v-show="vdata.saveObject.settCertImg" :src="vdata.saveObject.settCertImg">
            </div>
            <div>
              <JeepayUpload
                v-model:src="vdata.saveObject.settCertImg"
                bizType="avatar"
                :showUploadList="false"
              />
              <span class="jeepay-tip-text">请上传发票等凭证图片</span>
            </div>
          </div>
        </a-col>

        <a-col :span="24">
          <a-col :span="10">
            <a-form-item label="支付密码：" name="sipwRaw">
              <a-input-password
                v-model:value="vdata.saveObject['sipwRaw']"
                maxlength="6"
                autocomplete="new-password"
                placeholder="请输入支付密码"
              />
            </a-form-item>
          </a-col>
        </a-col>

        <a-divider orientation="left" />
        <a-col :span="10">
          <a-descriptions>
            <a-descriptions-item label="提现手续费">
              {{ vdata.saveObject.settFeeAmount }}
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
        <a-col :span="10">
          <a-descriptions>
            <a-descriptions-item label="到账金额">
              {{ vdata.receivedAmount }}
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
        <a-col :sm="12">
          <a-descriptions>
            <a-descriptions-item label="服务商类型">
              {{ vdata.saveObject.agentType === 1 ? '个人':'企业' }}
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
        <a-col :sm="12">
          <a-descriptions>
            <a-descriptions-item label="收款账户类型">
              {{ vdata.saveObject.settAccountType === "WX_CASH" ? '个人微信':vdata.saveObject.settAccountType === "ALIPAY_CASH"? '个人支付宝':vdata.saveObject.settAccountType === "BANK_PUBLIC"? '对公账户':vdata.saveObject.settAccountType === "BANK_PRIVATE"? '对私账户':'银行卡' }}
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
      </a-row>
      <a-row v-if="vdata.saveObject.settAccountType === 'WX_CASH' || vdata.saveObject.settAccountType === 'ALIPAY_CASH'" justify="space-between" type="flex">
        <a-col :sm="12">
          <a-descriptions>
            <a-descriptions-item label="账户姓名">
              {{ vdata.saveObject.settAccountName }}
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
        <a-col :sm="12">
          <a-descriptions>
            <a-descriptions-item :label="vdata.saveObject.settAccountType === 'ALIPAY_CASH'?'支付宝账号':'个人微信号'">
              {{ vdata.saveObject.settAccountNo }}
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
      </a-row>
      <a-row v-if="vdata.saveObject.settAccountType === 'BANK_PRIVATE'" justify="space-between" type="flex">
        <a-col :sm="12">
          <a-descriptions>
            <a-descriptions-item label="账户姓名">
              {{ vdata.saveObject.settAccountName }}
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
        <a-col :sm="12">
          <a-descriptions>
            <a-descriptions-item label="收款银行卡号">
              {{ vdata.saveObject.settAccountNo }}
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
      </a-row>
      <a-row v-if="vdata.saveObject.settAccountType === 'BANK_PUBLIC'" justify="space-between" type="flex">
        <a-col :sm="12">
          <a-descriptions>
            <a-descriptions-item label="对公账户名称">
              {{ vdata.saveObject.settAccountName }}
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
        <a-col :sm="12">
          <a-descriptions>
            <a-descriptions-item label="对公账号">
              {{ vdata.saveObject.settAccountNo }}
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
        <a-col :sm="12">
          <a-descriptions>
            <a-descriptions-item label="开户银行名称">
              {{ vdata.saveObject.settAccountBank }}
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
        <a-col :sm="12">
          <a-descriptions>
            <a-descriptions-item label="开户行支行名称">
              {{ vdata.saveObject.settAccountSubBank }}
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
        <a-col v-if="!vdata.saveObject.settAccountNo" :span="10">
          <a-form-item label="温馨提示：" name="tips">
            <a-tag color="red">您还未配置结算信息，请联系运营平台添加</a-tag>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" style="margin-right:8px" @click="onClose">
        <close-outlined />
        取消
      </a-button>
      <a-button type="primary" :loading="vdata.btnLoading" @click="handleOkFunc">
        <check-outlined />
        保存
      </a-button>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
import { $withdrawalApply, $withdrawalFee } from '@/api/manage'
import { message } from 'ant-design-vue'
import { defineProps, reactive, ref, watch } from 'vue'
import { Base64 } from 'js-base64'
const props = defineProps({
  callbackFunc: { type: Function,default:null }
})
  const infoFormModel = ref()
  const vdata : any = reactive({
    feeType: '',//手续费类型
    applyLimit: 0,//最低提现金额
    freeLimit: 0,//免收手续费额度
    fixFee: 0,//固定费用
    feeRate: 0,//费率
    btnLoading: false,
    amount: 0,//可以提现的金额
    isAgain: true, // 重新提现 or 提现页面标志
    saveObject: {}, // 数据对象
    detailData: {} as any, // 数据对象(详情数据)
    recordId: null, // 更新对象ID
    visible: false, // 是否显示弹层/抽屉
    receivedAmount: 0,//到账金额
    rules: {
      amount: [{ required: true, message: '请输入提现金额', trigger: 'blur' }],
      settFeeAmount: [{ required: true, message: '提现手续费', trigger: 'blur' }],
      contactName: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
      contactTel: [{ required: true, message: '请输入联系人手机号', trigger: 'blur' }],
      sipwRaw: [{ required: true, message: '请输入支付密码', trigger: 'blur' }],
    }
  })

// 计算手续费
function calculationFee() {
  $withdrawalFee().then(res => {
      vdata.feeType = res.feeType
      vdata.applyLimit = res.applyLimit / 100
      vdata.freeLimit = res.freeLimit / 100
      vdata.fixFee =  res.fixFee / 100
      vdata.feeRate =  res.feeRate
      if(res.freeLimit !== 0){ //如果在额度限度里，手续费为0
        if(vdata.saveObject.amount <= res.freeLimit / 100){
            vdata.saveObject.settFeeAmount = 0
        } else { //如果超过限制额度
          if(res.feeType === 'FIX'){//若是固定额度
            vdata.saveObject.settFeeAmount  = res.fixFee / 100
          }else if(res.feeType === 'SINGLE'){//若是费率
            vdata.saveObject.settFeeAmount = (res.feeRate * vdata.saveObject.amount).toFixed(2)
          }else if(res.feeType === 'FIXANDRATE'){//若是费率 + 固定
            vdata.saveObject.settFeeAmount = ((res.fixFee) / 100 + (res.feeRate * vdata.saveObject.amount)).toFixed(2)
          }
        }
    } else {
        //如果额度为0则计算费率
        if(res.feeType === 'FIX'){
          vdata.saveObject.settFeeAmount  = res.fixFee / 100
        }else if(res.feeType === 'SINGLE'){ //若是费率
          vdata.saveObject.settFeeAmount = (res.feeRate * vdata.saveObject.amount).toFixed(2)
        }else if(res.feeType === 'FIXANDRATE'){//若是费率 + 固定
            vdata.saveObject.settFeeAmount = ((res.fixFee) / 100 + (res.feeRate * vdata.saveObject.amount)).toFixed(2)
          }
      }
    vdata.receivedAmount = (vdata.saveObject.amount - vdata.saveObject.settFeeAmount).toFixed(2)
    if(vdata.receivedAmount <0 ){
      vdata.receivedAmount = 0
    }
    }).catch(err => {
      console.log(err)
    })
}

function show (params) { // 弹层打开事件
  vdata.isAgain = params.isAgain
  vdata.amount = params.amount
  vdata.saveObject = params
  vdata.detailData = params
  vdata.btnLoading = false
  vdata.visible = true
  calculationFee()
  if(params.isAgain) {
    vdata.saveObject.amount = params.applyAmount / 100
  } else {
    vdata.saveObject.amount = ''
  }
  delete vdata.saveObject.applyAmount
  delete vdata.saveObject.isAgain
  delete vdata.saveObject.sipwRaw
}
// 监听提现金额和手续费的变化
watch([() => vdata.saveObject.settFeeAmount, () => vdata.saveObject.amount, () => vdata.receivedAmount], (values) => {
  calculationFee()
})

function handleOkFunc () { // 点击【确认】按钮事件
    infoFormModel.value.validate().then(valid =>{
      vdata.btnLoading = true
      const phoneReg = /^1\d{10}$/
      if(!phoneReg.test(vdata.saveObject.contactTel)) {
        message.error(`请输入合法手机号`)
        vdata.btnLoading = false
      }else if(isNaN(vdata.receivedAmount) || vdata.receivedAmount <= 0){
        message.error(`到账金额计算有误， 请重新填写`)
        vdata.btnLoading = false
      }else {
          if(vdata.amount >= parseFloat(vdata.saveObject.amount)) {
            if(vdata.applyLimit > parseFloat(vdata.saveObject.amount)) {
              message.error(`最低提现金额为：${vdata.applyLimit}元`)
              vdata.btnLoading = false
            } else {
              // 请求接口
              vdata.saveObject.sipw = Base64.encode(vdata.saveObject.sipwRaw) // base 64
              $withdrawalApply(vdata.saveObject).then(res => {
                if(vdata.isAgain) {
                  message.success('已重新发起提现')
                } else {
                  message.success('提现已发起')
                }
                props.callbackFunc() // 刷新列表
                vdata.btnLoading = false
              }).catch(err => {
                console.log(err)
                vdata.btnLoading = false
              })
                vdata.visible = false
              }
        } else {
          message.error(`请输入不大于${vdata.amount}元的金额`)
          vdata.btnLoading = false
        }
      }
    }).catch(valid =>{
      console.log(valid)
    })
}

function handleTakeAllFunc(){
  vdata.saveObject.amount = vdata.amount
}
function onClose () {
  vdata.visible = false
}
defineExpose({
  show
})
</script>
<style lang="less">
.ant-upload-preview {
  display: flex;
  justify-content: space-between;
  img {
    width: 100px;
    height: 100px;
    border: 1px solid rgba(0,0,0,0.08);
  }
  .upload-icon {
    font-size: 1.4rem;
    background: rgba(222, 221, 221, 0.7);
    border-radius: 50%;
    border: 1px solid rgba(0, 0, 0, 0.2);
  }
}
</style>
