<!--
  通用 【参数配置】页面


  渠道方可以引入该页面：  可覆写三个插槽： appConfigPage 、 wxConfigPage ， advancedConfigPage


  @author terrfly
  @site https://www.jeequan.com
  @date 2022/11/03 08:35
-->
<template>
  <div v-if="vdata.recordId">
    <a-form layout="vertical">
      <a-row :gutter="16">
        <!-- 判断是否显示配置到应用 -->
        <template v-if="isShowConfig2AppPage()">
          <a-col :span="24">
            <a-form-item label="用户号：">
              <a-tag color="blue">{{ vdata.detailData.mchNo }}</a-tag>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="支付参数：">
              <a-textarea
                v-model:value="vdata.detailData.succResParameter"
                disabled="disabled"
                style="height: 100px;color: black"
              />
            </a-form-item>
          </a-col>
        </template>

        <a-divider v-if="isShowConfig2AppPage()" class="jeepay-m-divider" orientation="left" orientationMargin="0">
          <span style="font-size: 16px;font-weight: 600;color: var(--ant-primary-color);">应用配置</span>
        </a-divider>

        <!-- 判断是否显示配置到应用 -->
        <slot v-if="isShowConfig2AppPage()" name="appConfigPage">
          <a-col :span="isMobile ? 24 : 12">
            <a-form-item label="一键配置到应用：" style="margin: 0;">
              <a-select v-model:value="vdata.configAppId" placeholder="选择应用">
                <a-select-option key="">请选择商户应用</a-select-option>
                <a-select-option v-for="(item) in vdata.mchAppList" :key="item.appId">{{ item.appName }} [{{ item.appId }}]</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item>
              <div class="jeepay-m-pz-box" style="margin-top: 20px;">
                <a-popover placement="top">
                  <template #title><span>一键配置到应用</span></template>
                  <template #content>
                    <p>顺序：支付参数 --> 支付费率 --> 通道配置 </p>
                    <p>提示： 若有异常则结束配置</p>
                  </template>
                  <a-button data-type="text" type="primary" :disabled="!vdata.configAppId" @click="autoConfigMchAppFunc">
                    <save-outlined />一键配置到应用
                  </a-button>
                </a-popover>
              </div>
            </a-form-item>
          </a-col>
        </slot>

        <!-- 微信配置选项 显示卡片   只有运营平台可见 -->
        <slot v-if="isShowWxConfigAndAdConfigPage()" name="wxConfigPage">
          <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 :span="isMobile ? 24 : 12">
            <a-form-item class="jeepay-valid" label="微信支付目录" style="margin: 0;">
              <a-input v-model:value="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="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="vdata.configWxBindLiteAppId" 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.configWxBindLiteAppId)"
              >
                <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="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 v-if="isShowConfig2AppPage()" 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>
        </slot>

        <a-divider />
        
        <!-- 高级配置 显示卡片 : 只有运营平台可见 -->
        <slot v-if="isShowWxConfigAndAdConfigPage()" name="advancedConfigPage">
          <a-col :span="24">
            <a-collapse v-model:activeKey="vdata.activeKey">
              <a-collapse-panel key="k1" header="高级设置">
                <a-form-item label="商户简称更改（支付公司侧）">
                  <div class="jeepay-m-pz-box">
                    <a-input v-model:value="vdata.mchShortName" class="form-item-content" />
                    <a-button
                      class="jeepay-m-btn"
                      data-type="text"
                      size="small"
                      style="margin-left: 20px;"
                      type="primary"
                      @click="configInterfaceFunc('MCH_SHORT_NAME', vdata.mchShortName)"
                    >
                      <save-outlined />更改
                    </a-button>
                  </div>
                  <p class="jeepay-tip-text">每月只能修改一次（以支付公司接口为准）</p>
                </a-form-item>


                <a-form-item class="jeepay-valid" label="设置商户公钥(填入[ ISV ] 表示设置服务商公钥)">
                  <a-textarea v-model:value="vdata.mchAppPublicKey" class="form-item-content" />
                  <a-button
                    class="jeepay-m-btn"
                    data-type="text"
                    size="small"
                    style="margin-left: 20px;"
                    type="primary"
                    @click="configInterfaceFunc('MCH_APP_PUBLIC_KEY', vdata.mchAppPublicKey)"
                  >
                    <save-outlined />更新
                  </a-button>
                </a-form-item>
              

                <a-form-item label="费率调整">
                  <a-button
                    v-if="!vdata.showRateData"
                    class="jeepay-m-btn"
                    data-type="text"
                    size="small"
                    style="margin-left: 20px;"
                    type="primary"
                    @click="vdata.showRateData = true"
                  >
                    <down-outlined />申请费率修改
                  </a-button>

                  <template v-if="vdata.showRateData">
                    <div>
                      获取商户应用 [{{ vdata.configAppId }}] 费率：  
                      <JeepayPaywayRatePanel
                        v-if="vdata.configAppId"
                        ref="jeepayPaywayRatePanel"
                        :infoId="vdata.configAppId"
                        selectIfCode="shengpay"
                        :configMode="vdata.rateConfigMode"
                        :showSaveBtn="false"
                      />
                    </div>

                    <div style="display: flex;justify-content: center;">
                      <a-button class="jeepay-m-btn" data-type="block" type="primary" @click="rateUpdateOnSubmit"><send-outlined />发起费率修改</a-button>
                    </div>
                  </template>
                </a-form-item>
              </a-collapse-panel>
            </a-collapse>
          </a-col>

          <a-divider v-if="vdata.detailData.ifCode == 'hmpay'" orientation="left"><a-tag color="green">河马付门店配置项</a-tag></a-divider>
          <a-col v-if="vdata.detailData.ifCode == 'hmpay'" span="12">
            <a-form-item label="河马付商户号">
              <a-input v-model:value="vdata.detailData.channelApplyNo" disabled="disabled" class="form-item-content" />
            </a-form-item>
          </a-col>
         
          <a-col v-if="vdata.detailData.ifCode == 'hmpay'" span="24">
            <a-form-item label="门店参数">
              <a-card style="width: 100%" title="">
                <template #extra>
                  <a-button style="background: dodgerblue; color: white" @click="addRow()">
                    <a-popover placement="top">
                      <template #content>
                        <p>门店号：本系统该商户下的门店ID。</p>
                      </template>
                      <template #title>
                        <span>参数说明</span>
                      </template>
                      <question-circle-outlined />
                    </a-popover>
                    添加门店
                  </a-button>
                </template>
                <a-table :columns="accTableColumns" :data-source="vdata.tableData.filter((item: any) => item.state)" :pagination="false" rowKey="rowKey">
                  <template #bodyCell="{column, record}">
                    <template v-if="column.key == 'storeId'">
                      <a-input v-model:value="record.storeId" />
                    </template>

                    <template v-if="column.key == 'storeNo'">
                      <a-input v-model:value="record.store_no" />
                    </template>

                    <template v-if="column.key == 'state'">
                      <a-select v-model:value="record.state" placeholder="状态">
                        <a-select-option :value="0" disabled="true" hidden="true">
                          尚未发起入驻
                        </a-select-option>
                        <a-select-option :value="3" disabled="true" hidden="true">
                          审核未通过
                        </a-select-option>
                        <a-select-option :value="2">
                          启用
                        </a-select-option>
                        <a-select-option :value="1">
                          关闭
                        </a-select-option>
                      </a-select>
                    </template>

                    <template v-if="column.key == 'op'"><a-button type="link" @click="delRow(record)">删除</a-button></template>
                  </template>
                </a-table>
              </a-card>
            </a-form-item>
          </a-col>
       
          <a-col v-if="vdata.detailData.ifCode == 'hmpay'" span="24">
            <div style="margin-left: 20px;">
              <a-popover placement="top">
                <template #title><span>一键配置</span></template>
                <template #content>
                  <p>一键配置参数：将当前配置参数全部配置到子账户。 </p>
                  <p>提示：若有异常则结束配置</p>
                </template>
                <a-button style="margin-left: 20px;" type="primary" @click="configInterfaceFunc('MCH_STORE_ADD', vdata.detailData)"><alert-outlined />一键配置</a-button>
              </a-popover>
            </div>
          </a-col>
        </slot>
      </a-row>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { API_URL_MCH_APP, req, $applymentAppConfig, $queryInterfaceConfig, $configInterfaceConfig, $saveRateConfig, $getMchPayPassageExist, $autoConfigMchPayInfo } from '@/api/manage'
