<template>
  <div>
    <a-modal
      v-model:visible="vdata.visible"
      title="退款"
      :confirm-loading="vdata.confirmLoading"
      :closable="false"
      @ok="handleOk"
      @cancel="handleCancel"
      style="position: relative;top: 50px !important;"
    >
      <a-row justify="space-between" type="flex">
        <a-col :sm="24">
          <a-descriptions>
            <a-descriptions-item label="支付订单号">
              {{ vdata.detailData.payOrderId }}
<!--              <a-tag color="purple">-->
<!--                {{ vdata.detailData.payOrderId }}-->
<!--              </a-tag>-->
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
        <a-col :sm="12">
          <a-descriptions>
            <a-descriptions-item label="支付通道">
              {{vdata.detailData.ifName}}
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
        <a-col :sm="12">
          <a-descriptions>
            <a-descriptions-item label="结算类型">
              {{vdata.detailData.settleType}}
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
        <a-col :sm="12">
          <a-descriptions>
            <a-descriptions-item label="支付金额">
              ￥ {{ (vdata.detailData.amount/100).toFixed(2) }}
<!--              <a-tag color="green">-->
<!--                {{ vdata.detailData.amount/100 }}-->
<!--              </a-tag>-->
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
        <a-col :sm="12">
          <a-descriptions>
            <a-descriptions-item label="可退金额">
              ￥{{ nowRefundAmount }}
<!--              <a-tag color="pink">-->
<!--                {{ nowRefundAmount }}-->
<!--              </a-tag>-->
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
      </a-row>

      <a-form ref="refundInfo" :rules="rules" :model="vdata.refund">

        <a-form-item label="退款模式" name="refundModel">
          <div style="display: grid">
                <a-radio-group v-model:value="vdata.refund.refundModel">
                  <a-radio :style="radioStyle" :value="1" :disabled="!vdata.settleTypeRefundState">收款商户号退款
                    <a-tooltip   class="my-tooltip">
                      <template #title>
                        需要今日存在正向交易订单且交易金额大于退款金额
                      </template>
                      <question-circle-outlined style="font-size: 12px" />
                    </a-tooltip>
                  </a-radio>
                  <span  class="jeepay-tip-text">仅T1、D1、定时结算类型订单支持，需要今日存在正向交易订单且交易金额大于退款金额</span>

                  <a-radio :style="radioStyle" :value="2"  :disabled="!vdata.settleTypePaymentState">退款专用账户
                    <a-tooltip   class="my-tooltip">
                      <template #title>
                        一般户充值退款
                      </template>
                      <question-circle-outlined style="font-size: 12px;" />
                    </a-tooltip>
                  </a-radio>
                </a-radio-group>

                <span  class="jeepay-tip-text" v-if="vdata.detailData.ifCode !='lklspay' || vdata.isPlatCheck == 1">(退款专用账户余额：{{(vdata.balacnePrice / 100).toFixed(2)}} 元，<a href="javascript:void(0)" @click="getfundRecharge">前往充值</a>)</span>
               <span  class="jeepay-tip-text" v-else>当前商户暂未申请绑定拉卡拉退款专用账户，<a href="javascript:void(0)" @click="getLklspay">点击申请</a></span>

          </div>

        </a-form-item>
        <a-form-item label="退款金额" name="refundAmount">
          <a-input-number v-model:value="vdata.refund.refundAmount" placeholder="请输入退款金额" :precision="2" style="width:100%" />
        </a-form-item>
        <a-form-item label="支付密码" name="refundPassword">
          <a-input v-model:value="vdata.refund.refundPassword" maxlength="6" type="password" autocomplete="off" />
          <span  class="jeepay-tip-text">(如果当前未设置支付密码，请进入 <a href="javascript:void(0)" @click="getSetConfig">【账号中心-系统配置-安全管理】</a> 设置支付密码)</span>
        </a-form-item>
        <a-form-item label="退款原因" name="refundReason">
          <a-input v-model:value="vdata.refund.refundReason" type="textarea" autocomplete="off" />
        </a-form-item>


      </a-form>
    </a-modal>
  </div>
</template>
<script setup lang="tsx">
import {
  API_URL_PAY_ORDER_LIST,
  req,
  $payOrderRefund,
  API_MCH_PAY_ACCOUNT,
  $getUserInfo,
  $payOrderCount, $getPayOrderRefundsIsPlatCheck, $unbindQrc, $getPayOrderRefundsApply
} from '@/api/manage'
import {ref, onMounted, reactive, getCurrentInstance,computed} from 'vue'
import { useRouter } from 'vue-router'
const routerPath = useRouter() //这是全部路由

const router = useRouter()

  // 获取全局函数
  const { $infoBox,$access } = getCurrentInstance()!.appContext.config.globalProperties

 const props = defineProps ({
    callbackFunc: { type: Function, default: () => () => ({}) }
  })
