<template>
  <div>
    <div class="gva-search-box">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" @keyup.enter="handleSearch">
        <el-form-item label="支付名称">
          <el-input v-model="searchForm.name" placeholder="输入名称" clearable />
        </el-form-item>
        <el-form-item label="支付编码">
          <el-input v-model="searchForm.code" placeholder="输入编码" clearable />
        </el-form-item>
        <el-form-item label="支付类型">
          <el-select v-model="searchForm.type" placeholder="全部" clearable style="width: 160px">
            <el-option v-for="opt in typeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="启用状态">
          <el-select v-model="searchForm.enable" placeholder="全部" clearable style="width: 140px">
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleSearch">查询</el-button>
          <el-button icon="refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="openCreate">新增支付配置</el-button>
      </div>

      <el-table
        :data="tableData"
        v-loading="tableLoading"
        style="width: 100%"
        row-key="ID"
      >
        <el-table-column prop="ID" label="ID" width="80" />
        <el-table-column prop="name" label="名称" min-width="180" show-overflow-tooltip />
        <el-table-column prop="code" label="编码" min-width="160" show-overflow-tooltip />
        <el-table-column label="类型" width="120">
          <template #default="{ row }">
            <el-tag :type="row.type === 'wechat' ? 'success' : 'primary'">
              {{ formatType(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="90" />
        <el-table-column label="启用" width="110">
          <template #default="{ row }">
            <el-switch
              v-model="row.enable"
              :loading="row._toggleLoading"
              active-text="启用"
              inactive-text="禁用"
              @change="() => handleToggle(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
        <el-table-column prop="CreatedAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.CreatedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" min-width="230">
          <template #default="{ row }">
            <el-button link type="primary" @click="openDetail(row)">查看</el-button>
            <el-button link type="primary" icon="edit" @click="openEdit(row)">编辑</el-button>
            <el-button link type="danger" icon="delete" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="gva-pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <el-drawer
      destroy-on-close
      v-model="formVisible"
      :size="appStore.drawerSize"
      :show-close="false"
      :before-close="closeForm"
    >
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ isEdit ? '编辑支付配置' : '新增支付配置' }}</span>
          <div>
            <el-button type="primary" :loading="btnLoading" @click="submitForm">确 定</el-button>
            <el-button @click="closeForm">取 消</el-button>
          </div>
        </div>
      </template>

      <el-form ref="formRef" :model="formData" :rules="rules" label-position="top">
        <el-form-item label="支付名称" prop="name">
          <el-input v-model="formData.name" placeholder="例如：微信支付-主账号" />
        </el-form-item>
        <el-form-item label="支付编码（唯一，创建后不建议修改）" prop="code">
          <el-input v-model="formData.code" :disabled="isEdit" placeholder="例如：wechat_main" />
        </el-form-item>
        <el-form-item label="支付类型" prop="type">
          <el-radio-group v-model="formData.type" @change="handleTypeChange">
            <el-radio label="shenqi">神奇支付</el-radio>
            <el-radio label="wechat">微信支付</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否启用" prop="enable">
          <el-switch v-model="formData.enable" active-text="启用" inactive-text="禁用" />
        </el-form-item>
        <el-form-item label="排序（越小越靠前，建议10的倍数）" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :step="1" controls-position="right" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :rows="2" placeholder="备注说明" />
        </el-form-item>

        <el-divider>神奇支付配置</el-divider>
        <template v-if="formData.type === 'shenqi'">
          <el-form-item label="神奇支付商户ID" prop="shenqiPid">
            <el-input-number v-model="formData.shenqiPid" :min="1" :step="1" controls-position="right" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="商户私钥" prop="shenqiPrivateKey">
            <el-input v-model="formData.shenqiPrivateKey" type="textarea" :rows="4" placeholder="支持Base64或PEM格式" />
          </el-form-item>
          <el-form-item label="平台公钥" prop="shenqiPlatformPubKey">
            <el-input v-model="formData.shenqiPlatformPubKey" type="textarea" :rows="3" placeholder="平台公钥" />
          </el-form-item>
          <el-form-item label="异步回调地址" prop="shenqiNotifyUrl">
            <el-input v-model="formData.shenqiNotifyUrl" placeholder="http://your-domain.com/app_order/shenqi/notify/{code}" />
          </el-form-item>
          <el-form-item label="同步跳转地址" prop="shenqiReturnUrl">
            <el-input v-model="formData.shenqiReturnUrl" placeholder="http://your-domain.com/pay/success" />
          </el-form-item>
          <el-form-item label="API基础地址" prop="shenqiBaseUrl">
            <el-input v-model="formData.shenqiBaseUrl" placeholder="默认：https://www.shenqiyzf.cn" />
          </el-form-item>
        </template>

        <el-divider>微信支付配置</el-divider>
        <template v-if="formData.type === 'wechat'">
          <el-form-item label="微信AppID" prop="wechatAppId">
            <el-input v-model="formData.wechatAppId" placeholder="微信开放平台AppID" />
          </el-form-item>
          <el-form-item label="商户号" prop="wechatMchId">
            <el-input v-model="formData.wechatMchId" placeholder="微信商户号" />
          </el-form-item>
          <el-form-item label="API V3密钥" prop="wechatMchApiV3Key">
            <el-input v-model="formData.wechatMchApiV3Key" placeholder="32位API V3密钥" />
          </el-form-item>
          <el-form-item label="商户私钥" prop="wechatPrivateKey">
            <el-input v-model="formData.wechatPrivateKey" type="textarea" :rows="4" placeholder="PEM格式私钥" />
          </el-form-item>
          <el-form-item label="证书序列号" prop="wechatSerialNo">
            <el-input v-model="formData.wechatSerialNo" placeholder="证书序列号" />
          </el-form-item>
          <el-form-item label="回调地址" prop="wechatNotifyUrl">
            <el-input v-model="formData.wechatNotifyUrl" placeholder="http://your-domain.com/app_order/notify/{code}" />
          </el-form-item>
        </template>
      </el-form>
    </el-drawer>

    <el-drawer destroy-on-close v-model="detailVisible" :size="appStore.drawerSize" title="支付配置详情">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="名称">{{ detailData.name }}</el-descriptions-item>
        <el-descriptions-item label="编码">{{ detailData.code }}</el-descriptions-item>
        <el-descriptions-item label="类型">{{ formatType(detailData.type) }}</el-descriptions-item>
        <el-descriptions-item label="启用">{{ detailData.enable ? '是' : '否' }}</el-descriptions-item>
        <el-descriptions-item label="排序">{{ detailData.sort ?? '-' }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ detailData.remark || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(detailData.CreatedAt) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDate(detailData.UpdatedAt) }}</el-descriptions-item>
        <template v-if="detailData.type === 'shenqi'">
          <el-descriptions-item label="商户ID">{{ detailData.shenqiPid }}</el-descriptions-item>
          <el-descriptions-item label="商户私钥">
            <div class="secret-text">{{ detailData.shenqiPrivateKey || '-' }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="平台公钥">
            <div class="secret-text">{{ detailData.shenqiPlatformPubKey || '-' }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="回调地址">{{ detailData.shenqiNotifyUrl || '-' }}</el-descriptions-item>
          <el-descriptions-item label="跳转地址">{{ detailData.shenqiReturnUrl || '-' }}</el-descriptions-item>
          <el-descriptions-item label="基础地址">{{ detailData.shenqiBaseUrl || '-' }}</el-descriptions-item>
        </template>
        <template v-else-if="detailData.type === 'wechat'">
          <el-descriptions-item label="AppID">{{ detailData.wechatAppId }}</el-descriptions-item>
          <el-descriptions-item label="商户号">{{ detailData.wechatMchId }}</el-descriptions-item>
          <el-descriptions-item label="API V3密钥">{{ detailData.wechatMchApiV3Key || '-' }}</el-descriptions-item>
          <el-descriptions-item label="商户私钥">
            <div class="secret-text">{{ detailData.wechatPrivateKey || '-' }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="证书序列号">{{ detailData.wechatSerialNo || '-' }}</el-descriptions-item>
          <el-descriptions-item label="回调地址">{{ detailData.wechatNotifyUrl || '-' }}</el-descriptions-item>
        </template>
      </el-descriptions>
    </el-drawer>
  </div>
</template>

<script setup>
import { list, detail, createPayConfig, updatePayConfig, removePayConfig, togglePayConfig } from '@/api/payConfig/index.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, computed, nextTick } from 'vue'
import { formatDate } from '@/utils/format'
import { useAppStore } from '@/pinia'

defineOptions({ name: 'PayConfig' })

const appStore = useAppStore()

const typeOptions = [
  { label: '神奇支付', value: 'shenqi' },
  { label: '微信支付', value: 'wechat' }
]

const searchForm = ref({
  name: '',
  code: '',
  type: '',
  enable: ''
})

const tableData = ref([])
const tableLoading = ref(false)
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

const btnLoading = ref(false)
const formVisible = ref(false)
const formRef = ref(null)
const formType = ref('create')

const initForm = () => ({
  ID: undefined,
  name: '',
  code: '',
  type: 'shenqi',
  enable: false,
  sort: 10,
  remark: '',
  shenqiPid: null,
  shenqiPrivateKey: '',
  shenqiPlatformPubKey: '',
  shenqiNotifyUrl: '',
  shenqiReturnUrl: '',
  shenqiBaseUrl: 'https://www.shenqiyzf.cn',
  wechatAppId: '',
  wechatMchId: '',
  wechatMchApiV3Key: '',
  wechatPrivateKey: '',
  wechatSerialNo: '',
  wechatNotifyUrl: ''
})

const formData = ref(initForm())

const isEdit = computed(() => formType.value === 'update')

const requiredWhen = (type, message) => ({
  validator: (_, value, callback) => {
    if (formData.value.type !== type) return callback()
    if (value === null || value === undefined || value === '') return callback(new Error(message))
    callback()
  },
  trigger: 'blur'
})

const rules = reactive({
  name: [{ required: true, message: '请输入支付名称', trigger: ['blur', 'input'] }],
  code: [{ required: true, message: '请输入支付编码', trigger: ['blur', 'input'] }],
  type: [{ required: true, message: '请选择支付类型', trigger: 'change' }],
  shenqiPid: [requiredWhen('shenqi', '请输入神奇支付商户ID')],
  shenqiPrivateKey: [requiredWhen('shenqi', '请输入商户私钥')],
  shenqiPlatformPubKey: [requiredWhen('shenqi', '请输入平台公钥')],
  shenqiNotifyUrl: [requiredWhen('shenqi', '请输入神奇支付回调地址')],
  shenqiReturnUrl: [requiredWhen('shenqi', '请输入神奇支付跳转地址')],
  wechatAppId: [requiredWhen('wechat', '请输入微信AppID')],
  wechatMchId: [requiredWhen('wechat', '请输入微信商户号')],
  wechatMchApiV3Key: [requiredWhen('wechat', '请输入API V3密钥')],
  wechatPrivateKey: [requiredWhen('wechat', '请输入微信商户私钥')],
  wechatSerialNo: [requiredWhen('wechat', '请输入证书序列号')],
  wechatNotifyUrl: [requiredWhen('wechat', '请输入微信回调地址')]
})

const formatType = (type) => (type === 'wechat' ? '微信支付' : '神奇支付')

const fetchList = async () => {
  tableLoading.value = true
  try {
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      ...searchForm.value
    }
    const res = await list(params)
    if (res.code === 0) {
      tableData.value = (res.data?.list || []).map((item) => ({
        ...item,
        enable: !!item.enable,
        _toggleLoading: false
      }))
      total.value = res.data?.total || 0
      page.value = res.data?.page || page.value
      pageSize.value = res.data?.pageSize || pageSize.value
    }
  } finally {
    tableLoading.value = false
  }
}

const handleSearch = () => {
  page.value = 1
  fetchList()
}

const handleReset = () => {
  searchForm.value = {
    name: '',
    code: '',
    type: '',
    enable: ''
  }
  page.value = 1
  pageSize.value = 10
  fetchList()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchList()
}

const handleCurrentChange = (val) => {
  page.value = val
  fetchList()
}

const closeForm = () => {
  formVisible.value = false
  formRef.value?.resetFields()
  formData.value = initForm()
}

const handleTypeChange = () => {
  // 清空另一类型的字段，避免脏数据提交
  if (formData.value.type === 'shenqi') {
    formData.value.wechatAppId = ''
    formData.value.wechatMchId = ''
    formData.value.wechatMchApiV3Key = ''
    formData.value.wechatPrivateKey = ''
    formData.value.wechatSerialNo = ''
    formData.value.wechatNotifyUrl = ''
  } else {
    formData.value.shenqiPid = null
    formData.value.shenqiPrivateKey = ''
    formData.value.shenqiPlatformPubKey = ''
    formData.value.shenqiNotifyUrl = ''
    formData.value.shenqiReturnUrl = ''
    formData.value.shenqiBaseUrl = 'https://www.shenqiyzf.cn'
  }
  nextTick(() => formRef.value?.clearValidate())
}

const openCreate = () => {
  formType.value = 'create'
  formData.value = initForm()
  formVisible.value = true
}

const normalizeDetail = (data) => ({
  ...initForm(),
  ...(data || {}),
  enable: !!data?.enable
})

const openEdit = async (row) => {
  const res = await detail(row.ID)
  if (res.code === 0) {
    formType.value = 'update'
    formData.value = normalizeDetail(res.data)
    formVisible.value = true
  }
}

const submitForm = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return
    btnLoading.value = true
    try {
      const payload = { ...formData.value }
      const api = isEdit.value ? updatePayConfig : createPayConfig
      const res = await api(payload)
      if (res.code === 0) {
        ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
        closeForm()
        fetchList()
      }
    } finally {
      btnLoading.value = false
    }
  })
}

const handleDelete = async (row) => {
  await ElMessageBox.confirm('确定删除该支付配置吗？', '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
  const res = await removePayConfig(row.ID)
  if (res.code === 0) {
    ElMessage.success('删除成功')
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    fetchList()
  }
}

const handleToggle = async (row) => {
  const nextVal = row.enable
  row._toggleLoading = true
  try {
    const res = await togglePayConfig({ id: row.ID, enable: nextVal })
    if (res.code === 0) {
      ElMessage.success(nextVal ? '已启用' : '已禁用')
    } else {
      row.enable = !nextVal
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (e) {
    row.enable = !nextVal
  } finally {
    row._toggleLoading = false
  }
}

const detailVisible = ref(false)
const detailData = ref({})

const openDetail = async (row) => {
  const res = await detail(row.ID)
  if (res.code === 0) {
    detailData.value = normalizeDetail(res.data)
    detailVisible.value = true
  }
}

fetchList()
</script>

<style scoped>
.gva-pagination {
  margin-top: 20px;
  text-align: right;
}
.secret-text {
  white-space: pre-wrap;
  word-break: break-all;
}
</style>

