<template>
    <div class="main-wrapper">
        <div class="container-fluid">
            <div class="row justify-content-center">
                <div class="col-12">
                    <div class="card shadow-lg">
                        <div
                            class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">支付设置</h5>
                            <button class="btn btn-outline-light btn-sm" @click="resetForm">
                                <i class="fa fa-sync-alt"></i> 重置
                            </button>
                        </div>
                        <div class="card-body">

                            <!-- 支付方式 -->
                            <div class="mb-5">
                                <label class="d-block font-weight-bold mb-3">支付方式</label>
                                <div class="d-flex flex-wrap">
                                    <button v-for="method in paymentMethodsObj" :key="method.id"
                                        class="btn btn-outline-primary mr-3 mb-2"
                                        :class="{ active: form.method === method.name }"
                                        @click="form.method = method.name; form.payType = ''">
                                        {{ method.name }}
                                    </button>
                                </div>
                            </div>

                            <!-- 接口类型 -->
                            <transition name="fade">
                                <div v-if="form.method" class="mb-5">
                                    <label class="d-block font-weight-bold mb-3">接口类型</label>
                                    <div class="d-flex flex-wrap">
                                        <button v-for="type in interfaceTypesObj" :key="type.id"
                                            class="btn btn-outline-success mr-3 mb-2"
                                            :class="{ active: form.payType === type.name }"
                                            @click="form.payType = type.name">
                                            {{ type.name }}
                                        </button>
                                    </div>
                                </div>
                            </transition>

                            <!-- 详细配置 -->
                            <transition name="slide-fade">
                                <div v-if="form.method && form.payType" class="payment-form">
                                    <div class="row">
                                         <!-- 是否启用 -->
            <div class="col-12 mb-4">
                <label class="form-label">是否启用</label>
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="enabled"
                        v-model="form.isEnabled">
                    <label class="form-check-label" for="enabled">
                        {{ form.isEnabled ? '已启用' : '已停用' }}
                    </label>
                </div>
            </div>
                                        <div class="col-md-6 mb-4">
                                            <label for="appId" class="form-label">App ID</label>
                                            <input type="text" id="appId" class="form-control" v-model="form.appId"
                                                placeholder="请输入 App ID" />
                                        </div>
                                        <div class="col-md-6 mb-4">
                                            <label for="secretKey" class="form-label">密钥 Secret Key</label>
                                            <input type="text" id="secretKey" class="form-control"
                                                v-model="form.secretKey" placeholder="请输入 Secret Key" />
                                        </div>
                                        <div class="col-md-6 mb-4" v-if="form.method !== '支付宝'">
                                            <label for="mchId" class="form-label">商户号（Mch ID）</label>
                                            <input type="text" id="mchId" class="form-control" v-model="form.mchId"
                                                placeholder="请输入 商户号" />
                                        </div>
                                        <div class="col-md-6 mb-4">
                                            <label for="publicKey" class="form-label">API 公钥</label>
                                            <div class="input-group">
                                                <input type="text" id="publicKey" class="form-control"
                                                    v-model="form.publicKey" placeholder="请输入 API 公钥" />
                                                <div class="input-group-append">
                                                    <button class="btn btn-outline-secondary" @click="copyApiKey"
                                                        type="button" title="复制">
                                                        <i class="fa fa-copy"></i>
                                                    </button>
                                                    <button class="btn btn-outline-danger" @click="regenerateApiKey"
                                                        type="button" title="重置">
                                                        <i class="fa fa-redo"></i>
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                        <!-- 第四方支付特有 网站地址 配置 -->
                                        <div class="col-12 mb-4" v-if="form.payType === '易支付'">
                                            <label for="url" class="form-label">支付网关地址</label>
                                            <input type="text" id="url" class="form-control" v-model="form.url"
                                                placeholder="请输入第四方支付网关地址" />
                                        </div>
                                    </div>
                                </div>
                            </transition>

                            <!-- 操作按钮 -->
                            <div class="mt-4 text-right">
                                <button class="btn btn-success" @click="saveSettings">
                                    <i class="fa fa-save"></i> 保存设置
                                </button>
                            </div>

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import axiosIntance from '@/request/request'

