<!--
  手机端的进件访问页面

  使用端： APP、小程序； web端二维码

  @author terrfly
  @site https://www.jeequan.com
  @date 2022/10/25 16:36
-->

<template>
  <div>
    <div v-if="vdata.divMode == 'loading'">请稍后。。。</div>

    <div v-if="vdata.divMode == 'applySuccess'"> 进件成功中间页 </div>

    <div v-if="vdata.divMode == 'applyInfo'">
      <JeepayMchApplymentDetailInfoEntry ref="jeepayMchApplymentDetailInfoEntryRef">
        <!-- 覆写子页面的排版 -->
        <template #top>
          <!-- <a-button v-if="!vdata.isView" @click="mergeApplyDetailInfosFunc"><bulb-outlined />智能读取</a-button>
        <a-button type="primary " @click="saveDataFunc(true)"><save-outlined />  保存草稿 </a-button> -->
          <div class="top-button">
            <!-- <div style="font-size: 16px; color: #000; font-weight: 500;"><span style="color: #2980FD;">1</span>/5主体信息</div> -->
          </div>
        </template>

        <!-- 覆写子页面的排版 -->
        <template #bottom>
          <!-- 底部操作项 -->
          <a-affix v-if="!vdata.isView" >
            <div class="bottom-buttons">
              <div class="button-top button-top-box-push" >
                <div class="bottom-buttons-item">
                  <a-button type="link" style="color: #808080 ;" @click="saveDataFunc(true)"><save-outlined />保存草稿</a-button>
                </div>
                <div class="bottom-buttons-item">
                  <a-button type="link" style="color: #808080 ;" @click="mergeApplyDetailInfosFunc('')"><bulb-outlined />智能读取</a-button>
                </div>
              </div>
              <div class="button-bottom" @click="saveDataFunc(false)">
                <a-button type="link"><send-outlined />发起进件</a-button>
              </div>
            </div>
          </a-affix>
        </template>
      </JeepayMchApplymentDetailInfoEntry>
    </div>
  </div>
</template>

<script setup lang="ts">

import { API_URL_MCH_APPLYMENT_LIST, reqLoad } from '@/api/manage'
import {ref, reactive, computed, provide, onMounted, nextTick, getCurrentInstance} from 'vue'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/store/modules/user'


// import './less/applyment.less'

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


const userStore = useUserStore()
const jeepayMchApplymentDetailInfoEntryRef = ref()


// 当前页面的对象信息
const vdata : any = reactive({

  divMode: 'loading', // loading: 等待页  applySuccess：发起成功中间页   applyInfo：进件详情填写

  mchApplymentData: {},   // 进件参数（包含 用户号， ifCode ）
  isView: false, // 是否保存模式
  isMobile: true, // 是否手机端
  copyInfoSourceApplyId: '', //副本信息
  isvNo: '', //渠道号
  autoConfigMchAppId: '', //应用号
})

// 参数注入： 接收进件参数（包含 用户号， ifCode ）  进件主表信息。
provide('mchApplymentData', computed( ()=> vdata.mchApplymentData) )

// 向子组件注入：是否预览模式
provide('isView', computed( ()=> vdata.isView) )

// 向子组件注入：是否手机端
provide('isMobile', computed( ()=> vdata.isMobile) )

// 副本来源
provide('copyInfoSourceApplyId', computed( ()=> vdata.copyInfoSourceApplyId) )


// 向子组件注入：渠道号
provide('isvNo', computed( ()=> vdata.isvNo) )

// 应用号
provide('autoConfigMchAppId', computed( ()=> vdata.autoConfigMchAppId) )


// 挂载事件
// 两种模式：
// A:  全新进件
// http://localhost:8000/h5MchApplyment?isView=0&jeepayToken=TOKEN&mchNo=M1665452692&ifCode=shengpay