import {ref, reactive, inject, getCurrentInstance} from 'vue'
import { genRowKey } from '@/utils/util'
const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties

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

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

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

// 接收父组件的参数注入： 选择的商户应用
let appConfigModeByMchAppId : any = inject('appConfigModeByMchAppId')

// 接收父组件的参数注入： 选择的渠道
let appConfigModeBySelectedIfCode : any = inject('appConfigModeBySelectedIfCode')


console.log('configMode:', configMode, 'applyRecord:', applyRecord, 'appConfigModeByMchAppId:', appConfigModeByMchAppId)

const jeepayPaywayRatePanel = ref()

const vdata : any = reactive({
  detailData: null, // 数据对象
  recordId: null, // 更新对象ID
  mchAppList: [], // 商户app列表
  configAppId: '',
  mchNo: '',
  tableData: [],
  
  configWxPayBaseUrl: '', // 微信支付目录
  configWxBindAppId: '', // 关联应用
  configWxBindLiteAppId: '', // 关联小程序
  configWxSubscribeAppId: '', // 关注公众号ID

  activeKey: '' , //手风琴展开key 
  mchShortName: '', //商户简称
  mchAppPublicKey: 'ISV', //商户应用key

  showRateData : false, // 是否显示费率申请的修改， 默认为：false 

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

})
const accTableColumns = [
  { key: 'storeId', title: '门店号' },
  { key: 'storeNo', title: '河马付门店号' },
  { key: 'state', title: '状态' },
  { key: 'op', title: '操作' }
]

