<!--
  盛付通： 【参数配置】 页面内容

  @author terrfly
  @site https://www.jeequan.com
  @date 2022/11/03 08:35
-->
<template>
  <div>
    <AppConfigCommonPage ref="appConfigCommonPageRef">
      <template v-if="isShowWxConfigAndAdConfigPage()" #wxConfigPage>
        <a-form layout="vertical">
          <a-row>
            <a-divider class="jeepay-m-divider" orientation="left" :orientationMargin="0">
              <span style="font-size: 16px;font-weight: 600;color: var(--ant-primary-color);">微信配置项</span>
            </a-divider>
            <a-col style="margin-top: 10px;" :span="24">
              <a-form-item label="第三方交易识别码：">
                <a-input v-model:value.trim="vdata.partner" class="form-item-content" />
                <a-button
                  class="jeepay-m-btn"
                  data-type="text"
                  size="small"
                  style="margin-left: 20px; margin-top: 10px !important;"
                  type="primary"
                  @click="getMchPartnerFunc"
                >
                  <save-outlined />查询第三方交易识别码
                </a-button>
                <span class="jeepay-tip-text">请输入或查询第三方交易识别码，获取到之后再进行微信配置</span>
              </a-form-item>
            </a-col>

            <a-col :span="isMobile ? 24 : 12">
              <a-form-item class="jeepay-valid" label="微信支付目录：" style="margin: 0;">
                <a-input v-model:value.trim="vdata.configWxPayBaseUrl" class="form-item-content" />
                <a-button
                  class="jeepay-m-btn"
                  data-type="text"
                  size="small"
                  style="margin-left: 20px !important;"
                  type="primary"
                  @click="configInterfaceFunc('PAY_BASE_URL', vdata.configWxPayBaseUrl)"
                >
                  <save-outlined />配置
                </a-button>
              </a-form-item>
            </a-col>
            <a-col :span="isMobile ? 24 : 12">
              <a-form-item class="jeepay-valid" label="关联服务商公众号/小程序appId：" style="margin: 0;">
                <a-input v-model:value.trim="vdata.configWxBindAppId" class="form-item-content" />
                <a-button
                  class="jeepay-m-btn"
                  data-type="text"
                  size="small"
                  style="margin-left: 20px !important;"
                  type="primary"
                  @click="configInterfaceFunc('BIND_APP_ID', vdata.configWxBindAppId)"
                >
                  <save-outlined />配置
                </a-button>
              </a-form-item>
            </a-col>
            <a-col :span="isMobile ? 24 : 12">
              <a-form-item class="jeepay-valid" label="关注appId：" style="margin: 0;">
                <a-input v-model:value.trim="vdata.configWxSubscribeAppId" class="form-item-content" />
                <a-button
                  class="jeepay-m-btn"
                  data-type="text"
                  size="small"
                  style="margin-left: 20px !important;"
                  type="primary"
                  @click="configInterfaceFunc('SUBSCRIBE_APP_ID', vdata.configWxSubscribeAppId)"
                >
                  <save-outlined />配置
                </a-button>
              </a-form-item>
            </a-col>
      
            <a-col :span="24">
              <div class="jeepay-m-pz">
                <a-popover placement="top">
                  <template #title><span>一键配置微信配置项</span></template>
                  <template #content>
                    <p>顺序：查询第三方交易识别码 --> 微信支付目录 --> 公众号AppId --> 小程序AppId --> 关注AppId </p>
                    <p>提示： 若有异常则结束配置</p>
                  </template>
                  <a-button class="jeepay-m-btn" data-type="text" type="primary" @click="autoConfigFunc"><alert-outlined />一键配置微信配置项</a-button>
                </a-popover>
                <a-button class="jeepay-m-btn" data-type="text" style="margin-left: 20px;" type="primary" @click="queryFunc"><bars-outlined />微信参数查询</a-button>
              </div>
            </a-col>
          </a-row>
        </a-form>
      </template>
      <template #advancedConfigPage><div /></template>
    </AppConfigCommonPage>
  </div>
</template>

<script lang="ts" setup>
import { $queryInterfaceConfig, $configInterfaceConfig, $getMchPartner } from '@/api/manage'
import {ref, reactive, inject, getCurrentInstance} from 'vue'
import AppConfigCommonPage from '../../commons/AppConfigCommonPage.vue'
const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties

// 接收父组件的参数注入： 配置方式 (判断是 运营平台  代理商 还是商户 )
let configMode : any = inject('configMode')

// 接收父组件的参数注入： 进件详细欣欣
let applyRecord : any = inject('applyRecord')

// 参数注入： 是否手机端
let isMobile : any = inject('isMobile')
// 接收父组件的参数注入： 选择的商户应用
let appConfigModeByMchAppId : any = inject('appConfigModeByMchAppId')
// 接收父组件的参数注入： 选择的渠道
let appConfigModeBySelectedIfCode : any = inject('appConfigModeBySelectedIfCode')

const vdata : any = reactive({
  recordId: null, // 更新对象ID
  
  configWxPayBaseUrl: '', // 微信支付目录
  configWxBindAppId: '', // 关联应用
  configWxBindLiteAppId: '', // 关联小程序
  configWxSubscribeAppId: '', // 关注公众号ID

  // 费率配置模式， 根据进件模式 进行赋值。 
  rateConfigMode: configMode == 'mgrApplyment' ? 'mgrMch' : null
})

const appConfigCommonPageRef = ref()

