<!-- 复制自： 运营平台
   差异： 删除商户号mchNo 的input即可。 

 -->
<template>
  <a-drawer
    :visible="vdata.visible"
    :title=" vdata.isAdd ? '新增应用' : '修改应用'"
    width="40%"
    :maskClosable="false"
    @close="onClose"
  >
    <a-form ref="infoFormModel" :model="vdata.saveObject" layout="vertical" :rules="vdata.rules">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="应用名称" name="appName">
            <a-input v-model:value="vdata.saveObject['appName']" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="应用状态" name="state">
            <a-radio-group v-model:value="vdata.saveObject['state']">
              <a-radio :value="1">启用</a-radio>
              <a-radio :value="0">停用</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col v-if="!vdata.isAdd" :span="12">
          <a-form-item label="应用ID" name="appId">
            <a-input v-model:value="vdata.saveObject['appId']" placeholder="请输入" :disabled="!vdata.isAdd" />
          </a-form-item>
        </a-col>
<!--        <a-col :span="12"  v-if="!vdata.isAdd && vdata.saveObject.range == 0">-->
<!--          <a-form-item label="是否设置为默认应用" name="defaultFlag">-->
<!--            <a-radio-group v-model:value="vdata.saveObject['defaultFlag']">-->
<!--              <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="备注" name="remark" class="m-b-50 ">
            <a-input v-model:value="vdata.saveObject['remark']" placeholder="请输入" />
          </a-form-item>
        </a-col>

        <a-col v-if="vdata.isAdd" :span="24">
          <a-divider orientation="left" style="color: #1A66FF;">签名配置</a-divider>

          <a-form-item name="appSignType">
            <template #label>
              <span>支持的签名方式</span> &nbsp;
              <a-popover placement="top">
                <template #title><span>签名方式</span></template>
                <template #content>
                  <p>若需要使用系统测试或者{{ $SYS_NAME_MAP.MCH_APP }}APP则必须支持MD5， 若仅通过API调用则根据需求进行选择。 </p>
                </template>
                <question-circle-outlined />
              </a-popover>
            </template>

            <a-checkbox-group v-model:value="vdata.saveObject.appSignTypeObject">
              <a-checkbox value="MD5">MD5</a-checkbox>
              <a-checkbox value="RSA2">RSA2</a-checkbox>
            </a-checkbox-group>
          </a-form-item>

          <a-form-item v-show="vdata.saveObject.appSignTypeObject && vdata.saveObject.appSignTypeObject.indexOf('MD5') >= 0" label="设置MD5秘钥" name="appSecret">
            <a-textarea v-model:value="vdata.saveObject['appSecret']" :placeholder="vdata.saveObject['appSecret_ph']" type="textarea" />
            <a-button type="primary" style="margin-top: 5px;" ghost @click="randomKey(false, 128, 0)"><file-sync-outlined />随机生成私钥</a-button>
          </a-form-item>

          <a-form-item v-show="vdata.saveObject.appSignTypeObject && vdata.saveObject.appSignTypeObject.indexOf('RSA2') >= 0" label="设置RSA2应用公钥" name="appRsa2PublicKey">
            <a-textarea v-model:value="vdata.saveObject['appRsa2PublicKey']" type="textarea" />
          </a-form-item>

          <a-form-item v-show="vdata.saveObject.appSignTypeObject && vdata.saveObject.appSignTypeObject.indexOf('RSA2') >= 0" label="支付网关系统公钥（回调验签使用）">
            <a-textarea :rows="6" :value="vdata.sysRSA2PublicKey" :disabled="true" type="textarea" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" @click="onClose"><close-outlined />取消</a-button>
      <a-button type="primary" :loading="vdata.btnLoading" @click="onSubmit"><check-outlined />保存</a-button>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import { API_URL_MCH_APP, req, $getSysRSA2PublicKey } from '@/api/manage'
import {ref, reactive, getCurrentInstance} from 'vue'