// 对外暴露的 页面渲染函数  也用作初始化
function pageRender (applyId){

  // 原逻辑的复用 
  vdata.recordId = applyId
  vdata.detailData = applyRecord || {}

   //重置配置
  vdata.configAppId = ''
  vdata.mchAppList = []
  vdata.configWxPayBaseUrl = ''
  vdata.configWxBindAppId = ''
  vdata.configWxBindLiteAppId = ''
  vdata.configWxSubscribeAppId = ''
  vdata.mchShortName = ''
  vdata.mchAppPublicKey = 'ISV'
  vdata.showRateData = false
  vdata.mchNo = vdata.detailData.mchNo

  vdata.activeKey = '' // 折叠

  if(vdata.detailData.storeSuccResParameter) {
      vdata.tableData = JSON.parse(vdata.detailData.storeSuccResParameter)
  }


  // 显示配置到应用才查询应用
  if(isShowConfig2AppPage()){
    req.list(API_URL_MCH_APP, { pageSize: -1, mchNo: vdata.detailData.mchNo }).then(res2 => {
      vdata.mchAppList = res2.records
      if(vdata.mchAppList.length > 0){
        vdata.configAppId = vdata.mchAppList[0].appId
      }
    })
  }else{
    // 默认的应用ID为上级带过来的。 
    vdata.configAppId = appConfigModeByMchAppId
    vdata.recordId = appConfigModeByMchAppId
  }


  // 查询配置信息 
  commonQueryInterfaceConfigFunc().then((res2) => {
    vdata.configWxPayBaseUrl = res2.paySiteUrl
    vdata.configWxBindAppId = res2.wxAppId
    vdata.configWxBindLiteAppId = res2.wxLiteAppId
    vdata.configWxSubscribeAppId = res2.wxAppId
  })

}

// 一键配置，按（支付参数 > 支付费率 > 通道配置）的顺序进行自动配置
function autoConfigMchAppFunc() {

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

  $getMchPayPassageExist(vdata.recordId, vdata.configAppId).then(res => {
    // 选择的应用在当前进件 支付方式已配置其他渠道
    if (res && res.existMchPayPassage) {
      $infoBox.confirmPrimaryPromise('提示', '当前应用部分支付方式已配置使用其他支付渠道，是否进行覆盖？', { okText: '覆盖', cancelText: '不覆盖', maskClosable: true }).then(() => {
        // 参数、费率配置、通道配置
        configMchParamsAndRateAndPayPassage(1)

      }).catch((e) => {
        // 点击不覆盖按钮  参数、费率配置
        if (!e.triggerCancel) {
          configMchParamsAndRateAndPayPassage(0)
        }
      })

    }else {
      // 进件支付方式未配置其他渠道，自动开启渠道
      configMchParamsAndRateAndPayPassage(1)
    }
  })
}