// B: 预览 & 修改/继续填写
// http://localhost:8000/h5MchApplyment?isView=0&jeepayToken=TOKEN&applyId=A1584801300910874626
function isWeiXinBrowser() {
  var ua = navigator.userAgent.toLowerCase()
  var isWeixin = ua.indexOf('micromessenger') != -1
  if (isWeixin) {
    return true
  } else {
    return false
  }
}
onMounted(() => {
  // 判断为微信环境 加载微信jssdk
  if(isWeiXinBrowser()){
    const script = document.createElement('script')
    script.src = 'https://res.wx.qq.com/open/js/jweixin-1.3.2.js'
    script.type = 'text/javascript'
    document.head.appendChild(script)
  }

  // 加载js
  loadOnMessageJS()

  // URL 参数获取
  let queryObject : any = useRoute().query

  // 参数验证 jeepayToken 和 isView 必填
  if(!queryObject.jeepayToken || typeof(queryObject.isView) == 'undefined'){
    return $infoBox.message.error('参数有误')
  }

  // 是否预览模式
  vdata.isView = queryObject.isView == 1
  userStore.putToken(queryObject.jeepayToken) // 放置token

  // 包含applyId
  if(queryObject.applyId){


    reqLoad.getById(API_URL_MCH_APPLYMENT_LIST, queryObject.applyId, { originData: vdata.isView ? '0' : '1' } ).then(res => {
      let { applyId, channelApplyNo, mchNo, ifCode, applyDetailInfo, applyErrorInfo, state,isvNo,autoConfigMchAppId ,range} = res
      vdata.mchApplymentData = {applyId, channelApplyNo, mchNo, ifCode, applyDetailInfo, applyErrorInfo, state,isvNo,autoConfigMchAppId,range}
      vdata.divMode = 'applyInfo'
      nextTick(() => jeepayMchApplymentDetailInfoEntryRef.value.pageRender())  // 渲染组件

    })

  }else{ // 全新进件

    // 参数验证
    if(!queryObject.mchNo || !queryObject.ifCode){
      return $infoBox.message.error('参数有误')
    }

    vdata.mchApplymentData.mchNo = queryObject.mchNo
    vdata.mchApplymentData.ifCode = queryObject.ifCode
    vdata.mchApplymentData.autoConfigMchAppId = queryObject.autoConfigMchAppId

    vdata.mchApplymentData.isvNo = queryObject.isvNo
    vdata.mchApplymentData.range = queryObject.range
    vdata.isvNo = queryObject.isvNo
    vdata.range = queryObject.range

    // 副本信息, 自动读取。
    if(queryObject.copyInfoSourceApplyId){
      vdata.copyInfoSourceApplyId = queryObject.copyInfoSourceApplyId
    }


    vdata.divMode = 'applyInfo'
    nextTick(() => jeepayMchApplymentDetailInfoEntryRef.value.pageRender())  // 渲染组件
  }

})


// 引入三方厂商的 js文件
async function loadOnMessageJS(){

  // 以下代码： 本地可正常导入 window.uni , 但是打包后无法获取到uni对象。   分析原因是： vite rollup 会摇树删除无用的代码，导致功能不完整。
  // 暂时将js增加到了  最外层的 index.html 中。
  // ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
  // var userAgent = navigator.userAgent

  // // 导入 微信组件
  // if (/miniProgram/i.test(userAgent) && /micromessenger/i.test(userAgent)) {

  //   await import('./js/jweixin-1.6.0.js')
  // }

  // await import('./js/uni.webview.1.5.4.js').then(() => {
  //   // 待触发 `UniAppJSBridgeReady` 事件后，即可调用 uni 的 API。
  //   document.addEventListener('UniAppJSBridgeReady', () => {})
  // })

  // ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

  // index。html包含了 js组件， 直接添加即可。
  // 待触发 `UniAppJSBridgeReady` 事件后，即可调用 uni 的 API。
  document.addEventListener('UniAppJSBridgeReady', () => {})


}


// 直接调用子组件的函数
function mergeApplyDetailInfosFunc(fixApplyId){
  if(jeepayMchApplymentDetailInfoEntryRef.value){
    jeepayMchApplymentDetailInfoEntryRef.value.mergeApplyDetailInfosFunc(fixApplyId)
  }
}

// 直接调用子组件的函数
function saveDataFunc(f){
  if(jeepayMchApplymentDetailInfoEntryRef.value){
    jeepayMchApplymentDetailInfoEntryRef.value.saveDataFunc(f).then(() => {

      // eslint-disable-next-line
      if((window as any).uni){
        (window as any).uni.postMessage({data: {ctrl: 'toApplymentListAndRef'}})
        if(isWeiXinBrowser()){ //判断为微信环境 调用小程序回退页面方法 因为小程序 回退会立即关闭页面 所以用 timeout 延迟执行
          const timeOut = setTimeout(()=>{
            (window as any).wx.miniProgram.navigateBack({ delta: 1 })
          },500)
        }
        console.log('postMessage 推送完成')
      }
    })
  }
}
</script>

<style  lang="less" scoped>
// 引入进件页面相关样式
@import './less/applyment.less';

.top-button {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 0;
  padding: 0 20px;
  border-bottom: 1px solid #EDEDED;
}
.bottom-buttons {
  background-color: #fff;
  .button-top {
    display: flex;
    height: 50px;
    .bottom-buttons-item {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-grow: 1;
      border: 1px solid #EDEDED;
      &:first-child {
        border-right: none;
      }
    }
  }
  .button-bottom {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 50px;
    border: 1px solid #EDEDED;
    border-top: none;
  }
  .bottom-buttons-item:hover {
    transition: 0.3s ease;
    background-color: rgba(23, 91, 230, 0.05);
    cursor: pointer;
  }
}
.button-top-box-push{
  position: fixed;
  top: 0px;
  z-index: 999;
  width: 100%;
  background: #fff;
}
</style>