<template>
  <a-collapse v-model:activeKey="vdata.activeKey" ghost accordion default-active-key="1">
    <a-collapse-panel key="1" header="服务商参数配置">
      <a-form ref="formRef" :model="vdata.currentConfig" layout="vertical" :rules="vdata.formRules">
        <a-row :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="银联服务商标识[serProvId]" name="serProvId">
              <a-input v-model:value.trim="vdata.currentConfig['serProvId']" placeholder="请输入" @change="changeFun('serProvId')" />
            </a-form-item>
          </a-col>
          <a-col span="12">
            <a-form-item label="服务商机构标识码[pnrInsIdCd]">
              <a-input v-model:value.trim="vdata.currentConfig['pnrInsIdCd']" placeholder="请输入" @change="changeFun('pnrInsIdCd')" />
            </a-form-item>
          </a-col>
          <a-col span="24">
            <a-form-item label="服务商私钥文件（.pfx格式）" name="isvPrivateCertFile">
              <JeepayUpload v-model:src="vdata.currentConfig.isvPrivateCertFile" bizType="cert" fileType="file" accept=".pfx" />
            </a-form-item>
          </a-col>
          <a-col span="12">
            <a-form-item label="服务商私钥文件密码" name="isvPrivateCertPwd">
              <a-input v-model:value.trim="vdata.currentConfig['isvPrivateCertPwd']" :placeholder="vdata.encryptionField.isvPrivateCertPwd || '请输服务商私钥文件密码'" @change="changeFun('isvPrivateCertPwd')" />
            </a-form-item>
          </a-col>
          <a-col span="24">
            <a-form-item label="云闪付开发公钥（证书管理页面可查询）" name="ysfpayPublicKey">
              <a-textarea v-model:value="vdata.currentConfig.ysfpayPublicKey" :placeholder="vdata.encryptionField.ysfpayPublicKey || '请输入云闪付开发公钥（证书管理页面可查询）'" type="textarea" @change="changeFun('ysfpayPublicKey')" />
            </a-form-item>
          </a-col>
          <a-col span="18">
            <a-card style="width: 90%" title="机构号配置">
              <template #extra>
                <a-button style="background: dodgerblue; color: white" @click="addRow()">添加机构</a-button>
              </template>
              <a-table :columns="accTableColumns" :data-source="vdata.tableData.filter((item: any) => item.acqOrg == 'acqOrgCodeConfig')" :pagination="false" rowKey="rowKey">
                <template #bodyCell="{column,record}">
                  <template v-if="column.key == 'acqOrgCodeType'">
                    <a-select v-model:value="record.acqOrgCodeType" style="width: 200px" placeholder="机构类型" default-value="RYX">
                      <a-select-option value="RYX">瑞银信</a-select-option>
                      <a-select-option value="ZF">中付</a-select-option>
                      <a-select-option value="COMMONS">其他</a-select-option>
                    </a-select>
                  </template>

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

                  <template v-if="column.key == 'op'"><a-button type="link" @click="delRow(record)">删除</a-button></template>
                </template>
              </a-table>
            </a-card>
          </a-col>
        </a-row>
      </a-form>
    </a-collapse-panel>
  </a-collapse>
</template>
<script setup lang="ts">
import { ref, reactive, defineExpose } from 'vue'
import { genRowKey } from '@/utils/util'

const accTableColumns = [
  { key: 'acqOrgCodeType', title: '机构类型' },
  { key: 'acqOrgCode', title: '机构号' },
  { key: 'op', title: '操作' }
]

const vdata = reactive ({
  ifDefineArray: [], // 接口的配置定义项数组
  currentConfig: {} as any, // 当前配置项
  liteConfig: {} as any, // 小程序配置项
  activeKey: ['1'], // 折叠默认展开
  encryptionField : { // 定义加密的字段
    ysfpayPublicKey: '',
    isvPrivateCertPwd: '',
  },
  tableData: [] as any,
  //表单规则
  formRules: {
    serProvId: [{required: true, message: '请输入银联服务商标识', trigger: 'blur'}],
    sandbox: [{required: true, type: 'number', message: '请选择环境', trigger: 'blur'}],
    isvPrivateCertPwd: [{ required: true, trigger: 'blur',
          validator: (rule, value) => {
            if (!value && !vdata.encryptionField[rule.field]) {
              return Promise.reject(new Error('请输入服务商私钥文件密码'))
            }
            return Promise.resolve()
    } }],
    isvPrivateCertFile: [{ required: true, trigger: 'blur',
          validator: (rule, value) => {
            if (!value && !vdata.encryptionField[rule.field]) {
              return Promise.reject(new Error('请上传服务商私钥文件'))
            }
            return Promise.resolve()
    } }],
    ysfpayPublicKey: [{ required: true, trigger: 'blur',
      validator: (rule, value) => {
        if (!value && !vdata.encryptionField[rule.field]) {
          return Promise.reject(new Error('请输入云闪付开发公钥'))
        }
        return Promise.resolve()
    } }]
  }
})

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

function getConfigParams(){
  vdata.currentConfig.acqOrgCodeList = vdata.tableData
  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
}

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

  // 赋值
  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()
  }

}

// 添加一行账号信息
function addRow () {
  vdata.tableData.push(Object.assign({}, {}, { rowKey: genRowKey(), acqOrg: 'acqOrgCodeConfig', acqOrgCodeType: 'RYX', acqOrgCode: '' }))
}

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

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

defineExpose({ getConfigParams, pageRender })

</script>
