<!--
  进件详细信息的入口页面（包含 ： 保存草稿， 发起进件）

  @author terrfly
  @site https://www.jeequan.com
  @date 2022/05/07 10:20
-->

<template>
  <a-card class="table-card"  v-if="vdata.mobileType == 'tab'" >
    <div  class="applyments_headers">
      <div v-if="!isMobile" style="display: flex; justify-content: space-between; line-height: 60px; background-color: white;">
        <a-button style="line-height: 60px;" type="text" @click="emits('switchApplyPage', 'list')"><left-outlined />返回列表页</a-button>
        <div style="font-weight: bold; margin-left: 30px;"> {{ isView ? '查看进件信息' : '填写进件资料' }}</div>
        <div style="width: 400px; display: flex; align-items: center; justify-content:space-evenly">
          <a-button v-if="!isView" @click="showMobileQrcode"><qrcode-outlined />手机扫码填写</a-button>

          <a-button v-if="!isView" @click="mergeApplyDetailInfosFunc('')"><bulb-outlined />智能读取</a-button>
          <a-tooltip v-if="!isView" placement="left" title="保存草稿将不验证数据的合法性">
            <a-button type="primary " @click="saveDataFunc(true)"><save-outlined />  保存草稿 </a-button>
          </a-tooltip>
        </div>
      </div>
      <a-divider style="margin: 0" />
    </div>
    <slot name="top">
      <!-- 吸顶： 返回列表 / 智能读取 / 保存草稿 按钮项 -->
      <a-affix offsetTop="0">

      </a-affix>
    </slot>
    <a-card v-if="mchApplymentData.state == 3" style="width: 90%;margin: 60px 0px 15px 20px; padding: 12px; background-color: #fff1f0;">
      <a-row type="flex" style="color: red;">
        <a-col flex="auto"><exclamation-circle-outlined /> {{ mchApplymentData.applyErrorInfo }}</a-col>
      </a-row>
    </a-card>

    <!-- 引入具体的接口组件  -->
    <component :is="vdata.currentComponent" :channelAppId="mchApplymentData.appid" :channelIsvNo="mchApplymentData.isvNo" ref="ifCodeComponentRef" />

    <slot name="bottom">
      <!-- 底部操作项 -->
      <a-affix v-if="!isView" :offset-bottom="20">
        <div style="background-color: white;">
          <a-divider style="margin: 0; margin-top: 20px;" />

          <div class="bottom-buttons">
            <div class="bottom-buttons-item" @click="emits('switchApplyPage', 'list')">
              <a-button type="link" style="color: #808080 ;"><left-outlined />返回列表页</a-button>
            </div>
            <div style="width: 1px; height: 100%; background-color: #f0f0f0;" />
            <a-tooltip v-if="!isView" placement="left" title="保存草稿将不验证数据的合法性">
              <div   class="bottom-buttons-item">
                <a-button type="link " @click="saveDataFunc(true)"><save-outlined />  保存草稿 </a-button>
              </div>
            </a-tooltip>


            <div style="width: 1px; height: 100%; background-color: #f0f0f0;" />
            <div class="bottom-buttons-item" @click="saveDataFunc(false)">
              <a-button type="link">发起进件<send-outlined /></a-button>
            </div>
          </div>
        </div>
      </a-affix>
    </slot>
  </a-card>

  <a-card class="table-card"  v-if="vdata.mobileType == 'tabMobile'" >

    <div class="success-box ">
      <div><CheckCircleTwoTone style="font-size: 50px;" /></div>
      <div><span class="notice">提交成功，等待审核中</span></div>
    </div>
  </a-card>

  <a-modal v-model:visible="vdata.isShowMobileQr" title="手机扫码填写" :footer="null" :width="300">
    <div style="width:100%;margin-bottom:20px;text-align:center">
      <div id="qrCodeUrl" style="width: 300px" class="qrcode" />
      <QrcodeVue :value="vdata.mobileQrUrl" :size="250" class="qrcode" />
      <br>
      <p style="color:red">为避免信息泄露，请当前系统登录者扫码！ 不要将二维码发送给他人！ </p>
    </div>
  </a-modal>
