<!--
  盛付通： 【签约开通】 页面内容

  @author terrfly
  @site https://www.jeequan.com
  @date 2022/11/03 08:35
-->
<template>
  <div v-if="vdata.visible">
    <div v-if="vdata.state && vdata.subMerchantId">
      <a-tabs @change="selectTabs">
        <a-tab-pane key="bandCardConfig" tab="绑卡信息">
          <span class="jeepay-tip-text">
            商户绑卡，可以新增绑卡，商户换卡<br>
            * 小微商户只能选择对私借记卡<br>
            * 商户审核通过之前进行换卡，此时修改的信息会立即生效<br>
            * 商户审核通过之后进行换卡，需等待审核通过后，在指定的换卡生效时间生效；若审核通过时间>=换卡生效时间，则会在审核通过+1天时间生效
          </span>
          <div style="margin-bottom: 10px;" />
          <a-form
            ref="bandCardFormRef"
            :model="vdata.applyData"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 8 }"
            :rules="vdata.rules"
          >
            <a-form-item label="河马付商户类型">
              <span v-if="vdata.applyData.hmMerchantType == 'GENERAL_MERCHANT'">普通商户
                <span v-if="vdata.applyData.enterpriseNature == 'STOCK_COMPANY'">(股份公司)</span>
                <span v-if="vdata.applyData.enterpriseNature == 'LIMITED_COMPANY'">(有限公司)</span>
                <span v-if="vdata.applyData.enterpriseNature == 'INDIVIDUAL_BUSINESS'">(个体工商户)</span>
                <span v-if="vdata.applyData.enterpriseNature == 'GOVERNMENT_INSTITUTION'">(事业单位)</span>
                <span v-if="vdata.applyData.enterpriseNature == 'OTHER'">(其他组织)</span>
              </span>
              <span v-else-if="vdata.applyData.hmMerchantType == 'PERSONAL_MERCHANT'">个人小微</span>
            </a-form-item>
            <a-form-item label="银行账户类型" name="bankAccountType">
              <a-radio-group v-model:value="vdata.applyData.bankAccountType" @change="changeSettInfo()">
                <a-radio value="PUBLIC_ACCOUNT" :disabled="vdata.applyData?.hmMerchantType == 'PERSONAL_MERCHANT'">对公帐户</a-radio>
                <a-radio value="PRIVATE_DEBIT_ACCOUNT" :checked="true">对私借记卡</a-radio>
              </a-radio-group>
            </a-form-item>
            
            <a-form-item label="银行开户名" name="settAccountName">
              <a-input v-model:value.trim="vdata.applyData.settAccountName" />
            </a-form-item>
            <a-form-item v-if="vdata.applyData.bankAccountType == 'PRIVATE_DEBIT_ACCOUNT'" label="银行卡正面照" name="settAccountLicenseImg">
              <JeepayUpload v-model:src="vdata.applyData.settAccountLicenseImg" bizType="applyment" ocrType="bankCard" @ocrScan="ocrScanFunc" />
              <span class="jeepay-tip-text">(上传图片自动识别 银行卡号)</span>
            </a-form-item>
            <a-form-item label="银行卡卡号" name="settAccountNo">
              <a-input v-model:value.trim="vdata.applyData.settAccountNo" />
            </a-form-item>
            <a-form-item v-if="vdata.applyData.bankAccountType == 'PUBLIC_ACCOUNT'" label="银行联行号" name="bankChannelNo">
              <a-input v-model:value.trim="vdata.applyData.bankChannelNo" />
              <span><a href="https://www.icvio.cn/" target="_blank">联行号查询</a></span>
            </a-form-item>
            <a-form-item v-if="vdata.applyData.bankAccountType == 'PRIVATE_DEBIT_ACCOUNT'" label="银行开户身份证号码" name="bankAccountIdCardNo">
              <a-input v-model:value.trim="vdata.applyData.bankAccountIdCardNo" />
            </a-form-item>
            <a-form-item v-if="vdata.applyData.bankAccountType == 'PRIVATE_DEBIT_ACCOUNT'" label="银行预留手机号" name="bankAccountPhone">
              <a-input v-model:value.trim="vdata.applyData.bankAccountPhone" />
            </a-form-item>
            <a-form-item label="换卡生效时间" name="validDate">
              <a-input v-model:value.trim="vdata.applyData.validDate" />
              <span class="jeepay-tip-text">（商户换卡必填，格式示例：2019-08-01）</span>
            </a-form-item>
            <br>
          </a-form>
          
          <div class="drawer-btn-center">
            <a-button class="jeepay-m-btn" data-type="block" type="primary" :loading="vdata.btnLoading" @click="merchantBankBind()"><check-outlined />更新绑定信息</a-button>
          </div>
        </a-tab-pane>
        <a-tab-pane v-if="configMode != 'mchApplyment'" key="payWayRateConfig" tab="业务开通">
          <a-form layout="vertical">
            已申请的费率信息状态<a-button :loading="vdata.bizQueryInfoBtnLoading" size="small" style="margin-left: 20px;" type="primary" @click="merchantRateQuery()"><reload-outlined />刷新</a-button>
            <div v-for="(item, index) in vdata.bizRateInfoList" :key="index" style="margin-top: 5px; margin-bottom: 5px; color: #2358e8;">{{ item }}</div>

            <div v-if="vdata.channelVar1">
              <p style="margin-top: 30px;"><b>费率配置错误响应数据:</b></p><span style="color: red;">{{ vdata.channelVar1 }}</span>
            </div>
            
            <JeepayPaywayRatePanel 
              ref="jeepayPaywayRatePanelRef" 
              :configMode="configMode"
              :infoId="vdata.recordId + '_' + vdata.mchNo" 
              :selectIfCode="vdata.ifCode" 
              onlyRate="true"
            />
          </a-form>
          
          <a-divider class="jeepay-m-divider" orientation="left" style="color: #1A66FF;" />
          <div class="drawer-btn-center">
            <a-button class="jeepay-m-btn" data-type="block" type="primary" :loading="vdata.btnLoading" @click="merchantRateSet()"><check-outlined />确认开通</a-button>
          </div>
        </a-tab-pane>
        <a-tab-pane v-if="vdata.state == '2'" key="signConfig" tab="认证开通">
          <a-divider orientation="left" style="color: #1A66FF;">渠道入驻</a-divider>
          <a-form
            ref="channelRegisterRef"
            :model="vdata.applyData"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 8 }"
            :rules="vdata.rules"
          >
            已生效的入驻信息：
            <div style="margin-top: 5px; margin-bottom: 5px; color: #2358e8;">
              <span v-if="vdata.bizChannelInfo?.wxSubMchNo">【微信】渠道子商户号：{{ vdata.bizChannelInfo.wxSubMchNo }}</span>
              <span v-if="vdata.bizChannelInfo?.aliSubMchNo">【支付宝】渠道子商户号：{{ vdata.bizChannelInfo.aliSubMchNo }}</span>
              <span v-if="vdata.bizChannelInfo?.unionSubMchNo">【银联】渠道子商户号：{{ vdata.bizChannelInfo.unionSubMchNo }}</span>
            </div>
            
            <a-form-item label="河马付门店号" name="hmStoreNo">
              <div style="width: 100%;">
                <a-input v-model:value.trim="vdata.hmStoreNo" style="display: inline-block; " />
                <a-button :loading="vdata.bizQueryInfoBtnLoading" size="small" type="primary" @click="channelRegisterQuery()"><SearchOutlined />查询入驻信息（默认100001）</a-button>
              </div>
            </a-form-item>
              

            <a-form-item label="支付方式" name="channelRegisterType">
              <div style="width: 150%;">
                <a-radio-group v-model:value="vdata.channelRegisterType">
                  <a-radio value="WEIXIN">微信</a-radio>
                  <a-radio value="ALIPAY">支付宝</a-radio>
                  <a-radio value="UNION_PAY">银联支付</a-radio>
                </a-radio-group>
                <a-button size="small" type="primary" :loading="vdata.btnLoading" @click="channelRegister()"><check-outlined />入驻</a-button>
                <a-button size="small" type="dashed" :loading="vdata.btnLoading" @click="(e) => vdata.channelRegisterType = '' "><DeleteOutlined />清空</a-button>
              </div>
              <span class="jeepay-tip-text">不上送支付方式时默认入驻全部</span>
            </a-form-item>
          </a-form>
          
          <!-- 商户开户意愿确认公共组件 -->
          <NextBizsCommonPage ref="nextBizsCommonPage" />
        </a-tab-pane>
        <a-tab-pane v-if="vdata.state == '2'" key="storeRegister" tab="门店入驻">
          <StoreRegister ref="storeRegisterRef" />
        </a-tab-pane>
      </a-tabs>
    </div>
    <div v-else>
      <a-result title="暂无更多操作">
        <template #icon>
          <smile-twoTone />
        </template>
      </a-result>
    </div>
  </div>
