<template>
  <a-form ref="formRef" :model="vdata.currentConfig" layout="vertical" :rules="ifParamsRules">
    <a-row v-if="vdata.mchType === 1" :gutter="16">
      <a-col span="24">
        <a-form-item label="环境配置" name="sandbox">
          <a-radio-group v-model:value="vdata.currentConfig.sandbox">
            <a-radio :value="1">沙箱环境</a-radio>
            <a-radio :value="0">生产环境</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
      <a-col span="12">
        <a-form-item label="应用AppId" name="appId">
          <a-input v-model:value.trim="vdata.currentConfig.appId" placeholder="请输入" @change="changeFun('appId')" />
        </a-form-item>
      </a-col>
      <a-col span="24">
        <a-form-item label="应用私钥" name="privateKey">
          <a-textarea v-model:value="vdata.currentConfig.privateKey" :placeholder="vdata.encryptionField.privateKey || '请输入应用私钥'" @change="changeFun('privateKey')" />
        </a-form-item>
      </a-col>
      <a-col span="24">
        <a-form-item label="支付宝公钥" name="alipayPublicKey">
          <a-textarea v-model:value="vdata.currentConfig.alipayPublicKey" :placeholder="vdata.encryptionField.alipayPublicKey || '请输入支付宝公钥'" @change="changeFun('alipayPublicKey')" />
        </a-form-item>
      </a-col>
      <a-col span="12">
        <a-form-item label="接口签名方式(推荐使用RSA2)" name="signType">
          <a-radio-group v-model:value="vdata.currentConfig.signType">
            <a-radio value="RSA">RSA</a-radio>
            <a-radio value="RSA2">RSA2</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
      <a-col span="24">
        <a-form-item label="公钥证书" name="useCert">
          <a-radio-group v-model:value="vdata.currentConfig.useCert">
            <a-radio :value="1">使用证书（请使用RSA2私钥）</a-radio>
            <a-radio :value="0">不使用证书</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
      <a-col span="24">
        <a-form-item label="应用公钥证书（.crt格式）" name="appPublicCert">
          <JeepayUpload v-model:src="vdata.currentConfig.appPublicCert" bizType="cert" fileType="file" accept=".crt" />
        </a-form-item>
      </a-col>
      <a-col span="24">
        <a-form-item label="支付宝公钥证书（.crt格式）" name="alipayPublicCert">
          <JeepayUpload v-model:src="vdata.currentConfig.alipayPublicCert" bizType="cert" fileType="file" accept=".crt" />
        </a-form-item>
      </a-col>
      <a-col span="24">
        <a-form-item label="支付宝根证书（.crt格式）" name="alipayRootCert">
          <JeepayUpload v-model:src="vdata.currentConfig.alipayRootCert" bizType="cert" fileType="file" accept=".crt" />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row v-else-if="vdata.mchType === 2" :gutter="16">
      <a-col span="12">
        <a-form-item label="子商户app_auth_token" name="appAuthToken">
          <a-input v-model:value.trim="vdata.currentConfig['appAuthToken']" placeholder="请输入子商户app_auth_token" style="width: 330px" />
          <a-button type="primary" style="margin-left:20px" @click="alipayAuthRef.show(injectInfoId)">扫码授权</a-button>
        </a-form-item>
      </a-col>
    </a-row>
    <AlipayAuth ref="alipayAuthRef" :callbackFunc="initPageFunc" />
  </a-form>
</template>
<script setup lang="ts">
import { upload } from '@/api/manage'
import { ref, reactive, defineExpose, inject } from 'vue'
import AlipayAuth from './AlipayAuth.vue'

const vdata = reactive ({
  mchType: 1, //商户类型
  isAdd: true,
  ifDefineArray: [], // 接口的配置定义项数组
  currentConfig: {} as any, // 当前配置项
  liteConfig: {} as any, // 小程序配置项
  activeKey: ['1'], // 折叠默认展开
  action: upload.cert, // 上传文件地址
  encryptionField : { // 定义加密的字段
    privateKey: '',
    alipayPublicKey: ''
  },

})

// 获取上级注入的infoId
const injectInfoId = inject('infoId')

