<template>
  <a-form ref="formRef" :model="vdata.currentConfig" layout="vertical" :rules="ifParamsRules">
    <a-row :gutter="16">
      <a-col span="12">
        <a-form-item label="河马付商户号" name="subAppId">
          <a-input v-model:value.trim="vdata.currentConfig['subAppId']" placeholder="请输入河马付商户号subAppId" @change="changeFun('subAppId')" />
        </a-form-item>
      </a-col>
      <a-col span="12">
        <a-form-item label="微信appId" name="wxLiteAppId">
          <a-input v-model:value.trim="vdata.currentConfig['wxLiteAppId']" placeholder="请输入微信appId" @change="changeFun('wxLiteAppId')" />
        </a-form-item>
      </a-col>
      <a-col span="24">
        <a-form-item label="门店参数">
          <a-card style="width: 100%" title="">
            <template #extra>
              <a-button style="background: dodgerblue; color: white" @click="addRow()">
                <a-popover placement="top">
                  <template #content>
                    <p>门店号：本系统该商户下的门店ID。</p>
                  </template>
                  <template #title>
                    <span>参数说明</span>
                  </template>
                  <question-circle-outlined />
                </a-popover>
                添加门店
              </a-button>
            </template>
            <a-table :columns="accTableColumns" :data-source="vdata.tableData.filter((item: any) => item.state)" :pagination="false" rowKey="rowKey">
              <template #bodyCell="{column, record}">
                <template v-if="column.key == 'storeId'">
                  <a-input v-model:value.trim="record.storeId" />
                </template>

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

                <template v-if="column.key == 'state'">
                  <a-select v-model:value="record.state" placeholder="状态">
                    <a-select-option :value="0" disabled="true" hidden="true">
                      尚未发起入驻
                    </a-select-option>
                    <a-select-option :value="3" disabled="true" hidden="true">
                      审核未通过
                    </a-select-option>
                    <a-select-option :value="2">
                      启用
                    </a-select-option>
                    <a-select-option :value="1">
                      关闭
                    </a-select-option>
                  </a-select>
                </template>

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

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

})

const accTableColumns = [
  { key: 'storeId', title: '门店号' },
  { key: 'storeNo', title: '河马付门店号' },
  { key: 'state', title: '状态' },
  { key: 'op', title: '操作' }
]
//表单规则
const ifParamsRules = reactive({
  subAppId: [{ trigger: 'blur',
    validator: (rule, value) => {
      if (!value) {
        return Promise.reject(new Error('请输入河马付商户号subAppId'))
      }
      return Promise.resolve()
  } }]
})

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

function getConfigParams(){
  vdata.currentConfig.mchStoreConfig = JSON.stringify(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]
    }
  })

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

  return result
}

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

  if (vdata.currentConfig.mchStoreConfig) {
    vdata.tableData = JSON.parse(vdata.currentConfig.mchStoreConfig)
  }
  
  // 处理加密数据字段
  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(), storeId: '', store_no: '', state: 2 }))
}

// 删除某一行
function delRow (item) {
  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>