const radioStyle = reactive({
  display: 'block',
  height: '25px',
  lineHeight: '25px',
});
const  refundModel  =ref()
  const refundInfo = ref()
    const vdata : any =  reactive({
      settleTypePaymentState:true,
      settleTypeRefundState:true,
      isPlatCheck:true,
      sipw:2,
      refundErrorModal: null,  // 退款错误信息的modal对象
      recordId: '',
      labelCol: { span: 4 },
      wrapperCol: { span: 16 },
      visible: false,
      confirmLoading: false,
      balacnePrice:0,
      detailData: {} as any,
      accountList:[] as any,
      refund: {
         refundModel:"",
         refundReason: '', // 退款原因
         refundAmount: '' // 退款金额
      } as any,

    })

    const  rules = {
        refundModel: [{required: true, trigger: 'blur', message: '请输入退款模式' }],
        refundReason: [{ min: 0, max: 256, required: true, trigger: 'blur', message: '请输入退款原因，最长不超过256个字符' }],
        refundPassword: [{required: true, trigger: 'blur', message: '请输入支付密码' }],
        refundAmount: [{ required: true, message: '请输入金额', trigger: 'blur',type:'number' },
         {
            validator:  (rule, value) => {
              console.log(value)
              
              if (value < 0.01 || value >  nowRefundAmount.value) {
                return Promise.reject('退款金额不能小于0.01并且不能大于可退金额')
              }else{
                return Promise.resolve()
              }

            }
         }]
      }

  const nowRefundAmount = computed(()=>{
      return ((vdata.detailData.amount - vdata.detailData.refundAmount) / 100).toFixed(2)
  })

defineExpose({show})
   function show (record) {

      if (refundInfo.value !== undefined) {
				refundInfo.value.resetFields()
			}
      vdata.recordId = record.payOrderId
      vdata.visible = true
      vdata.refund = {}
     userDetail()
     getAccount()
     vdata.detailData = record
     // if(vdata.detailData.settleType == 'D1'){
     //   vdata.refund.refundModel = 1
     // }else{
     //   vdata.refund.refundModel = 2
     // }
     getPayOrderRefundsIsPlatCheck()
      // req.getById(API_URL_PAY_ORDER_LIST, recordId).then(res => {
      //
      // })
    }
function userDetail () { // 获取基本信息

  $getUserInfo().then(res => {
    vdata.sipw = res.sipw
  })
}
  function  handleOk () {
     if(vdata.detailData.ifCode =='lklspay' && vdata.isPlatCheck != 1){
       $infoBox.message.error('请申请拉卡拉退款专用账户')
       return false;
     }
    refundInfo.value.validate().then(valid =>{
          vdata.confirmLoading = true
    
          // 退款接口
          $payOrderRefund(vdata.recordId, vdata.refund.refundAmount, vdata.refund.refundReason, vdata.refund.refundPassword, vdata.refund.refundModel).then(res => {
              vdata.visible = false // 关闭弹窗
              vdata.confirmLoading = false // 取消按钮转圈

            if (res.state === 0 || res.state === 3) { // 订单生成 || 失败
              vdata.refundErrorModal = $infoBox.modalError('退款失败', buildModalText(res))
            } else if (res.state === 1) { // 退款中
              vdata.refundErrorModal = $infoBox.modalWarning('退款中', buildModalText(res))
              props.callbackFunc()
            } else if (res.state === 2) { // 退款成功
              $infoBox.message.success('退款成功')
              props.callbackFunc()
            } else {
              vdata.refundErrorModal = $infoBox.modalWarning('退款状态未知', buildModalText(res))
            }
          }).catch(() => {
            vdata.confirmLoading = false // 取消按钮转圈
          })
    })
    }
  function  handleCancel (e) {
      vdata.visible = false
    }

  // 跳转到退款列表函数
    function toRefundList () {
      vdata.refundErrorModal.destroy()
      router.push({
        path: '/refund',
      })
    }

    function buildModalText (res) {
      return <div>
        { res.errCode?  <div>错误码：{res.errCode} </div> : '' }
         { res.errMsg?  <div>错误信息：{res.errMsg} </div> : '' }
        <div>请到<a onClick={ toRefundList }>退款列表</a>中查看详细信息</div>
      </div>
    }
function getSetConfig(){
  router.push({
    path: '/config',
    query:{groupKey:"securityConfig"}
  })
}
function  getAccount(){
  req.list(API_MCH_PAY_ACCOUNT,{}).then(res => {
    vdata.accountList  = res
    vdata.balacnePrice = res[0].balacne
  })
}
function getfundRecharge() {
  routerPath.push({
    path:'/fundRecharge',
    query:{index:0}
  })
}

//验证一般户
function getPayOrderRefundsIsPlatCheck(){

  $getPayOrderRefundsIsPlatCheck(vdata.recordId).then( res => {

    vdata.settleTypePaymentState = res.isPlatAccount; //退款专用账户
    vdata.settleTypeRefundState = res.isDefaultAccount; //收款商户号退款
    vdata.isPlatCheck = res.bindStatus;
    if(vdata.detailData.settleType == 'D1'){
      if(vdata.settleTypePaymentState ){
        vdata.refund.refundModel = 1 //收款商户号退款
      }
    }else{
      if(vdata.settleTypeRefundState ){
        vdata.refund.refundModel = 2 //退款专用账户
      }
    }
    console.log(vdata.refund.refundModel,'vdata.refund.refundModel')
  })
}
//申请拉卡拉申请
function getLklspay(){
  const title = '确认申请？'
  const content = '是否申请绑定拉卡拉退款专用账户？'
  $infoBox.confirmDanger(title, content, () => {
    return $getPayOrderRefundsApply(vdata.recordId).then(res => {
      $infoBox.message.success('申请成功')
      setTimeout(() => {
        routerPath.push({
          path:'/applymentsOne',
        })
      },2000)
    })
  },() => {
    console.log(1111)
  })
}
</script>

<style scoped lang="less">
deep(.ant-modal-content svg){
  color: #0c2640 !important;
}
</style>