export default {
    name: 'PaymentSettings',
    data() {
        return {
            paymentMethodsObj: [
                { id: 0, name: '支付宝' },
                { id: 1, name: '微信' },
                { id: 3, name: 'QQ' }
            ],
            interfaceTypesObj: [
                { id: 1, name: '官方' },
                { id: 2, name: '易支付' }
            ],
            form: {
                method: '',
                payType: '',
                appId: '',
                secretKey: '',
                mchId: '',
                publicKey: '',
                url: '',
                isEnabled: false
            },
            payments: [],
            componentKey: 0
        }
    },
    methods: {
        resetForm() {
            this.form = {
                method: '', payType: '', appId: '', secretKey: '', mchId: '', publicKey: '', url: ''
            }
        },
        async saveSettings() {
            if (!this.form.method || !this.form.payType) {
                this.$alert('请选择支付方式和接口类型', 'danger')
                return
            }
            // TODO: 调用后端接口保存 form 数据
            //this.$emit('refresh')
            try {
                let data = JSON.parse(JSON.stringify(this.form));
                data.payType = this.interfaceTypesObj.find(x => x.name == this.form.payType).id
                data.method = this.paymentMethodsObj.find(x => x.name == this.form.method).id
                data.notifyUrl = axiosIntance.defaults.baseURL + '/api/pay/notice'
                const res = await this.$api.updatePayment(data)
                if(res.code != 1000){
                    this.$alert(res.message,'danger')
                    return;
                }
                this.$alert('支付设置已保存', 'success')
                 await this.loadPayments()
            } catch (e) {
                this.$alert('支付配置保存失败', 'danger')
                console.error(e)
            }
        },
        copyApiKey() {
            if (!this.form.publicKey) return
            navigator.clipboard.writeText(this.form.publicKey).then(() => {
                this.$alert('已复制 API 公钥', 'success')
            })
        },
        regenerateApiKey() {
            if (confirm('确定要重置 API 公钥？旧公钥将失效。')) {
                // TODO: 调用后端接口重新获取公钥
                //this.form.publicKey = '新生成的API公钥示例'
                this.$alert('测试功能...', 'success')
            }
        },
        async loadPayments() {
            try {
                const res = await this.$api.getAllPayment()
                if (res.code != 1000) {
                    this.$alert(res.message, 'danger')
                    return;
                }
                this.payments = res.data
            } catch (e) {
                this.$alert('支付配置加载失败', 'danger')
                console.error(e)
            }
        }
    },
    watch: {
        'form.payType': {
            handler(newVal) {
                if(this.form.payType == '' || this.form.method == '') return;
                const method = this.paymentMethodsObj.find(x => x.name == this.form.method)
                const payType = this.interfaceTypesObj.find(x => x.name == this.form.payType)
                const payment = this.payments.find(x => x.method == method.id && x.payType == payType.id)
                if (payment) {
                    this.form.id = payment.id
                    this.form.appId = payment.appId
                    this.form.mchId = ''
                    this.form.publicKey = payment.publicKey
                    this.form.secretKey = payment.secretKey
                    this.form.url = payment.url
                    this.form.isEnabled = payment.isEnabled
                } else {
                    
                    this.form.appId = '';
                    this.form.secretKey = '';
                    this.form.mchId = '';
                    this.form.publicKey = '';
                    this.form.url = '';
                    this.form.isEnabled = false
                    
                }
            },
            immediate: false
        }
    },
    async mounted() {
        await this.loadPayments()
    }
}
</script>

<style scoped>
.card {
    max-width: 1200px;
    margin: 0 auto;
}

.fade-enter-active,
.fade-leave-active {
    transition: opacity .3s;
}

.fade-enter,
.fade-leave-to {
    opacity: 0;
}

.slide-fade-enter-active {
    transition: all .4s ease;
}

.slide-fade-enter,
.slide-fade-leave-to {
    transform: translateY(-10px);
    opacity: 0;
}
</style>
