<!--
  联动惠商： 【签约开通】 页面内容

  @author terrfly
  @site https://www.jeequan.com
  @date 2022/11/03 08:35
-->
<template>
  <div v-if="vdata.state == 2">
    <a-tabs @change="selectTabs">
      <a-tab-pane v-if="vdata.state == '2'" key="signConfig" tab="认证开通">
        <!-- 商户开户意愿确认公共组件 -->
        <NextBizsCommonPage ref="nextBizsCommonPage" />
      </a-tab-pane>
      <a-tab-pane v-if="configMode != 'mchApplyment'" key="payWayRateConfig">
        <template #tab>
          业务开通
          <a-tooltip
            title="说明：如需变更联动惠商系统给配的默认费率，可使用此业务开通进行费率变更（前提是在代理商后台完成代理商实名认证）"
          >
            <info-circle-outlined />
          </a-tooltip>
        </template>
        <a-form layout="vertical">
          <!-- <span class="jeepay-tip-text">
            </span> -->
          <!-- 商户可配费率范围  仅运营平台可见 目前（20230922）联动惠商侧此接口范围不准确，暂时注掉 -->
          <!-- <div v-if="configMode == 'mgrApplyment'" style="margin-left: 30px;">
              商户可配费率范围<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> -->
            
          <div v-if="vdata.channelVar2">
            <p style="margin-top: 30px;"><b>费率配置错误响应数据:</b></p><span style="color: red;">{{ vdata.channelVar2 }}</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.applyData.merchantType != '1'" key="splitSignConfig">
        <template #tab>
          分账电签
          <a-tooltip
            title="使用场景：开通分账并使用电子签约"
          >
            <info-circle-outlined />
          </a-tooltip>
        </template>
        <a-form
          ref="splitSignRef"
          :model="vdata.applyData"
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 8 }"
          :rules="vdata.rules"
        >
          <a-divider class="jeepay-m-divider" orientation="left" style="color: #1A66FF;">分账电签状态信息</a-divider>
          <a-form-item label="">
            分账资料审核状态：
            {{ vdata.splitSignInfo['status'] == 0?'审核中':vdata.splitSignInfo['status'] == 1?'审核通过'
              :vdata.splitSignInfo['status'] == 2?'审核驳回':'未知' }}
            <a-button :loading="vdata.bizQueryInfoBtnLoading" size="small" style="margin-left: 20px;" type="primary" @click="merchantSplitSignQuery"><reload-outlined />刷新</a-button>
            <p v-if="vdata.splitSignInfo['failMsg']">失败原因：{{ vdata.splitSignInfo['failMsg'] }}</p>
            <p v-if="vdata.splitSignInfo['contractNo']">协议编号：{{ vdata.splitSignInfo['contractNo'] }}</p>
            <p v-if="vdata.splitSignInfo['status'] == 1">
              商户签约状态：
              {{ vdata.splitSignStateInfo['merSignState'] == 1?'待签约':vdata.splitSignStateInfo['merSignState'] == 2?'签约中'
                :vdata.splitSignStateInfo['merSignState'] == 3?'签约完成':vdata.splitSignStateInfo['merSignState'] == 4?'签约失败':'未知' }}
            </p>
            <p v-if="vdata.splitSignInfo['status'] == 1">
              OEM签约状态：
              {{ vdata.splitSignStateInfo['lpSignState'] == 1?'待签约':vdata.splitSignStateInfo['lpSignState'] == 2?'签约中'
                :vdata.splitSignStateInfo['lpSignState'] == 3?'签约完成':vdata.splitSignStateInfo['lpSignState'] == 4?'签约失败':'未知' }}
            </p>
          </a-form-item>

          <a-form-item v-if="vdata.splitSignInfo['merSignUrl']" label="">
            <p>
              签约地址:
              <a :href="vdata.splitSignInfo['merSignUrl']" target="_blank">{{ vdata.splitSignInfo['merSignUrl'] }}</a>
            </p>
            <p>签约二维码：</p>
            <QrcodeVue :value="vdata.splitSignInfo['merSignUrl']" :size="150" class="qrcode" />
            <br>
            <p class="jeepay-tip-text">(温馨提示:请联系商户签约人进行签约)</p>
          </a-form-item>


          <a-divider class="jeepay-m-divider" orientation="left" style="color: #1A66FF;">分账电签申请</a-divider>

          <a-form-item label="商户签约人类型" name="merSignType">
            <a-radio-group v-model:value="vdata.applyData.merSignType">
              <a-radio value="1">法人</a-radio>
              <a-radio value="2">经办人</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item label="商户签约人手机号码" name="merSignPhone">
            <a-input v-model:value.trim="vdata.applyData.merSignPhone" />
          </a-form-item>
          
          <div v-if="vdata.applyData.merSignType == '2'">
            <a-form-item label="经办人身份证人像面照片" name="merCardHeadsPic">
              <JeepayUpload v-model:src="vdata.applyData.merCardHeadsPic" bizType="applyment" ocrType="idCard" @ocrScan="ocrScanFunc" />
              <span class="jeepay-tip-text">(上传图片自动识别 身份证名称 身份证号)</span>
            </a-form-item>

            <a-form-item label="经办人身份证国徽面照片" name="merCardTailsPic">
              <JeepayUpload v-model:src="vdata.applyData.merCardTailsPic" bizType="applyment" />
            </a-form-item>

            <a-form-item label="经办人电签授权书" name="merContractAuth">
              <JeepayUpload v-model:src="vdata.applyData.merContractAuth" bizType="applyment" />
            </a-form-item>

            <a-form-item label="商户签约人姓名" name="merSignName">
              <a-input v-model:value.trim="vdata.applyData.merSignName" />
            </a-form-item>
            <a-form-item label="商户签约人身份证号" name="merSignCard">
              <a-input v-model:value.trim="vdata.applyData.merSignCard" />
            </a-form-item>
          </div>
        </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="merchantSignApply()"><check-outlined />发起申请</a-button>
        </div>
      </a-tab-pane>
      <a-tab-pane v-if="vdata.applyData.merchantType != '1'" key="splitMchList" tab="收账方信息">
        <div style="margin-left: 30px;">
          <p style="margin-top: 5px; margin-bottom: 5px; color: #2358e8;">说明：审核通过的接收方，才能接收分账。<br>如未有审核通过的接收方，会被当做“该商户未开通分账功能”，不能成功发起分账订单</p>
          <br>
          已审核通过的分账接收方：<a-button :loading="vdata.bizQueryInfoBtnLoading" size="small" style="margin-left: 20px;" type="primary" @click="splitMchListQuery()"><reload-outlined />刷新</a-button>
          <div v-for="(item, index) in vdata.splitMchList" :key="index" style="margin-top: 5px; margin-bottom: 5px; color: #2358e8;">{{ item }}</div>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
  <div v-else>
    <a-result title="暂无更多操作">
      <template #icon>
        <smile-twoTone />
      </template>
    </a-result>
  </div>
