<template>
    <div class="card">
        <el-space>
            <el-button type="primary" icon="Plus" @click="addHandle">添加菜单</el-button>
        </el-space>
        <div class="mt15">
            <el-space>
                <el-input placeholder="请输入appid搜索" v-model="tableOptions.appId" style="width: 200px;" />
                <el-button type="primary" icon="Search" @click="searchHandle">搜索</el-button>
                <el-button icon="RefreshRight" @click="resizeTable">重置</el-button>
            </el-space>
        </div>
        <div class="table mt15">
            <el-table ref="table" :data="tableOptions.list" border height="100%" v-loading="tableOptions.loading">
                <el-table-column prop="id" label="ID" width="50"></el-table-column>
                <el-table-column prop="appId" label="商户号"></el-table-column>
                <el-table-column prop="merchantName" label="商户名称"></el-table-column>
                <!-- <el-table-column prop="storeName" label="店铺名称"></el-table-column> -->
                <el-table-column prop="ip" label="允许访问的ip"></el-table-column>
                <el-table-column prop="publicKey" label="公钥">
                    <template #default="scope">
                        <el-popover title="点击复制" effect="dark" :width="500" :content="scope.row.publicKey">
                            <template #reference>
                                <el-text type="primary" tag="ins" truncated @click="copyHandle(scope.row.publicKey)">
                                    <el-icon>
                                        <CopyDocument />
                                    </el-icon>
                                    {{ scope.row.publicKey }}
                                </el-text>
                            </template>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column prop="privateKey" label="私钥">
                    <template #default="scope">
                        <el-popover title="点击复制" effect="dark" :width="500" :content="scope.row.privateKey">
                            <template #reference>
                                <el-text type="primary" tag="ins" truncated @click="copyHandle(scope.row.privateKey)">
                                    <el-icon>
                                        <CopyDocument />
                                    </el-icon>
                                    {{ scope.row.privateKey }}
                                </el-text>
                            </template>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间">
                    <template #default="scope">
                        <el-text>{{ scope.row.createTime && dayjs(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss')
                        }}</el-text>
                    </template>
                </el-table-column>
                <el-table-column prop="updateTime" label="更新时间">
                    <template #default="scope">
                        <el-text>{{ scope.row.updateTime && dayjs(scope.row.updateTime).format('YYYY-MM-DD HH:mm:ss')
                        }}</el-text>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                    <template #default="scope">
                        <el-button type="primary" size="small" icon="Edit" @click="editorHandle(scope.row)">编辑</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="mt15">
            <el-pagination layout="prev, pager, next, total, sizes, jumper" background
                v-model:current-page="tableOptions.pageNum" v-model:page-size="tableOptions.pageSzie"
                :page-size="tableOptions.pageSzie" :page-sizes="[10, 20, 30, 50]" :total="tableOptions.total"
                @size-change="paginationChange" @current-change="paginationChange" />
        </div>
    </div>
    <el-dialog title="新增api" v-model="showDialog" @closed="dialogClosed">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120" label-position="left">
            <el-form-item prop="appId" label="appId" v-if="type == 1">
                <el-input placeholder="请输入appId" v-model="form.appId" />
            </el-form-item>
            <el-form-item prop="ip" label="ip">
                <el-input type="textarea" :autosize="{ minRows: 2 }" placeholder="请输入ip，多个ip用,分割" v-model="form.ip" />
            </el-form-item>
            <el-form-item label="编辑公钥/私钥" v-if="type == 2">
                <el-switch v-model="showKey"></el-switch>
            </el-form-item>
            <template v-if="showKey">
                <el-form-item prop="publicKey" label="公钥">
                    <el-input type="textarea" :autosize="{ minRows: 2 }" placeholder="请输入公钥" v-model="form.publicKey" />
                </el-form-item>
                <el-form-item prop="privateKey" label="私钥">
                    <el-input type="textarea" :autosize="{ minRows: 2 }" placeholder="请输入私钥" v-model="form.privateKey" />
                    <el-text type="warning" size="small" v-if="type == 2">注意：更改公钥/密钥会导致打印机无法使用</el-text>
                </el-form-item>
                <el-form-item>
                    <el-button type="success" icon="Connection" :loading="keyLoading"
                        @click="createKeyAjax">一键获取公钥/私钥</el-button>
                </el-form-item>
            </template>
        </el-form>
        <template #footer>
            <el-space>
                <el-button @click="showDialog = false">取消</el-button>
                <el-button type="primary" :loading="formLoading" @click="submitHandle">提交</el-button>
            </el-space>
        </template>
    </el-dialog>
</template>

<script setup>
import useClipboard from 'vue-clipboard3'
import { dayjs, ElMessage } from 'element-plus'
import { querySystemApis, createKey, initApi, modfityApi } from '@/api/setting.js'
const { toClipboard } = useClipboard()

const showKey = ref(true)

const table = ref(null)
// 表格参数
const tableOptions = reactive({
    loading: true,
    appId: '',
    list: [],
    total: 0,
    pageNum: 1,
    pageSzie: 10
})

// 显示添加表单
const showDialog = ref(false)
const formLoading = ref(false)
const type = ref(1) // 1添加 2编辑
const formRef = ref(null)
const keyLoading = ref(false)

// 创建表单
const form = reactive({
    id: '',
    appId: '',
    ip: '',
    publicKey: '',
    privateKey: ''
})

// 表单校验规则
const rules = reactive({
    appId: [
        {
            required: true,
            message: '',
            trigger: 'blur'
        }
    ],
    ip: [
        {
            required: true,
            message: '',
            trigger: 'blur'
        }
    ],
    publicKey: [
        {
            required: true,
            message: '',
            trigger: 'blur'
        }
    ],
    privateKey: [
        {
            required: true,
            message: '',
            trigger: 'blur'
        }
    ]
})

// 编辑
function editorHandle(row) {
    showDialog.value = true
    showKey.value = false
    type.value = 2
    form.id = row.id
    form.ip = row.ip
    form.publicKey = row.publicKey
    form.privateKey = row.privateKey
}

// 复制
async function copyHandle(text) {
    try {
        await toClipboard(text)
        ElMessage.success('复制成功')
    } catch (error) {
        ElMessage.error('复制失败，请重试')
    }
}

// 获取密钥对
async function createKeyAjax() {
    try {
        keyLoading.value = true
        const res = await createKey()
        ElMessage.success('获取成功')
        keyLoading.value = false
        form.publicKey = res.publicKey
        form.privateKey = res.privateKey
    } catch (error) {
        keyLoading.value = false
    }
}

// 表单关闭
function dialogClosed() {
    formRef.value.resetFields()
    form.id = ''
    form.appId = ''
    form.ip = ''
    form.publicKey = ''
    form.privateKey = ''
}

// 添加
function addHandle() {
    type.value = 1
    showDialog.value = true
}

// 提交表单
const submitHandle = async () => {
    await formRef.value.validate(async (vaild) => {
        if (vaild) {
            try {
                formLoading.value = true
                if (type.value == 1) {
                    await initApi(form)
                } else {
                    await modfityApi(form)
                }
                formLoading.value = false
                showDialog.value = false
                ElMessage.success(type.value == 1 ? '添加成功' : '编辑成功')
                paginationChange()
            } catch (error) {
                formLoading.value = false
            }
        }
    })
}


// 重置表格
function resizeTable() {
    tableOptions.appId = ''
    searchHandle()
}

// 搜索
function searchHandle() {
    tableOptions.pageNum = 1;
    paginationChange()
}

// 分页回调
function paginationChange() {
    tableOptions.loading = true
    getTableData()
}

// 获取appid 信息
async function getTableData() {
    try {
        const res = await querySystemApis({
            appId: tableOptions.appId,
            pageNum: tableOptions.pageNum,
            pageSize: tableOptions.pageSzie
        })
        tableOptions.loading = false
        tableOptions.list = res.list
        tableOptions.total = res.total
        table.value.setScrollTop(0)
    } catch (error) { }
}

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

<style scoped lang="scss">
.table {
    height: calc(100vh - 356px);
}
</style>