</template>
<script setup lang="ts">

import {ref, reactive, computed, getCurrentInstance, inject, defineEmits, nextTick, defineExpose, provide} from 'vue'
import { API_URL_MCH_APPLYMENT_LIST, $getMergeApplyDetailInfos, reqLoad, $getIsvChannelConfig } from '@/api/manage'
import QrcodeVue from 'qrcode.vue'
import storage from '@/utils/jeepayStorageWrapper'
import { getOriginIfCode } from '../util/jeepayComponentUtil.js'


const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties

const ifCodeComponentRef = ref()

// list页面的 切换页面的函数
const emits = defineEmits(['switchApplyPage'])

// 当前页面的对象信息
const vdata : any = reactive({
  mobileType:"tab",
  currentComponent: null,
  applymentDetailInfo: {}, //进件详细参数，JSON串

  isShowMobileQr: false,  // 是否显示手机扫码二维码
  mobileQrUrl: '' // 二维码地址

})

// 参数注入： 接收进件参数（包含 用户号， ifCode ）
let mchApplymentDataRef : any = inject('mchApplymentData')
let mchApplymentData : any = mchApplymentDataRef.value

// 参数注入： 是否预览模式
let isView : any = inject('isView')

// 参数注入： 是否手机端
let isMobile : any = inject('isMobile')

// 参数注入： 副本来源
let copyInfoSourceApplyId : any = inject('copyInfoSourceApplyId')


// 向子组件注入： 进件参数具体数据
provide('applymentDetailInfo', computed( ()=> vdata.applymentDetailInfo) )


// 智能读取
function mergeApplyDetailInfosFunc(fixApplyId){

  // 传入当前页面操作的 ifCode 到后台
  const ifCodeView = getOriginIfCode(mchApplymentData.ifCode)

  console.log(mchApplymentData,'mchApplymentDatamchNo')
  return $getMergeApplyDetailInfos(mchApplymentData.mchNo, fixApplyId, ifCodeView).then(res => {
    $infoBox.message.info('读取成功')
    if(ifCodeView == 'lklspay'){
      if(copyInfoSourceApplyId.value || !fixApplyId) {
        delete res.mccCode
        delete res.settAccountBankBranchAreaCode
        delete res.settAccountBankName
        delete res.settAccountBankBranchName
        // delete res.settAccountNo
        delete res.mchAreaCode
      }
    }

    if(ifCodeView == 'yspay'){
      if(copyInfoSourceApplyId.value || !fixApplyId) {
        delete res.mccCode
        delete res.areaCode
        delete res.bankSubCode
        // delete res.settAccountNo
        delete res.settAccountBankBranchAreaCode
        delete res.settAccountBankBranchName
        delete res.settAccountBankName
      }
    }

    if(ifCodeView == 'ryxpay' ){
      if(copyInfoSourceApplyId.value || !fixApplyId) {
        delete res.mccCode
        delete res.mccName
        delete res.areaCode
        delete res.areaName
        delete res.bankSubCode
        delete res.settAccountNo
        delete res.settAccountBankBranchAreaCode
        delete res.settAccountBankName
        delete res.settAccountBankBranchName
        delete res.mchFullName
      }
    }


    if(ifCodeView == 'sxfpay'){
      if(copyInfoSourceApplyId.value || !fixApplyId){
          delete res.mccCode
          delete res.areaCode
          delete res.bankSubCode
          delete res.settAccountNo
          delete res.settAccountBankBranchAreaCode
          delete res.settAccountBankBranchName
          delete res.settAccountBankBranchCode
          delete res.settAccountBankName
      }
    }

    if(ifCodeView == 'zftpay'){
      if(copyInfoSourceApplyId.value || !fixApplyId){
        delete res.mccCode
        delete res.areaCode
        delete res.bankSubCode
        delete res.settAccountNo
        delete res.settAccountBankBranchAreaCode
        delete res.settAccountBankBranchName
        delete res.settAccountBankBranchCode
        delete res.settAccountBankName
      }
    }
    console.log(res,'resresresresresresresres')
    if(ifCodeView == 'dgpay' ){
      if(copyInfoSourceApplyId.value || !fixApplyId) {
        delete res.regCapital
        delete res.mccCode
        delete res.bankSubCode
        delete res.branchName
        delete res.branchCode
        delete res.areaCode
        delete res.bankCode
        delete res.settAccountBankBranchName
        delete res.openAccCityName
        delete res.settAccountBankName
        delete res.settAccountNo
        delete res.settAccountBankBranchAreaCode
        delete res.settAccountBankName
      }
    }

    if(ifCodeView == 'kqpay'){
      if(copyInfoSourceApplyId.value || !fixApplyId) {
        delete res.mccCode
        delete res.areaCode
        delete res.contactEmail
        delete res.settAccountNo
        delete res.settAccountLicenseImg
        delete res.settAccountBankBranchAreaCode

        delete res.settAccountBankName
        delete res.settAccountBankBranchName
      }
    }

    console.log(ifCodeView,res,'ifCodeViewifCodeViewifCodeViewifCodeView')
    Object.assign(vdata.applymentDetailInfo, res)
    if(ifCodeComponentRef.value.mergeApplyDetailInfosCallback){
      ifCodeComponentRef.value.mergeApplyDetailInfosCallback()
    }
  })
}

