<!-- 证书查询 -->
<template>
    <app-drawer class="header-certificate" title="证书查询" :width="600" v-model:show="show">
        <el-tabs v-model="certTab">
            <el-tab-pane label="国内" :name="1" />
            <el-tab-pane label="国际" :name="2" />
        </el-tabs>
        <el-radio-group v-model="formData.certtype">
            <el-radio :label="item.certtype" v-for="(item, index) in certList" :key="index">
                {{ item.certtype }}
            </el-radio>
        </el-radio-group>
        <ul v-if="selectedCert">
            <li>
                <label>{{ selectedCert.orgenname }}</label>
                <el-input placeholder="请输入证书号" v-model="formData.certno" />
            </li>
            <li>
                <label>{{ selectedCert.orgcnname }}</label>
                <el-input placeholder="请输入防伪码" v-model="formData.certcode" />
            </li>
            <li>
                <span>{{ selectedCert.certtype }}证书数据来源于官网，所有权归{{ selectedCert.certtype }}所有。</span>
            </li>
            <li>
                <el-button type="primary" @click="formSubmit">查询</el-button>
            </li>
        </ul>
    </app-drawer>
</template>

<script lang="ts" setup>
import { reactive, shallowRef, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { gzCertAddressConfig, gzCertAddressParam } from '@/services/api/common'
import AppDrawer from '@pc/components/base/drawer/index.vue'

const show = shallowRef(true)
const certTab = shallowRef(1)
const dataList = shallowRef<Ermcp.GzCertAddressConfigRsp[]>([])
const urlParams = shallowRef<Ermcp.GzCertAddressParamRsp[]>([])

const formData = reactive({
    certtype: '', // 证书类型
    certno: '', // 证书号
    certcode: '', // 防伪码
})

// 证书列表
const certList = computed(() => (dataList.value.filter((e) => e.certregion === certTab.value)))
// 当前选中的证书
const selectedCert = computed(() => (dataList.value.find((e) => e.certtype === formData.certtype)))

const formSubmit = () => {
    const cert = selectedCert.value
    const params = urlParams.value.filter((e) => e.certtype === formData.certtype)

    const qs = params.reduce((res, e, i) => {
        if (i === 0) {
            res.push(`${e.paramkey}=${formData.certno}`)
        }
        if (i === 1) {
            res.push(`${e.paramkey}=${formData.certcode}`)
        }
        return res
    }, [] as string[])

    if (cert) {
        const url = cert.queryaddress + '?' + qs.join('&')
        window.open(url)
    } else {
        ElMessage.success('查询失败')
    }
}

gzCertAddressParam().then((res) => {
    urlParams.value = res.data
})

gzCertAddressConfig().then((res) => {
    if (res.data.length) {
        formData.certtype = res.data[0].certtype
    }
    dataList.value = res.data
})
</script>

<style lang="less">
@import './index.less';
</style>