</template>

<script lang="ts" setup>

import { ref, nextTick, inject } from 'vue'
import ruleGenerator from '@/utils/ruleGenerator'
import NextBizsCommonPage from '../../commons/NextBizsCommonPage.vue'
import StoreRegister from '../hmpay/StoreRegister.vue'
import { API_URL_MCH_APPLYMENT_LIST, req, $hmpayAfterOperate } from '@/api/manage'
import { getCurrentInstance, reactive } from 'vue'
const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties
const jeepayPaywayRatePanelRef = ref()
const nextBizsCommonPage = ref()
const bandCardFormRef = ref()
const channelRegisterRef = ref()
const storeRegisterRef = ref()
let configMode : any = inject('configMode')


const vdata : any = reactive({
  state: '',
  subMerchantId: '',
  ifCode: '',
  mchNo: '',
  hmStoreNo: '',
  recordId: null, // 更新对象ID
  applyData: {} as any, // 进件资料对象
  bizRateInfoList: [] as any, // 业务开通查询响应数据对象
  bizChannelInfo: '', // 渠道入驻查询响应数据对象
  visible: false, // 是否显示弹层/抽屉
  btnLoading: false, // 编辑类按钮
  bizQueryInfoBtnLoading: false, // 查询类按钮
  rules: {
    bankAccountType: [ ruleGenerator.requiredSelect('银行账户类型', 'string') ],
    settAccountName: [ ruleGenerator.requiredInput('银行开户名') ],
    settAccountNo: [ ruleGenerator.requiredInput('银行卡卡号') ],
    bankChannelNo: [ ruleGenerator.requiredInput('银行联行号') ],
    bankAccountIdCardNo: [ ruleGenerator.requiredInput('银行开户身份证号码') ],
    bankAccountPhone: [ ruleGenerator.requiredInput('银行预留手机号') ],
    validDate: [{ required: false, pattern: /^\d{4}-\d{2}-\d{2}$/, message: '请输入正确的换卡生效时间[yyyy-MM-dd]', trigger: 'blur' }]
  }
})

