<template>
  <a-form v-if="vdata.currentConfig" ref="formRef" :model="vdata.currentConfig" layout="horizontal" :rules="vdata.formRules">
    <a-divider orientation="left">
      <a-tag color="#FF4B33">设备参数配置</a-tag>
    </a-divider>
    <a-row v-if="vdata.isAdd" justify="space-between" type="flex">
      <a-col :span="24">
        <a-form-item label="设备参数" name="deviceNo">
          <a-textarea v-model:value="vdata.currentConfig.deviceNo" placeholder="请输入" />
          <span class="jeepay-tip-text">请按照“deviceNo_deviceKey”格式填入，多个设备请以英文逗号隔开</span>
        </a-form-item>
      </a-col>
    </a-row>
    <a-row v-else justify="space-between" type="flex">
      <a-col :span="11">
        <a-form-item label="设备号" name="deviceNo_c">
          <a-input v-model:value="vdata.currentConfig.deviceNo_c" placeholder="请输入设备号" />
        </a-form-item>
      </a-col>
      <a-col :span="11">
        <a-form-item label="终端秘钥" name="deviceKey_c">
          <a-input v-model:value="vdata.currentConfig.deviceKey_c" placeholder="请输入终端秘钥" />
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
</template>

<script lang="ts" setup>
import {reactive, ref, defineExpose} from 'vue'
 
  // 当前的form
  const formRef = ref()

  const  vdata = reactive({
    // 配置对象
    currentConfig: {} as any,
    isAdd: true, // 新增 or 修改页面标志
    // 表单规则
    formRules: {
      deviceNo: [{ required: true, message: '请输入设备参数', trigger: 'blur' }],
      deviceKey: [{ required: true, message: '请输入终端秘钥', trigger: 'blur' }],
      deviceNo_c: [{ required: true, message: '请输入设备参数', trigger: 'blur' }],
      deviceKey_c: [{ required: true, message: '请输入终端秘钥', trigger: 'blur' }]
    }
  })

  // 对外提供的页面的渲染函数 （ currentConfig = 当前配置项 ）
function pageRender(currentConfig: any, deviceType: any, isAdd:boolean){
  
  vdata.isAdd = isAdd

  // 赋值
  if (currentConfig) {
    vdata.currentConfig = currentConfig
    const arr = vdata.currentConfig.deviceNo.split('_')
    if (arr.length > 1) {
      vdata.currentConfig.deviceNo_c = arr[0]
      vdata.currentConfig.deviceKey_c = arr[1]
    }else {
      vdata.currentConfig.deviceNo_c = vdata.currentConfig.deviceNo
      vdata.currentConfig.deviceKey_c = vdata.currentConfig.deviceKey

      vdata.currentConfig.deviceNo = vdata.currentConfig.deviceNo_c+'_'+vdata.currentConfig.deviceKey_c
    }

  }

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

// 对外提供的获取配置参数函数 （返回JSON类型）
function getConfigParams(){
  return formRef.value.validate().then( () => {
    console.log(vdata.currentConfig)
    
    if(vdata.isAdd) {
      return vdata.currentConfig
    }else {
      vdata.currentConfig.deviceNo = vdata.currentConfig.deviceNo_c + '_' + vdata.currentConfig.deviceKey_c
      return { deviceNo: vdata.currentConfig.deviceNo }
    }
  })
}

defineExpose({ getConfigParams, pageRender })

</script>
