<template>
  <a-form ref="formRef" :model="vdata.currentConfig" layout="vertical" :rules="vdata.formRules">
    <a-row :gutter="16">
      <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-divider dashed />
      <a-col span="24">
        <a-form-item label="微信支付商户号" name="mchId">
          <a-input v-model:value.trim="vdata.currentConfig['mchId']" placeholder="请输入" @change="changeFun('mchId')" />
        </a-form-item>
      </a-col>
      <a-col span="12">
        <a-form-item label="微信支付API版本" name="apiVersion">
          <a-radio-group v-model:value="vdata.currentConfig['apiVersion']" defaultValue="V2">
            <a-radio value="V2">V2</a-radio>
            <a-radio value="V3">V3</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
      <a-col span="24">
        <a-form-item label="APIv2密钥" name="key">
          <a-input v-model:value.trim="vdata.currentConfig.key" :placeholder=" vdata.encryptionField.key || '请输入APIv2密钥' " @change="changeFun('key')" />
        </a-form-item>
      </a-col>
      <a-col span="24">
        <a-form-item label="APIv3密钥" name="apiV3Key">
          <a-input v-model:value.trim="vdata.currentConfig.apiV3Key" :placeholder=" vdata.encryptionField.apiV3Key || '请输入APIv3密钥' " @change="changeFun('apiV3Key')" />
        </a-form-item>
      </a-col>
      <a-col span="24">
        <a-form-item label="序列号" name="serialNo">
          <a-input v-model:value.trim="vdata.currentConfig.serialNo" :placeholder=" vdata.encryptionField.serialNo || '请输入序列号' " @change="changeFun('serialNo')" />
        </a-form-item>
      </a-col>
      <a-col span="24">
        <a-form-item label="API证书(apiclient_cert.p12)" name="cert">
          <JeepayUpload v-model:src="vdata.currentConfig.cert" bizType="cert" fileType="file" accept=".p12" />
        </a-form-item>
      </a-col>
      <a-col span="24">
        <a-form-item label="证书文件(apiclient_cert.pem)" name="apiClientCert">
          <JeepayUpload v-model:src="vdata.currentConfig.apiClientCert" bizType="cert" fileType="file" accept=".pem" />
        </a-form-item>
      </a-col>
      <a-col span="24">
        <a-form-item label="私钥文件(apiclient_key.pem)" name="apiClientKey">
          <JeepayUpload v-model:src="vdata.currentConfig.apiClientKey" bizType="cert" fileType="file" accept=".pem" />
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
</template>
<script setup lang="ts">
import { ref, reactive, defineExpose } from 'vue'


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

const vdata = reactive({

  // 定义加密的字段
  encryptionField : {
    mchKey: '',
    key: '',
    apiV3Key: '',
    serialNo: '',
  },

  currentConfig: {} as any, // 当前配置项

  //表单规则
  formRules: {
    mchId: [{ required: true, message: '请输入微信支付商户号', trigger: 'blur' }],
    appId: [{ required: true, message: '请输入应用AppID', trigger: 'blur' }],
    key: [{ trigger: 'blur',
      validator: (rule, value, callback) => {
        if (vdata.currentConfig['apiVersion'] === 'V2' && !vdata.encryptionField[rule.field] && !value) {
          return Promise.reject(new Error('请输入API密钥'))
        }
        return Promise.resolve()
      } }],
    apiV3Key: [{ trigger: 'blur',
      validator: (rule, value, callback) => {
        if (vdata.currentConfig['apiVersion'] === 'V3' && !vdata.encryptionField[rule.field] && !value) {
          return Promise.reject(new Error('请输入API V3秘钥'))
        }
        return Promise.resolve()
      } }],
    serialNo: [{ trigger: 'blur',
      validator: (rule, value, callback) => {
        if (vdata.currentConfig['apiVersion'] === 'V3' && !vdata.encryptionField[rule.field] && !value) {
          return Promise.reject(new Error('请输入序列号'))
        }
        return Promise.resolve()
      } }],
    apiClientCert: [{ trigger: 'blur',
      validator: (rule, value, callback) => {
        if (vdata.currentConfig['apiVersion'] === 'V3' && !vdata.currentConfig['apiClientCert']) {
          return Promise.reject(new Error('请上传证书文件'))
        }
        return Promise.resolve()
      } }],
    apiClientKey: [{ trigger: 'blur',
      validator: (rule, value, callback) => {
        if (vdata.currentConfig['apiVersion'] === 'V3' && !vdata.currentConfig['apiClientKey']) {
          return Promise.reject(new Error('请上传私钥文件'))
        }
        return Promise.resolve()
      } }]
  }
})


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

  // 赋值
  vdata.currentConfig = currentConfig

  // 处理加密数据字段
  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()
  }

}

// 对外提供的获取配置参数函数 （返回JSON类型）
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]
    }
  })
  return result
}

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

defineExpose({ getConfigParams, pageRender })

</script>