// 保存草稿的事件
function saveDataFunc(isTemp){
  console.log(mchApplymentData)

  if(!ifCodeComponentRef.value.saveDataPreCallback){
    return Promise.reject()
  }

  // 调用子组件的回调函数
  return ifCodeComponentRef.value.saveDataPreCallback(isTemp).then(() => {

    // 参数复制
    let reqData = Object.assign({}, mchApplymentData)

    reqData.isTempData = isTemp
    console.log(vdata.applymentDetailInfo,'vdataapplymentDetailInfo')
    reqData.mchFullName = vdata.applymentDetailInfo.mchFullName
    reqData.mchShortName = vdata.applymentDetailInfo.mchShortName
    reqData.merchantType = vdata.applymentDetailInfo.merchantType
    reqData.contactName = vdata.applymentDetailInfo.contactName
    reqData.contactPhone = vdata.applymentDetailInfo.contactPhone
    reqData.areaCode = vdata.applymentDetailInfo.areaCode ? vdata.applymentDetailInfo.areaCode[2] : null
    reqData.address = vdata.applymentDetailInfo.address

    //  替换paywayFeeList
    let applymentDetailInfoCopy = Object.assign({}, vdata.applymentDetailInfo)
    if(applymentDetailInfoCopy.reqPaywayFeeList){
      applymentDetailInfoCopy.paywayFeeList = applymentDetailInfoCopy.reqPaywayFeeList
    }

    delete applymentDetailInfoCopy.reqPaywayFeeList

    reqData.applyDetailInfo = JSON.stringify(applymentDetailInfoCopy)

    // 组装报文， 发送请求
    if(mchApplymentData.applyId){
      return reqLoad.updateById(API_URL_MCH_APPLYMENT_LIST, mchApplymentData.applyId, reqData).then( res => {
        return submitSuccess(isTemp)
      })
    }else{
      return reqLoad.add(API_URL_MCH_APPLYMENT_LIST, reqData).then( res => {
        return submitSuccess(isTemp)
      })
    }
  })
}

// 封装： 新增 or 修改保存 的响应事件
function submitSuccess(isTempData){
  $infoBox.message.success(isTempData ? '保存成功' : '提交成功，请等待审核')
  if(isMobile && !isTempData){
    vdata.mobileType = 'tabMobile'
  }else{
    vdata.mobileType = 'tab'
  }
  // 返回列表
  emits('switchApplyPage', 'list')

  return Promise.resolve()
}