function merchantRateSet() {
  // 放置费率配置项
  let paywayFeeList = jeepayPaywayRatePanelRef.value.getReqMchRatePaywayFeeList()
  if (!paywayFeeList) {
    $infoBox.message.error('费率信息填写有误')
    return
  }
  vdata.btnLoading = true
  vdata.applyData.paywayFeeList = paywayFeeList
  $hmpayAfterOperate(vdata.ifCode, vdata.mchNo, vdata.recordId, 1, vdata.applyData).then((res) => { 
    if (res) {
      vdata.channelVar1= res
      $infoBox.message.error(res)
    } else {
      $infoBox.message.success('业务开通发起成功！')
    }
    vdata.btnLoading = false
  }).catch(() => {
    vdata.btnLoading = false
  })
  
}

// 查询费率配置信息
function merchantRateQuery() {
  vdata.bizQueryInfoBtnLoading = true
  $hmpayAfterOperate(vdata.ifCode, vdata.mchNo, vdata.recordId, 2, vdata.applyData).then((res) => {
    if (res) {
      vdata.bizRateInfoList = res.split(';')
    }
    $infoBox.message.success('刷新成功', 0.5)
    vdata.bizQueryInfoBtnLoading = false
  }).catch(() => {
    vdata.bizQueryInfoBtnLoading = false
  })
}

