<template>
  <div class="p-2">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>支付配置</span>
          <el-button type="primary" @click="handleSave" :loading="saving">保存配置</el-button>
        </div>
      </template>

      <el-form :model="form" label-width="140px" v-loading="loading">
        <!-- 微信支付商户配置 -->
        <el-divider content-position="left">微信小程序支付</el-divider>
        
        <el-form-item label="商户号ID">
          <el-input v-model="form.mchId" placeholder="请输入微信支付商户号(MCHID)" style="width: 400px" />
        </el-form-item>
        
        <el-form-item label="商户号API密钥">
          <el-input v-model="form.apiV3Key" placeholder="请输入微信支付商户API密钥(APIv3密钥)" 
                    type="password" show-password style="width: 400px" />
        </el-form-item>
        
        <el-form-item label="商户API证书序列号">
          <el-input v-model="form.mchSerialNo" placeholder="请输入商户API证书序列号" style="width: 400px" />
        </el-form-item>
        
        <el-form-item label="商户私钥">
          <div>
            <el-upload
              action="#"
              :auto-upload="false"
              :show-file-list="false"
              accept=".pem"
              :on-change="handlePrivateKeyChange"
            >
              <el-button type="primary">上传私钥文件</el-button>
            </el-upload>
            <div class="tip-text">微信支付证书私钥(apiclient_key.pem)，前往微信商家平台下载</div>
            <div v-if="form.privateKeyUploaded" class="success-text">✓ 私钥已上传</div>
          </div>
        </el-form-item>
        
        <el-form-item label="API回调地址">
          <el-input v-model="form.notifyUrl" placeholder="请输入支付回调地址，如：https://域名/v1/order/notify" style="width: 400px" />
        </el-form-item>

        <!-- 订阅价格配置 -->
        <el-divider content-position="left">超短池配置</el-divider>
        <el-form-item label="订阅价格（元）">
          <el-input-number v-model="form.shortPrice" :min="0" :precision="2" :step="1" />
          <span class="ml-2 tip-text">有效期：当日24:00</span>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const loading = ref(false)
const saving = ref(false)
const privateKeyFile = ref<File | null>(null)

const form = ref({
  mchId: '',
  apiV3Key: '',
  mchSerialNo: '',
  notifyUrl: '',
  shortPrice: 18,
  privateKeyUploaded: false
})

// 处理私钥文件选择
const handlePrivateKeyChange = (file: any) => {
  privateKeyFile.value = file.raw
  ElMessage.success('私钥文件已选择，保存时将一并上传')
}

// 获取配置
const getConfig = async () => {
  loading.value = true
  try {
    const res = await request.get('/miniapp/paymentConfig/list')
    if (res.code === 200 && res.data) {
      form.value.mchId = res.data.mchId || ''
      form.value.apiV3Key = res.data.apiV3Key || ''
      form.value.mchSerialNo = res.data.mchSerialNo || ''
      form.value.notifyUrl = res.data.notifyUrl || ''
      form.value.shortPrice = res.data.shortPrice || 18
      form.value.privateKeyUploaded = res.data.privateKeyUploaded || false
    }
  } catch (e) {
    console.error('获取配置失败', e)
  } finally {
    loading.value = false
  }
}

// 保存配置
const handleSave = async () => {
  saving.value = true
  try {
    // 如果有私钥文件，先上传
    if (privateKeyFile.value) {
      const formData = new FormData()
      formData.append('file', privateKeyFile.value)
      const uploadRes = await request.post('/miniapp/paymentConfig/uploadPrivateKey', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      if (uploadRes.code !== 200) {
        ElMessage.error('私钥上传失败：' + uploadRes.msg)
        saving.value = false
        return
      }
      form.value.privateKeyUploaded = true
      privateKeyFile.value = null
    }
    
    // 保存其他配置
    const res = await request.put('/miniapp/paymentConfig', {
      mchId: form.value.mchId,
      apiV3Key: form.value.apiV3Key,
      mchSerialNo: form.value.mchSerialNo,
      notifyUrl: form.value.notifyUrl,
      shortPrice: form.value.shortPrice
    })
    if (res.code === 200) {
      ElMessage.success('保存成功')
    } else {
      ElMessage.error(res.msg || '保存失败')
    }
  } catch (e) {
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  getConfig()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.tip-text {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
}
.success-text {
  color: #67c23a;
  font-size: 12px;
  margin-top: 4px;
}
</style>
