<template>
  <div class="payment-config-page">
    <div class="page-toolbar">
      <div class="title-block">
        <div class="title-icon">
          <el-icon><Money /></el-icon>
        </div>
        <div>
          <h2>007pay 支付配置</h2>
          <p>管理 007pay 收银台、回调与支付通道参数</p>
        </div>
      </div>
      <div class="toolbar-actions">
        <el-button :loading="loading" @click="fetchConfig">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
        <el-button type="primary" :loading="saving" @click="submitForm">
          <el-icon><Check /></el-icon>保存配置
        </el-button>
      </div>
    </div>

    <div class="summary-grid">
      <div class="summary-item">
        <div class="summary-label">配置状态</div>
        <div class="summary-value">
          <el-tag :type="isConfigured ? 'success' : 'warning'" effect="plain">
            {{ isConfigured ? '已配置' : '待完善' }}
          </el-tag>
        </div>
      </div>
      <div class="summary-item">
        <div class="summary-label">商户 PID</div>
        <div class="summary-value mono">{{ form.pid || '-' }}</div>
      </div>
      <div class="summary-item">
        <div class="summary-label">通道类型</div>
        <div class="summary-value">
          <el-tag type="info" effect="plain">{{ getChannelText(form.channel_type) }}</el-tag>
        </div>
      </div>
    </div>

    <div class="config-panel" v-loading="loading">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="150px"
        class="config-form"
      >
        <el-form-item label="API 地址" prop="base_url">
          <el-input v-model.trim="form.base_url" placeholder="https://pay.example.com" clearable>
            <template #prefix><el-icon><Connection /></el-icon></template>
          </el-input>
        </el-form-item>

        <el-form-item label="商户 PID" prop="pid">
          <el-input v-model.trim="form.pid" placeholder="请输入商户 PID" clearable>
            <template #prefix><el-icon><Setting /></el-icon></template>
          </el-input>
        </el-form-item>

        <el-form-item label="商户密钥" prop="key">
          <el-input v-model.trim="form.key" placeholder="请输入商户密钥" show-password clearable>
            <template #prefix><el-icon><Key /></el-icon></template>
          </el-input>
        </el-form-item>

        <el-form-item label="异步回调地址" prop="notify_url">
          <el-input v-model.trim="form.notify_url" placeholder="https://api.example.com/api/v1/callback/007pay/pay" clearable>
            <template #prefix><el-icon><Connection /></el-icon></template>
          </el-input>
        </el-form-item>

        <el-form-item label="同步跳转地址" prop="return_url">
          <el-input v-model.trim="form.return_url" placeholder="https://example.com/pay/return" clearable>
            <template #prefix><el-icon><Connection /></el-icon></template>
          </el-input>
        </el-form-item>

        <el-form-item label="通道类型" prop="channel_type">
          <el-select
            v-model="form.channel_type"
            placeholder="请选择或输入通道类型"
            filterable
            allow-create
            default-first-option
            clearable
            style="width: 100%"
          >
            <el-option label="支付宝" value="alipay" />
            <el-option label="微信支付" value="wxpay" />
          </el-select>
        </el-form-item>
      </el-form>

      <div class="panel-footer">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" :loading="saving" @click="submitForm">保存配置</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Check, Connection, Key, Money, Refresh, Setting } from '@element-plus/icons-vue'
import { getPay007Config, updatePay007Config } from '@/api/admin/pay007'

const formRef = ref(null)
const loading = ref(false)
const saving = ref(false)

const emptyForm = {
  base_url: '',
  pid: '',
  key: '',
  notify_url: '',
  return_url: '',
  channel_type: ''
}

const form = reactive({ ...emptyForm })
const originalForm = ref({ ...emptyForm })

const optionalUrlValidator = (rule, value, callback) => {
  if (!value) {
    callback()
    return
  }
  try {
    const url = new URL(value)
    if (!['http:', 'https:'].includes(url.protocol)) {
      callback(new Error('请输入 http 或 https 地址'))
      return
    }
    callback()
  } catch {
    callback(new Error('请输入有效地址'))
  }
}

const rules = {
  base_url: [{ validator: optionalUrlValidator, trigger: 'blur' }],
  notify_url: [{ validator: optionalUrlValidator, trigger: 'blur' }],
  return_url: [{ validator: optionalUrlValidator, trigger: 'blur' }]
}

const isConfigured = computed(() => {
  return Boolean(form.base_url && form.pid && form.key && form.notify_url)
})

const getChannelText = (channel) => {
  const map = {
    alipay: '支付宝',
    wxpay: '微信支付'
  }
  return map[channel] || channel || '-'
}

const assignForm = (data = {}) => {
  Object.assign(form, {
    base_url: data.base_url || '',
    pid: data.pid || '',
    key: data.key || '',
    notify_url: data.notify_url || '',
    return_url: data.return_url || '',
    channel_type: data.channel_type || ''
  })
  originalForm.value = { ...form }
}

const fetchConfig = async () => {
  loading.value = true
  try {
    const res = await getPay007Config()
    if (res.data.code === 200) {
      assignForm(res.data.data || {})
    } else {
      ElMessage.error(res.data.message || '获取支付配置失败')
    }
  } catch (error) {
    console.error('获取 007pay 支付配置失败:', error)
    ElMessage.error(error.response?.data?.message || '获取支付配置失败')
  } finally {
    loading.value = false
  }
}

const submitForm = async () => {
  const formEl = formRef.value
  if (formEl) {
    const valid = await formEl.validate().catch(() => false)
    if (!valid) return
  }

  saving.value = true
  try {
    const res = await updatePay007Config({ ...form })
    if (res.data.code === 200) {
      assignForm(res.data.data || form)
      ElMessage.success('支付配置已保存')
    } else {
      ElMessage.error(res.data.message || '保存支付配置失败')
    }
  } catch (error) {
    console.error('保存 007pay 支付配置失败:', error)
    ElMessage.error(error.response?.data?.message || '保存支付配置失败')
  } finally {
    saving.value = false
  }
}

const resetForm = () => {
  Object.assign(form, originalForm.value)
  formRef.value?.clearValidate()
}

onMounted(fetchConfig)
</script>

<style scoped>
.payment-config-page {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.page-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  padding: 18px 20px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.title-block {
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 0;
}

.title-icon {
  width: 42px;
  height: 42px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f0f9eb;
  color: #67c23a;
  font-size: 22px;
  flex-shrink: 0;
}

.title-block h2 {
  margin: 0;
  color: #1f2d3d;
  font-size: 18px;
  font-weight: 600;
}

.title-block p {
  margin: 4px 0 0;
  color: #909399;
  font-size: 13px;
}

.toolbar-actions {
  display: flex;
  gap: 10px;
  flex-shrink: 0;
}

.summary-grid {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 12px;
}

.summary-item {
  padding: 14px 16px;
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 8px;
}

.summary-label {
  color: #909399;
  font-size: 12px;
  margin-bottom: 8px;
}

.summary-value {
  min-height: 24px;
  color: #303133;
  font-size: 15px;
  font-weight: 600;
  word-break: break-all;
}

.summary-value.mono {
  font-family: Consolas, Monaco, monospace;
}

.config-panel {
  padding: 24px 22px 18px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.config-form {
  max-width: 880px;
}

.panel-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 18px;
  border-top: 1px solid #f0f2f5;
}

@media (max-width: 900px) {
  .page-toolbar {
    align-items: flex-start;
    flex-direction: column;
  }

  .toolbar-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .summary-grid {
    grid-template-columns: 1fr;
  }
}
</style>