// 获取上级注入的func
const initPageFunc : any = inject('initPageFunc')

const alipayAuthRef = ref()

//表单规则
const ifParamsRules = reactive({
        appId: [{ trigger: 'blur',
          validator: (rule, value) => {
            if (vdata.mchType === 1 && !value) {
              return Promise.reject(new Error('请输入应用AppID'))
            }
            return Promise.resolve()
         } }],
        privateKey: [{ trigger: 'blur',
          validator: (rule, value) => {
            if (vdata.mchType === 1 && !vdata.encryptionField[rule.field] && !value) {
              return Promise.reject(new Error('请输入应用私钥'))
            }
            return Promise.resolve()
        } }],
        alipayPublicKey: [{ trigger: 'blur',
          validator: (rule, value) => {
            if (vdata.mchType === 1 && !vdata.encryptionField[rule.field]&& vdata.currentConfig['useCert'] === 0 && !value) {
              return Promise.reject(new Error('请输入支付宝公钥'))
            }
            return Promise.resolve()
        } }],
        appPublicCert: [{ trigger: 'blur',
          validator: (rule, value) => {
            if (vdata.mchType === 1 && vdata.currentConfig['useCert'] === 1 && !vdata.currentConfig['appPublicCert']) {
              return Promise.reject(new Error('请上传应用公钥证书（.crt格式）'))
            }
            return Promise.resolve()
        } }],
        alipayPublicCert: [{ trigger: 'blur',
          validator: (rule, value) => {
            if (vdata.mchType === 1 && vdata.currentConfig['useCert'] === 1 && !vdata.currentConfig['alipayPublicCert']) {
              return Promise.reject(new Error('请上传支付宝公钥证书（.crt格式）'))
            }
            return Promise.resolve()
        } }],
        alipayRootCert: [{ trigger: 'blur',
          validator: (rule, value) => {
            if (vdata.mchType === 1 && vdata.currentConfig['useCert'] === 1 && !vdata.currentConfig['alipayRootCert']) {
              return Promise.reject(new Error('请上传支付宝根证书（.crt格式）'))
            }
            return Promise.resolve()
        } }],
        appAuthToken: [{ trigger: 'blur',
          validator: (rule, value) => {
            if (vdata.mchType === 2 && !value) {
              return Promise.reject(new Error('请输入子商户app_auth_token'))
            }
            return Promise.resolve()
        } }]
      })

// 当前的form
const formRef = ref()

function getConfigParams(){
  return formRef.value.validate().then( () => {
    return convertEncryData()
  })

}

// 转换加密数据
function convertEncryData(){

  // 对象克隆
  let result = Object.assign({}, vdata.currentConfig)
  Object.keys(vdata.encryptionField).forEach(key => {
    // 加密数据 && 空串
    if (!result[key]) {
      delete result[key]
    }
  })

  // 转换小程序参数
  result.liteParams = vdata.liteConfig

  return result
}

// 对外提供的页面的渲染函数 （ ifDefineArray = 接口的配置定义项数组，  currentConfig = 当前配置项,mchType=商户类型 ）
// 20230918 新增： isProcessStarField = true ( 是否处理 脱敏数据， 默认为 true  )
function pageRender(ifDefineArray, currentConfig, mchType, isProcessStarField = true){  
  // 赋值
  vdata.mchType = mchType
  vdata.currentConfig = currentConfig
  if(currentConfig.liteParams) {
    vdata.liteConfig = currentConfig.liteParams
  }

  // 处理加密数据字段
  if(isProcessStarField){
    Object.keys(vdata.encryptionField).forEach(key => {
      vdata.encryptionField[key] = vdata.currentConfig[key]
      delete vdata.currentConfig[key]
    })
  }

  // 重置form验证
  if (formRef.value !== undefined && formRef.value !== null) {
    formRef.value.resetFields()
  }

}

// 消除参数空格
function changeFun(value) {
  if(vdata.currentConfig[value]) {
    vdata.currentConfig[value] = vdata.currentConfig[value].trim()
  }
}

defineExpose({ getConfigParams, pageRender })

</script>