// 页面渲染函数
function pageRender(){

  // props.selectIfCode格式： ifCode或ifCode_1等等，保存数据使用传入的ifCode或ifCode_1，页面渲染使用ifCode(需截取ifCode_1)
  const ifCodeView = getOriginIfCode(mchApplymentData.ifCode)

  // 根据支付接口名称  动态引入组件
  import(`./diy/${ifCodeView}/Applyment.vue`).then((module) => {
    vdata.currentComponent = module.default

    // 加载已存的数据
    if(mchApplymentData.applyDetailInfo){
      vdata.applymentDetailInfo = JSON.parse(mchApplymentData.applyDetailInfo)
    }

    // 服务商渠道参数配置
    $getIsvChannelConfig(mchApplymentData.mchNo, mchApplymentData.ifCode, mchApplymentData.isvNo).then(res => {
      if (res) {
        Object.assign(vdata.applymentDetailInfo, res)
      }
    })

    // 副本来源
    if(copyInfoSourceApplyId?.value){
      nextTick(() => {
        mergeApplyDetailInfosFunc(copyInfoSourceApplyId.value)
      })
    }

  })

}

// 显示手机扫码二维码地址二维码
function showMobileQrcode(){

  let url = ''

  let jeepayToken = storage.getToken()
  let autoConfigMchAppId = ''
  if(mchApplymentData.autoConfigMchAppId != undefined){
    autoConfigMchAppId = mchApplymentData.autoConfigMchAppId
  }
  // 包含 记录ID
  if(mchApplymentData.applyId){

    url = `${window.location.origin}/h5MchApplyment?isView=${isView.value ? 1 : 0 }&jeepayToken=${jeepayToken}&autoConfigMchAppId=${autoConfigMchAppId}&applyId=${mchApplymentData.applyId}&isvNo=${mchApplymentData.isvNo}&mchNo=${mchApplymentData.mchNo}&range=${mchApplymentData.range}`
  }else{

    let copyInfoSourceApplyIdParam : any = ''
    // 副本来源
    if(copyInfoSourceApplyId && copyInfoSourceApplyId.value){
      copyInfoSourceApplyIdParam =copyInfoSourceApplyId.value
    }
    url = `${window.location.origin}/h5MchApplyment?isView=${isView.value ? 1 : 0 }&jeepayToken=${jeepayToken}&autoConfigMchAppId=${autoConfigMchAppId}&mchNo=${mchApplymentData.mchNo}&ifCode=${mchApplymentData.ifCode}&copyInfoSourceApplyId=${copyInfoSourceApplyIdParam}&isvNo=${mchApplymentData.isvNo}&range=${mchApplymentData.range}`
  }

  vdata.mobileQrUrl = url

  console.log(url)

  vdata.isShowMobileQr = true
}

defineExpose({ pageRender, saveDataFunc, mergeApplyDetailInfosFunc })
</script>
<style  lang="less" scoped>

.bottom-buttons{
  display: flex; flex-direction: row; justify-content: center; height: 60px;

  .bottom-buttons-item{
    flex-grow: 1; display: flex; flex-direction: column; justify-content: center;
  }

  .bottom-buttons-item:hover{
    transition: 0.3s ease;
    background-color: rgba(23, 91, 230, 0.05);
    cursor: pointer;
  }

}
.applyments_headers{
  // position: fixed;
  // top: 70px;
  // right: 42px;
  // width: 82.5%;
  // padding: 10px;
  // width: 80%;
  // z-index: 99;
  // border-radius: 10px 0 10px 0;
  // background-color:#f9f9f9 !important;
  // justify-content: flex-start !important;
}
.applyments_headers::after{
  // border-bottom:1px solid #c3c3c3 ;
}
.jeepay-m-center{
  // margin-top:100px !important;
}
//.table-card-success{
//  position: fixed;
//  top: 50%;
//  left: 50%;
//  transform: translate(-50%);
//}

.success-box {
  position: fixed;
  top: 20%;
  left: 50%;
  transform: translate(-50%);
  background: #fff;
  width: 100%;

  div{
    text-align: center;
    padding: 5px 0;
  }

  .notice {
    font-size: 20px;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    line-height: 30px;
  }
}
</style>