const { $SYS_NAME_MAP } = getCurrentInstance()!.appContext.config.globalProperties
const props = defineProps({
  callbackFunc: { type: Function, default: () => () => ({}) }
})
  
const vdata : any =  reactive({
  isAdd: true, // 新增 or 修改
  visible: false, // 抽屉开关
  appId: '', // 应用AppId
  saveObject: {}, // 数据对象
  btnLoading:false,
  sysRSA2PublicKey: '', 
  rules: {
    mchNo: [{ required: true, message: '请输入商户号', trigger: 'blur' }],
    appName: [{ required: true, message: '请输入应用名称', trigger: 'blur' }],
    appSecret: [{
      validator:  (rule, value) => {

          // 新增 & 选择了MD5 :  必须输入MD5私钥
          if(vdata.isAdd && vdata.saveObject.appSignTypeObject.indexOf('MD5') >= 0 && !value){
            return Promise.reject('请输入MD5秘钥')
          }
          return Promise.resolve()
      }
    }],
    appRsa2PublicKey: [{
      validator:  (rule, value) => {

          // 新增 & 选择了MD5 :  必须输入MD5私钥
          if(vdata.saveObject.appSignTypeObject.indexOf('RSA2') >= 0 && !value){
            return Promise.reject('请输入RSA2应用公钥')
          }
          return Promise.resolve()

      } 
                  
    }]
  }
})

// 表单组件
const infoFormModel = ref()

// 抽屉显示
const show = (mchNo, appId) => {
  vdata.isAdd = !appId
  // 数据清空
  vdata.saveObject = {
    'state': 1,
    'appSecret': '',
    'mchNo': mchNo,
    'defaultFlag': 1,
    'appSecret_ph': '请输入',
    appSignTypeObject: ['MD5']
  }
  
  if (infoFormModel.value !== undefined) {
    infoFormModel.value.resetFields()
  }

  if (!vdata.isAdd) { // 修改信息 延迟展示弹层
    vdata.appId = appId
    // 拉取详情
    req.getById(API_URL_MCH_APP, appId).then(res => {
      vdata.saveObject = res
      vdata.saveObject['appSecret_ph'] = res.appSecret
      vdata.saveObject['range'] = res.range
      vdata.saveObject['appSecret'] = ''

      vdata.saveObject.appSignTypeObject = []
      if(res.appSignType){
        vdata.saveObject.appSignTypeObject = JSON.parse(res.appSignType)
      }

    })

    vdata.visible = true
  } else {

    vdata.visible = true // 展示弹层信息
  }

  // 查询系统公钥
  $getSysRSA2PublicKey().then((res) => {
    vdata.sysRSA2PublicKey = res
  })

}
// 表单提交
const onSubmit = () => {

  // 处理签名方式
  vdata.saveObject.appSignType = JSON.stringify(vdata.saveObject.appSignTypeObject)
  
  infoFormModel.value.validate().then(() => {

    vdata.btnLoading = true
    let reqObject = Object.assign({}, vdata.saveObject) // 请求数据
  
    delete reqObject['appSecret_ph']
    if (!vdata.isAdd && reqObject['appSecret'] === '') {
        delete reqObject['appSecret']
    }
    console.log(reqObject,'reqObjectreqObjectreqObject')
    // return false;

    req.addOrUpdate(vdata.isAdd ? null : vdata.appId, API_URL_MCH_APP, reqObject).then(res => {
        vdata.visible = false
        props.callbackFunc() // 刷新列表
    }).finally(() => {
        vdata.btnLoading = false
    })
  })
}


function randomKey(randomFlag, min, max) { // 生成随机128位私钥
  let str = ''
  let range = min
  const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  // 随机产生
  if (randomFlag) {
    range = Math.round(Math.random() * (max - min)) + min
  }
  for (var i = 0; i < range; i++) {
    var pos = Math.round(Math.random() * (arr.length - 1))
    str += arr[ pos ]
  }
  vdata.saveObject['appSecret'] = str
}

const onClose = () => {
  vdata.visible = false
}

defineExpose({ show })
</script>

