<template>
    <hc-dialog v-model="showModal" ui="hc-sms-auth-dialog" widths="30rem" :padding="false" :footer="false" :is-close="false" @close="cancelClick">
        <hc-tab-card :tabs="tabsData" :tab-key="tabsKey" is-action-btn contents @change="tabsChange">
            <div v-if="tabsKey === '1'" class="relative p-[14px]">
                <el-form ref="reportFormRef" :model="reportModel" :rules="reportRules" label-width="auto">
                    <el-form-item label="手机号码">
                        <el-input v-model="phoneVal" disabled placeholder="手机号码" />
                    </el-form-item>
                    <el-form-item class="hc-input-button-group" label="验证码" prop="code">
                        <el-input v-model="reportModel.code" placeholder="请输入验证码" />
                        <el-button :disabled="isDisabled" type="primary" @click="getCodeClick">
                            {{ isDisabled ? `倒计时${currentTime}s` : '获取验证码' }}
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div v-if="tabsKey === '2'" class="relative p-[14px]">
                <div class="relative mb-24px text-center">
                    <el-button v-if="isUKey" type="warning" size="large" @click="linkUkeyClick">已连接UKey</el-button>
                    <el-button v-else type="success" size="large" @click="linkUkeyClick">点击连接UKey</el-button>
                </div>
                <div class="mb-10px text-red-6">操作步骤：</div>
                <div class="mb-10px">第一步、插入UKey在电脑上（一定要先插入密钥UKey），点击上方按钮连接配对</div>
                <div class="mb-10px">第二步、选择【Utap】，点击【连接】，当页面显示【已配对】</div>
                <div class="relative">
                    <img :src="HcImgUKey" class="w-full" alt="">
                </div>
            </div>
            <template #action>
                <el-button @click="cancelClick">
                    <hc-icon name="close" />
                    <span>取消</span>
                </el-button>
                <el-button :loading="isLoading" type="primary" @click="confirmClick">
                    <hc-icon name="check" />
                    <span>确认</span>
                </el-button>
            </template>
        </hc-tab-card>
    </hc-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import { formValidate } from 'js-fast-way'
import { saveSmsTimeout, sendNotice } from '~api/other'
import config from '~src/config/index'
import HcImgUKey from '~src/assets/view/ukey.png'

//参数
const props = defineProps({
    show: {
        type: Boolean,
        default: false,
    },
    tabKey: {
        type: String,
        default: '1',
    },
})

//事件
const emit = defineEmits(['cancel', 'confirm'])
//变量
const userStore = useAppStore()
const userInfo = ref(userStore.getUserInfo)
const projectId = ref(userStore.getProjectId)

const phoneVal = ref(config.smsPhone + '' || userInfo.value.phone + '')
const showModal = ref(props.show)


//Ukey是否存在
const isUKey = ref(userStore.getIsUKey)
watch(() => userStore.getIsUKey, (ukey) => {
    isUKey.value = ukey
}, { immediate: true, deep: true })

//监听
watch(() => [props.show, userStore.getUserInfo], ([show, user]) => {
    userInfo.value = user
    showModal.value = show
    if (show) setDataApi()
})

//处理数据
const setDataApi = () => {
    tabsKey.value = props.tabKey
}

//tab
const tabsKey = ref('1')
const tabsData = ref([
    { key: '1', name: '个人认证' },
    { key: '2', name: '公章认证' },
])
const tabsChange = ({ key }) => {
    tabsKey.value = key
}

//返回的验证码
const resCode = ref('')
//表单
const reportFormRef = ref(null)
const reportModel = ref({ code: null })
const reportRules = ref({
    code: {
        required: true,
        validator: (rule, value, callback) => {
            const code = resCode.value ?? ''
            if (!code) {
                callback(new Error('请先获取验证码'))
            } else if (!value) {
                callback(new Error('请输入验证码'))
            } else if (code !== value) {
                callback(new Error('验证码错误'))
            } else {
                callback()
            }
        },
        trigger: 'blur',
    },
})

//短信验证码
const isDisabled = ref(false) //是否开启倒计时
const totalTime = 60 //总时间，单位秒
const recordingTime = ref(0) //记录时间变量
const currentTime = ref(0) //显示时间变量

//获取短信验证码
const getCodeClick = async () => {
    const { error, code, msg } = await sendNotice({
        phone: phoneVal.value,
    }, false)
    //处理数据
    if (!error && code === 200 && msg) {
        resCode.value = msg
        //把显示时间设为总时间
        currentTime.value = totalTime
        //开始倒计时
        isDisabled.value = true
        //执行倒计时
        checkingTime()
        window?.$message?.success('发送成功')
    } else {
        resCode.value = ''
        window?.$message?.error(msg || '请求异常')
    }
}

//倒计时
const checkingTime = () => {
    //判断是否开启
    if (isDisabled.value) {
        //判断显示时间是否已到0，判断记录时间是否已到总时间
        if (currentTime.value > 0 && recordingTime.value <= totalTime) {
            //记录时间增加 1
            recordingTime.value++
            //显示时间，用总时间 - 记录时间
            currentTime.value = totalTime - recordingTime.value
            //1秒钟后，再次执行本方法
            setTimeout(() => {
                checkingTime()
            }, 1000)
        } else {
            //时间已完成，还原相关变量
            isDisabled.value = false		//关闭倒计时
            recordingTime.value = 0	//记录时间为0
            currentTime.value = totalTime	//显示时间为总时间
        }
    } else {
        //倒计时未开启，初始化默认变量
        isDisabled.value = false
        recordingTime.value = 0
        currentTime.value = totalTime
    }
}

//取消
const cancelClick = () => {
    emit('cancel')
}

//确认
const isLoading = ref(false)
const confirmClick = async () => {
    if (tabsKey.value === '1') {
        const validate = await formValidate(reportFormRef.value)
        if (validate) {
            await saveSmsTimeoutApi()
            emit('confirm', true)
        }
    } else if (tabsKey.value === '2') {
        if (isUKey.value) {
            emit('confirm', false)
        } else {
            window?.$message?.warning('请先连接UKey')
        }
    }
}

//验证码过期时间
const saveSmsTimeoutApi = async () => {
    isLoading.value = true
    await saveSmsTimeout({
        code: resCode.value,
        projectId: projectId.value,  
    })
    isLoading.value = false
}

//连接UKey
const linkUkeyClick = () => {
    navigator.usb.requestDevice({
        filters: [{ vendorId: 10367 }],
    }).then(data => {
        if (data.manufacturerName === 'CFIST') {
            userStore.setIsUKey(true)
            isUKey.value = true
        }
    }).catch(() => {})
}
</script>

<style lang="scss">
.el-overlay-dialog .el-dialog.hc-new-dialog.hc-sms-auth-dialog {
    --el-dialog-padding-primary: 2px;
    .el-dialog__header {
        display: none;
    }
    .el-card.hc-card-box.hc-new-card-box .hc-card-action.is-action-btn {
        border-top: 1px solid #E9E9E9;
        padding-top: 14px;
    }
}
</style>