// 一键配置到应用
async function configMchParamsAndRateAndPayPassage(isOverWrite) {
  $autoConfigMchPayInfo(vdata.recordId, vdata.configAppId, { isOverWrite }).then(res => {
    $infoBox.message.success('一键配置成功')
  })
}

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

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

  return $applymentAppConfig(vdata.recordId, vdata.configAppId).then((res) => {
    $infoBox.message.success('商户应用支付参数配置完成 ')
    return Promise.resolve()
  })

}


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

  vdata.detailData.storeSuccResParameter = JSON.stringify(vdata.tableData)

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

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

  return commonConfigInterfaceConfigFunc(vdata.recordId, vdata.configAppId, configType, configVal).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(){

vdata.detailData.storeSuccResParameter = JSON.stringify(vdata.tableData)

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

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

}

// 添加一行信息
function addRow () {
  vdata.tableData.push(Object.assign({}, {}, { rowKey: genRowKey(), storeId: '', storeNo: '', state: 2 }))
}

// 删除某一行
function delRow (item: any) {
  const index = vdata.tableData.indexOf(item)
  if (index > -1) {
    vdata.tableData.splice(index, 1)
  }
}

// 配置费率到应用
function configMchRateAppIdFunc(paywayFeeList = null){

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


  // 自定义费率 or 进件费率 
  let reqPaywayFeeList = paywayFeeList || JSON.parse(vdata.detailData.applyDetailInfo).paywayFeeList

  let reqObject = {infoId: vdata.configAppId, ifCode: vdata.detailData.ifCode, configMode: vdata.rateConfigMode, MCHRATE: reqPaywayFeeList}

  // app配置模式的时候， ifCode需要在 注入参数取值。 
  if(!isShowConfig2AppPage()){
    reqObject.ifCode = appConfigModeBySelectedIfCode
  }

  return $saveRateConfig(reqObject).then((res) => {
    $infoBox.message.success('费率保存成功')
  })

}

// 申请调整费率
function rateUpdateOnSubmit(){


  if(jeepayPaywayRatePanel.value){

    let reqPaywayFeeList = jeepayPaywayRatePanel.value.getReqMchRatePaywayFeeList()

    return configInterfaceFunc('MCH_RATE_UPDATE', JSON.stringify(reqPaywayFeeList)).then((res) => {
      $infoBox.confirmDanger('申请费率调整成功！', '是否更新商户应用费率？', () => {
        return configMchRateAppIdFunc(reqPaywayFeeList)
      })
    })

  }else{ // 没有获取到组件。 

    $infoBox.message.success('获取费率失败，请刷新页面重试')

  }
}

// 获取当前配置的APPID
function getSelectedConfigAppId(){
  return vdata.configAppId
}

// 获取当前商户号
function getSelectedMchNo(){
  return vdata.mchNo
}

// 是否 显示 配置到应用的选项。 
function isShowConfig2AppPage(){

  // 运营平台 --》 商户应用配置 此时：  无需显示配置到应用即可。 
  if((configMode == 'mgrMch' || configMode == 'agentMch') && appConfigModeByMchAppId){
    return false
  }

  return true

}

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


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

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

  let convertMchAppIfCode = null

  // 应用配置页面 需要做转换
  if(!isShowConfig2AppPage() || configMode == 'agentMch'){

    reqApplyId = appConfigModeByMchAppId
    applyIdConvertMchAppId = 1
    convertMchAppIfCode = appConfigModeBySelectedIfCode
  }

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

}

// 给diy页面的全局公用函数 （ 请求在一个地方处理 ）
function commonConfigInterfaceConfigFunc(applyId, mchAppId, configType, configVal){
  return $configInterfaceConfig(applyId, mchAppId, configType, configVal, appConfigModeBySelectedIfCode)
}


defineExpose({ pageRender, configInterfaceFunc, configMchAppIdFunc, configMchRateAppIdFunc, getSelectedConfigAppId, getSelectedMchNo, commonQueryInterfaceConfigFunc, commonConfigInterfaceConfigFunc, autoConfigMchAppFunc })
</script>
<style scoped>

.form-item-content{
  width: 70%
}

</style>