// 绑卡
function merchantBankBind() {
  bandCardFormRef.value.validate().then(valid =>{
    vdata.btnLoading = true
    $hmpayAfterOperate(vdata.ifCode, vdata.mchNo, vdata.recordId, 3, vdata.applyData).then((res) => { 
      if (res) {
        $infoBox.message.error(res)
      }else{
        $infoBox.message.success('绑卡申请发起成功！')
      }
      vdata.btnLoading = false
    }).catch(() => {
      vdata.btnLoading = false
    })
  }).catch(valid =>{
  })
}

// 渠道入驻
function channelRegister() {
    vdata.btnLoading = true
    $hmpayAfterOperate(vdata.ifCode, vdata.mchNo, vdata.recordId, 5, {channelRegisterType: vdata.channelRegisterType, hmStoreNo: vdata.hmStoreNo }).then((res) => { 
      if (res) {
        $infoBox.message.error(res)
      }else{
        $infoBox.message.success('渠道入驻申请发起成功！')
      }
      vdata.btnLoading = false
    }).catch(() => {
      vdata.btnLoading = false
    })
}

// 查询渠道入驻信息
function channelRegisterQuery() {
    if(!vdata.hmStoreNo){
      vdata.hmStoreNo = '100001'
    }
    vdata.bizChannelInfo = {}
    vdata.bizQueryInfoBtnLoading = true
    $hmpayAfterOperate(vdata.ifCode, vdata.mchNo, vdata.recordId, 6, {hmStoreNo: vdata.hmStoreNo}).then((res) => {
      if (res) {
        vdata.bizChannelInfo = JSON.parse(res)
      }
      $infoBox.message.success('刷新成功', 0.5)
      vdata.bizQueryInfoBtnLoading = false
    }).catch(() => {
      vdata.bizQueryInfoBtnLoading = false
    })
}


function selectTabs (key) { // 切换tab
  if(key == 'signConfig') {
    // 签约开通
    channelRegisterQuery()
    nextTick(() => {
      nextBizsCommonPage.value.pageRender(vdata.recordId) // 直接调用通用组件
    })
  } else if(key == 'payWayRateConfig') {
    merchantRateQuery()
  } else if(key == 'storeRegister') {
    nextTick(() => {
      storeRegisterRef.value.show(vdata.recordId, vdata.mchNo) // 直接调用通用组件
    })
  }
}

// 对外暴露的 页面渲染函数  也用作初始化
function pageRender (applyId){
  req.getById(API_URL_MCH_APPLYMENT_LIST, applyId, { originData: 1}).then( (res) => {
    // 进件资料
    vdata.applyData = JSON.parse(res.applyDetailInfo)
    // 状态
    vdata.state = res.state
    // 单号
    vdata.recordId = applyId
    // 类型 
    vdata.ifCode = res.ifCode
    // 用户号
    vdata.mchNo = res.mchNo
    // 渠道申请单号（标识在河马付已创建商户）
    vdata.subMerchantId = res.channelApplyNo
    // 渠道拓展参数1 用来存放费率失败信息
    vdata.channelVar1 = res.channelVar1

    // 小微商户只能对私
    if (vdata.applyData?.hmMerchantType == 'PERSONAL_MERCHANT') {
      vdata.applyData.bankAccountType = 'PRIVATE_DEBIT_ACCOUNT'
      if (!vdata.applyData.settAccountName) {
        vdata.applyData.settAccountName = vdata.applyData.idcardName
      }
      if (!vdata.applyData.bankAccountIdCardNo) {
        vdata.applyData.bankAccountIdCardNo = vdata.applyData.idcardNo
      }
    }

    vdata.visible = true
  })
}

// 图片识别的回调函数
function ocrScanFunc(orcObject){
  if(orcObject){
    Object.assign(vdata.applyData, orcObject)
    if(orcObject.settAccountNo) {
      vdata.applyData.settAccountNo = orcObject.settAccountNo
    }
  }
}

function changeSettInfo(){
  if (vdata.applyData.bankAccountType == 'PRIVATE_DEBIT_ACCOUNT') {
        vdata.applyData.settAccountName = vdata.applyData.idcardName
        vdata.applyData.bankAccountIdCardNo = vdata.applyData.idcardNo
  } else {
        vdata.applyData.settAccountName = vdata.applyData.mchFullName
        vdata.applyData.bankAccountIdCardNo = ''
  }
}
defineExpose({ pageRender })
</script>