</template>

<script lang="ts" setup>

import { ref, nextTick, inject } from 'vue'
import ruleGenerator from '@/utils/ruleGenerator'
import { API_URL_MCH_APPLYMENT_LIST, req, $hmpayAfterOperate } from '@/api/manage'
import { getCurrentInstance, reactive } from 'vue'
import NextBizsCommonPage from '../../commons/NextBizsCommonPage.vue'
import QrcodeVue from 'qrcode.vue'

const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties
const jeepayPaywayRatePanelRef = ref()
const nextBizsCommonPage = ref()
const splitSignRef = ref()
let configMode : any = inject('configMode')


const vdata : any = reactive({
  state: '',
  ifCode: '',
  mchNo: '',
  recordId: null, // 更新对象ID
  applyData: {} as any, // 进件资料对象
  bizRateInfoList: [] as any, // 业务开通查询响应数据对象
  splitMchList: [] as any, // 分账接收方查询响应数据对象
  btnLoading: false, // 编辑类按钮
  bizQueryInfoBtnLoading: false, // 查询类按钮
  splitSignInfo: {} as any, // 分账电签查询响应数据对象
  splitSignStateInfo: {} as any, // 分账电签签约状态查询响应数据对象
  rules: {
    merSignType: [ ruleGenerator.requiredSelect('商户签约人类型', 'string') ],
    merSignPhone: [ ruleGenerator.requiredInput('商户签约人手机号码') ],
    merCardHeadsPic: [ ruleGenerator.requiredUpload('经办人身份证人像面照片') ],
    merCardTailsPic: [ ruleGenerator.requiredUpload('经办人身份证国徽面照片') ],
    merContractAuth: [ ruleGenerator.requiredUpload('经办人电签授权书') ],
    merSignName: [ ruleGenerator.requiredInput('商户签约人姓名') ],
    merSignCard: [ ruleGenerator.requiredInput('商户签约人身份证号') ]
  }
})

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.channelVar2 = res
      $infoBox.message.error(res)
    } else {
      vdata.channelVar2 = ''
      $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 merchantSignApply() {
  splitSignRef.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 merchantSplitSignQuery() {
  vdata.bizQueryInfoBtnLoading = true
  vdata.splitSignInfo = {}
  $hmpayAfterOperate(vdata.ifCode, vdata.mchNo, vdata.recordId, 4, vdata.applyData).then((res) => {
    if (res) {
      vdata.splitSignInfo = JSON.parse(res)
      if (vdata.splitSignInfo['status'] == 1) {
        // 分账资料审核通过后再查询签约状态
        splitSignStateQuery()
      }
    }
    $infoBox.message.success('刷新成功', 0.5)
    vdata.bizQueryInfoBtnLoading = false
  }).catch(() => {
    vdata.bizQueryInfoBtnLoading = false
  })
}

// 查询电签开通信息
function splitSignStateQuery() {
  vdata.bizQueryInfoBtnLoading = true
  vdata.splitSignStateInfo = {}
  $hmpayAfterOperate(vdata.ifCode, vdata.mchNo, vdata.recordId, 5, vdata.applyData).then((res) => {
    if (res) {
      vdata.splitSignStateInfo = JSON.parse(res)
    }
    vdata.bizQueryInfoBtnLoading = false
  }).catch(() => {
    vdata.bizQueryInfoBtnLoading = false
  })
}

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

function selectTabs (key) { // 切换tab
  if(key == 'signConfig') {
    nextTick(() => {
      nextBizsCommonPage.value.pageRender(vdata.recordId) // 直接调用通用组件
    })
  } else if(key == 'splitSignConfig') {
    merchantSplitSignQuery()
  } else if(key == 'splitMchList') {
    splitMchListQuery()
  }
  // 第三方可配费率范围查询有问题，暂不使用
  // else if(key == 'payWayRateConfig' && configMode == 'mgrApplyment') {
  //   merchantRateQuery()
  // }
}

// 对外暴露的 页面渲染函数  也用作初始化
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
    // 渠道拓展参数2 用来存放费率失败信息
    vdata.channelVar2 = res.channelVar2

    if (vdata.state != '1') {
      nextTick(() => {
        nextBizsCommonPage.value.pageRender(applyId) // 直接调用通用组件
      })
    }
  })
}

// 图片识别的回调函数  经办人身份证
function ocrScanFunc(orcObject){
  if(orcObject){
    if(orcObject.idcardName){
      vdata.applyData.merSignName = orcObject.idcardName
    }
    if(orcObject.idcardNo){
      vdata.applyData.merSignCard = orcObject.idcardNo
    }
  }
}
defineExpose({ pageRender })
</script>