// 对外暴露的 页面渲染函数  也用作初始化
function pageRender (applyId){
  // 原逻辑的复用 
  vdata.recordId = applyId

  //重置配置
  vdata.configWxPayBaseUrl = ''
  vdata.configWxBindAppId = ''
  vdata.configWxBindLiteAppId = ''
  vdata.configWxSubscribeAppId = ''

  if (vdata.recordId) {
    $queryInterfaceConfig(vdata.recordId, null, null).then((res2) => {
      vdata.configWxPayBaseUrl = res2.paySiteUrl
      vdata.configWxBindAppId = res2.wxAppId
      vdata.configWxBindLiteAppId = res2.wxLiteAppId
      vdata.configWxSubscribeAppId = res2.wxAppId
    })
  }else {

      // 查询配置信息 
      commonQueryInterfaceConfigFunc().then((res2) => {
        vdata.configWxPayBaseUrl = res2.paySiteUrl
        vdata.configWxBindAppId = res2.wxAppId
        vdata.configWxBindLiteAppId = res2.wxLiteAppId
        vdata.configWxSubscribeAppId = res2.wxAppId
      })
  }
    
  appConfigCommonPageRef.value.pageRender(applyId) // 直接调用通用组件
}

// 给diy页面的全局公用函数 （ 请求在一个地方处理 ）
function commonQueryInterfaceConfigFunc(){

  // 查询配置信息参数。 
  let reqApplyId = vdata.recordId
  let applyIdConvertMchAppId = 0
  let convertMchAppIfCode :any = null

  // 应用配置页面 需要做转换
  reqApplyId = appConfigModeByMchAppId
  applyIdConvertMchAppId = 1
  convertMchAppIfCode = 'utmpay'

  // 查询配置信息 
  return $queryInterfaceConfig(reqApplyId, applyIdConvertMchAppId, convertMchAppIfCode)

}

// 配置本系统的app应用配置项
function getMchPartnerFunc(){

  const appId = getSelectedConfigAppId()

  if(!appId){
    $infoBox.message.error('请选择商户应用')
    return Promise.reject()
  }

  let recordId = vdata.recordId
  let appConfigModeIfCode = ''

  if (!vdata.recordId) {
    recordId = appConfigModeByMchAppId
    appConfigModeIfCode = appConfigModeBySelectedIfCode
  }
  return $getMchPartner(recordId, appId, appConfigModeIfCode).then((res) => {
    vdata.partner = res.data
    $infoBox.message.success('查询成功 ')
    return Promise.resolve()
  })

}

// 配置接口相关配置信息
function configInterfaceFunc(configType, configVal){

  let appId = getSelectedConfigAppId()

  if(!appId){
    $infoBox.message.error('请选择商户应用')
    return Promise.reject()
  }

  if(!configVal){
    $infoBox.message.error('请填写对应参数值!')
    return Promise.reject()
  }

  let reqData = {
    configWxPayBaseUrl: vdata.configWxPayBaseUrl, // 微信支付目录
    configWxBindAppId: vdata.configWxBindAppId, // 关联公众号ID
    configWxSubscribeAppId: vdata.configWxSubscribeAppId, // 关注公众号ID
    partner: vdata.partner
  }
  // 默认为进件记录ID、商户应用appId
  let recordId = vdata.recordId
  // 默认为空
  let appConfigModeAndIfCode = ''
  // 当进件记录ID为空时取透传的商户应用appId；类型默认为当前ifcode
  if (!recordId) {
    appConfigModeAndIfCode = appConfigModeBySelectedIfCode
    
    recordId = appConfigModeByMchAppId
    appId = appConfigModeByMchAppId
  }

  return $configInterfaceConfig(recordId, appId, configType, JSON.stringify(reqData), appConfigModeAndIfCode).then((res) => {
      
      if(res.channelState == 'CONFIRM_SUCCESS'){
         $infoBox.message.success('配置完成')
        return Promise.resolve()
      }

      $infoBox.modalError('接口配置失败：' + '[' + res.channelErrCode + ']' + res.channelErrMsg)
      return Promise.reject()
  })

}

// 一键配置 ( 顺序 --》 先配置本系统的商户应用参数信息 --》 接口侧的 支付目录  --》 appId --> 小程序appId  --> 关注公众号  )【若有报错则停止执行】
// async await  其实就是 Prosise的语法糖。 只有then才会进入下一个 await
async function autoConfigFunc(){

  if(vdata.configWxPayBaseUrl){
    await configInterfaceFunc('PAY_BASE_URL', vdata.configWxPayBaseUrl)
  }

  if(vdata.configWxBindAppId){
    await configInterfaceFunc('BIND_APP_ID', vdata.configWxBindAppId)
  }

  if(vdata.configWxBindLiteAppId){
    await configInterfaceFunc('BIND_APP_ID', vdata.configWxBindLiteAppId)
  }

  if(vdata.configWxSubscribeAppId){
    await configInterfaceFunc('SUBSCRIBE_APP_ID', vdata.configWxSubscribeAppId)
  }

}


function queryFunc(){
  const appId = getSelectedConfigAppId()

  if(!appId){
    $infoBox.message.error('请选择商户应用')
    return Promise.reject()
  }

  return $configInterfaceConfig(vdata.recordId, appId, 'QUERY', '1', null).then((res) => {
    $infoBox.modalSuccess('查询结果：', res)
  })

}

// 是否显示 微信配置和 高级配置项目  ( 仅 运营平台显示 )
function isShowWxConfigAndAdConfigPage(){
  return (configMode == 'mgrApplyment' || configMode == 'mgrMch')
}


// 获取当前配置的APPID
function getSelectedConfigAppId(){
  return appConfigModeByMchAppId ? appConfigModeByMchAppId : appConfigCommonPageRef.value.getSelectedConfigAppId()
}

defineExpose({ pageRender, getSelectedConfigAppId })
</script>
<style scoped>
.form-item-content{
  width: 70%
}

</style>
