<template>
<view>
    <view class="container">
		<view class="bg"></view>
        <view class="bg-con">
            <view class="bg-h">

                <view :style="{height: navBarPaddingTop + 'px'}"></view>
                <view class="auth-title">
                    <image src="@/static/images/icon-lock@2x.png"/>
                    <text>{{networkEnv==1?'内网':''}}设备授权</text>
                </view>
                <view class="login-con">
                    <!-- 登录 -->
                    <block v-if="!bindStatus">
                        <view class="login-form" :class="{network1:networkEnv==1}">
                            <uni-forms ref="form2" :model="formData2" :rules="rules2" label-position="top">
                                <!-- networkEnv -->
                                <uni-forms-item label="设备标识" required name="uniqCode" v-if="networkEnv==1">
                                    <view class="code-con code-device">
                                        <uni-easyinput prefixIcon="person" :inputBorder="false" 
                                            v-model="formData2.uniqCode" placeholder="请输入设备标识" 
                                        >
                                            <!-- <template #prefixIcon> -->
                                                <!-- <image src="@/static/images/login-biaoshi.png" style="width: 20px; height: 20px;" /> -->
                                            <!-- </template> -->
                                            
                                        </uni-easyinput>
                                    </view>
                                </uni-forms-item>
                                <uni-forms-item label="用户名" required name="username">
                                    <view class="code-con">
                                        <uni-easyinput prefixIcon="person" :inputBorder="false" 
                                            v-model="formData2.username" placeholder="请输入用户名" 
                                        />
                                    </view>
                                </uni-forms-item>
                                <uni-forms-item label="密码" required name="password" class="password">
                                    <view class="code-con">
                                        <uni-easyinput prefixIcon="locked" type="password" :inputBorder="false"
                                            v-model="formData2.password" placeholder="请输入登录密码"
                                        />
                                    </view>
                                </uni-forms-item>
                            </uni-forms>
                        </view>
                        <button type="primary" class="btn-submit" @click="submitForm" :loading="btnLoading" :disabled="btnLoading">设备授权申请</button>
                    </block>

                    <!-- 等待页面（定时任务查询 10秒查询一次） -->
                    <view v-if="bindStatus==2" class="login-form approval">
                        <view class="approval-title">审核中，请等待...</view>
                        <button type="primary" class="btn-refresh" @click="handleRefresh">刷新</button>
                    </view>
                    <!-- bindStatus=5-----显示授权失败，联系管理员 -->
                    <view v-if="bindStatus==5" class="login-form approval-red-con">
                        <view class="approval-red">显示授权失败，联系管理员</view>
                    </view>
                    <!-- bindStatus=3-----输入授权码页面 -->
                    <block v-if="bindStatus==3">
                        <view class="login-form approval" style="padding:110rpx 55rpx 150rpx;">
                            <view class="approval-title">审核通过，请输入授权码</view>
                            <view class="auth-code">
                                <input v-for="(item, index) in codes" 
                                    password
                                    :key="index"
                                    v-model="codes[index]"
                                    type="number"
                                    maxlength="1"
                                    :ref="el => { if (el) inputRefs[index] = el }"
                                    @input="handleInput(index, $event)"
                                    @keydown.delete="handleDelete(index, $event)"
                                    :focus="activeIndex==index"
                                    @blur="handleBlur(index,codes[index])"
                                />
                            </view>
                        </view>
                        <button type="primary" class="btn-submit" @click="handleSubmit" :loading="subLoading" :disabled="subLoading">提交</button>
                    </block>
                </view>

            </view>
        </view>

        <!-- <view class="bottom-pic">
            <image src="@/static/images/PicLogo@2x.png" class="pic-logo" /> 
            <view class="bottom-bg"></view>
        </view> -->
    </view>
</view>
</template>

<script setup>
import { ref,nextTick,onMounted,onUnmounted,getCurrentInstance } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { v4 as uuidv4 } from 'uuid'
import { getNavBarPaddingTop} from '@/utils/system.js';
import { getBindStatus,authDeviceApply,authInputCode } from '@/api/auth.js';
import {showToast,showAlert} from '@/utils/message.js'
import encryptObj from '@/utils/encrypt.js'
import { requestAndroidPermissionAsync } from '@/utils/common.js'

const { proxy } = getCurrentInstance();
import { useUserStore } from '@/stores/user';
const userStore = useUserStore();

// #ifdef APP-PLUS
// 获取 存储手机的module 
const safeSave = uni.requireNativePlugin("Tm-TmSafeSaveFileModule");
// #endif
let systemInfo = {};
let deviceId = ref(undefined);
let clientId = `${proxy.$CLIENT_ID || 2}`;
let networkEnv = ref(proxy.$NETWORK_ENV);//1-内网 2-外网
onLoad(async(opt) => {
    console.log("deviceAuth=>onLoad",clientId,networkEnv.value);
    uni.setStorageSync('page_cache',true);
    // uni.preloadPage({url: "/pages/login/login"});
    // uni.preloadPage({url: "/pages/home/home"});

    systemInfo = uni.getSystemInfoSync()
    // #ifdef APP-PLUS
    try {
        safeSave.getSafeFile({ "key": "app_device_id" }, res2 => {
            if (res2.code == 1) {
                let deviceId = res2.data;
                console.log("读取成功=>",deviceId)
                deviceId.value = deviceId; // 本地设备ID
                selectBindStatus(deviceId);
                if(bindStatus.value==2){
                    // bindStatus=2-----到等待页面（定时任务查询 10秒查询一次）
                    timer = setInterval(()=>{  
                        refreshBindStatus() 
                    },1000*10)//10秒刷新一次
                }
            } else {
                // showAlert('读取失败:'+res2.msg)
            }
        })
       
    } catch (error) {
        console.error('权限请求出错:', error);
        // showAlert('权限请求出错:', error)
    }
    // #endif
})

// 绑定状态（1=已提交、2=等待审核、3=审核通过、4=绑定成功、5=审核拒绝）
let bindStatus = ref(undefined);
let timer = null;
// 获取导航栏高度用于内容区域padding
const navBarPaddingTop = ref(0);
onMounted(async () => {
    navBarPaddingTop.value = getNavBarPaddingTop();
})

// 组件卸载时清除定时器
onUnmounted(() => {
    if (timer) clearInterval(timer)
})

// 根据设备ID查询设备状态
let selectBindStatus = async (uniqCode)=>{
    if(uniqCode){
        let res = await getBindStatus({uniqCode})
        bindStatus.value = res.bindStatus;
        //bindStatus=4-----已绑定成功，跳转用户登录页面
        if(bindStatus.value==4){
            if (userStore.isLogin) {
                uni.reLaunch({
                    url: '/pages/home/home',
                });
            }else{
                uni.reLaunch({
                    url: '/pages/login/login',
                });
            }
        }
    }
}

// 刷新定时任务
let refreshBindStatus = async ()=>{
    let res = await getBindStatus({uniqCode:deviceId.value})
    bindStatus.value = res.bindStatus;
    if(bindStatus.value==2){

    }else{
        if(bindStatus.value==4){
            if (userStore.isLogin) {
                uni.reLaunch({
                    url: '/pages/home/home',
                });
            }else{
                uni.reLaunch({
                    url: '/pages/login/login',
                });
            }
        }
        if (timer) clearInterval(timer)
    }
}

// 账号登录
const form2 = ref(null);
const formData2 = ref({
    uniqCode:'',
    username: '',
    password: ''
});

const rules2 = {
    uniqCode:{
        rules: [
            { required: true, errorMessage: '请输入设备标识' },
        ]
    },
    username: {
        rules: [
            { required: true, errorMessage: '请输入用户名' },
            // { minLength: 3, maxLength: 10, errorMessage: '用户名长度在3到10个字符之间' }
        ]
    },
    password: {
        rules: [
            { required: true, errorMessage: '请输入密码' },
            // { pattern: /^[a-zA-Z0-9]{6,12}$/, errorMessage: '密码必须是6-12位字母或数字' }
        ]
    }
};
const btnLoading=ref(false)
// 登录提交
const submitForm = async() => {
    // 用户名和密码登录
    form2.value.validate().then(async param => {
        btnLoading.value = true;
        //1-内网，2-外网
        if(networkEnv.value==1){
            deviceId.value = param.uniqCode;
        }else{
            deviceId.value = uuidv4(); //2-外网 生成的设备唯一标识
        }
        
        let password = encryptObj.Encrypt(param.username + clientId + "," + param.password);
        let params = {
            username:param.username,
            password,
            networkEnv:networkEnv.value,//1-内网，2-外网
            uniqCode:deviceId.value,
            ...systemInfo,//设备信息
            // #ifdef APP-PLUS
            verId:systemInfo.appWgtVersion,//当前版本号
            // #endif
            // #ifdef H5
            verId : systemInfo.appVersion,
            // #endif
            osAndroidApiLevel:systemInfo.osAndroidAPILevel
        }
        let res = await authDeviceApply(params);
        btnLoading.value = false;

        try {
            // 存储设备id
            safeSave.saveSafeFile({ "key": "app_device_id","value": deviceId.value}, res3 => {
                // showAlert("保存成功=>"+JSON.stringify(res3));
                if (res3.code == 1) {
                    console.log('保存成功:'+res3.msg)
                    // showAlert("保存成功=>"+res3.msg);
                    // uni.setStorageSync('app_device_id', deviceId.value)
                    bindStatus.value = res.bindStatus;//默认为 2-等待审核
                    // 刷新状态
                    refreshBindStatus();
                    timer = setInterval(()=>{ 
                        refreshBindStatus() 
                    },1000*10)//10秒刷新一次
                } else {
                    console.log("保存失败=>",res3.msg)
                    // showAlert('保存失败:'+res3.msg)
                }
            })
           
        } catch (error) {
            console.log("saveSafeFile=>",error)
            // showAlert('设备处理异常:'+error)
        }
        
    }).catch(err => {
        console.log('表单错误11:', err);
        btnLoading.value = false;
    });
};

// 刷新
const handleRefresh = ()=>{
    selectBindStatus(deviceId.value);
}

const codes = ref(Array(6).fill(''))
const inputRefs = ref([]);
const activeIndex = ref(0);//初始化焦点
let authCode = ref('')
const handleInput = (index, event) => {
    activeIndex.value = index;
    // 只允许数字输入
    const value = event.detail.value.replace(/\D/g, '')
    codes.value[index] = value
    
    // 自动跳转到下一个输入框
    if (value && index < 5) {
        nextTick(() => {
            activeIndex.value = index+1;
        })
    }

    // 输入最后一个框时获取值
    // if (index === 5 && value) {
    //     authCode.value =  codes.value.join('')
    //     console.log('输入完成:', authCode.value)
    // }
}

// 鼠标离开
const handleBlur = (index,value)=>{
    codes.value[index] = value;
    authCode.value =  codes.value.join('');
    // console.log('鼠标离开:', authCode.value)
}

const handleDelete = (index, event) => {
    // 如果当前框为空且按下删除键，跳转到上一个输入框
    if (!codes.value[index] && index > 0) {
        event.preventDefault() // 阻止默认删除行为
        nextTick(() => {
            activeIndex.value = index-1;
        })
    }
}

// 执行设备绑定
let subLoading = ref(false)
const handleSubmit=()=>{
    console.log("authCode=>",authCode.value)
    if(!authCode.value){
        showToast("请输入验证码")
        return;
    }
    if(authCode.value.length!=6){
        showToast("请正确输入验证码")
        return;
    }
    
    let uniqCode = deviceId.value;
    let param={
        uniqCode,
        authCode:authCode.value
    }
    subLoading.value=true;
    console.log("param=>",param)
    authInputCode(param).then(res=>{
        console.log("authInputCode=>",res)
        uni.reLaunch({ url: '/pages/login/login' })
    }).finally(()=>{
        subLoading.value = false;
    })
}
</script>

<style scoped>
.container {
	background:#307AF5 !important;
	height:100vh !important;
	position: relative;
}
.container .bg{
    background:url('@/static/images/bg@2x.png') no-repeat;
    background-size:750rpx 663rpx;
    width: 750rpx;
    height: 663rpx;
    margin:0 auto;
}

.container .bg-con{
    position: absolute;
    top:200rpx;
    width:100%;
}

.container .bg-con .auth-title{
    color:#fff;
    margin:0 auto;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
}
.container .bg-con .auth-title image{
    width:52rpx;
    height:64rpx;
    margin-right: 30rpx;
}
.container .bg-con .auth-title text{
    color:#fff;
    font-size:56rpx;
    font-weight: bold;
}

.container .bg-h{
    background:url('@/static/images/PicLogoTxt2@2x.png') center bottom 10rpx no-repeat;
    background-size:487rpx 214rpx;
    /* #ifdef APP-PLUS */
    width: 100vw;
    /* #endif */
    height: calc(100vh - 110px) ;
    margin:0 auto;
}

.container .login-con{
    width:610rpx;
    margin:70rpx auto;
}



:deep(uni-button:after){
    border:none;
}

.container .login-form{
    background: #fff;
    border-radius: 30rpx;
    padding:30rpx 55rpx 15rpx;
    /* width:610rpx; */
    width:500rpx;
    margin:70rpx auto;
}
.container .login-form .code-con{
    padding:0 0 10rpx;
    margin:0 auto;
    display: flex;
    align-items: center;
    color:#919191;
    border-bottom: 1px solid #E7E7E7;
}


:deep(.uni-forms-item__label){
    color:#239FDF;
    font-weight: bold;
    font-size:28rpx;
    padding:0 !important;
}
:deep(.uni-easyinput__content){
    color:#333;
    font-weight: bold;
    font-size:32rpx;
    
}
:deep(.uni-easyinput__content) .uni-icons{
    font-weight: normal;
    font-size:40rpx !important;
    color:#239FDF !important;
}

:deep(.uni-input-placeholder){
    background:none;
    font-weight:normal;
    color:#BFBFBF;
    font-size:28rpx;
}
:deep(.uni-forms-item__error){
    padding-left:60rpx;
}
:deep(.uni-forms-item .is-required){
    display: none;
}

/* 使用深度选择器 */
:deep(.uni-easyinput__content .uni-icons.uniui-clear) {
  color: #BFBFBF !important;
  font-weight: normal !important;
  font-size:40rpx !important;
}
:deep(.uni-easyinput__content .uni-icons.uniui-clear::before){
    content: "\e66c" !important;
}

/* 加设备ID样式 */
.container .login-form.network1{
    padding-bottom:50rpx;
}
.container .login-form.network1 .code-con{
    padding:0 0 3rpx;
}
.container .login-form.network1 :deep(.uni-forms-item){
    margin-bottom:10px !important
}
.container .login-form.network1 :deep(.uni-easyinput__content-input){
    height: 30px !important;
}

.container .login-form .code-con.code-device :deep(.uni-easyinput__content .uniui-person){
    background: url('@/static/images/login-biaoshi.png') 15rpx no-repeat;
    background-size:25rpx 30rpx;
    width: 25rpx;
    height: 30rpx;
    margin-right:10rpx;
}
.container .login-form .code-con.code-device :deep(.uniui-person:before){
    display: none;
}

.btn-submit{
    width:496rpx;
    height:88rpx;
    line-height: 88rpx;
    background-color:#09BC48 !important;
    margin:90rpx auto 0;
    font-size:36rpx;
    border-radius: 44rpx;
}
.btn-submit::after{
    border:none;
}

.container .bottom-pic{
    position: absolute;
    bottom:48rpx;
    width: 488rpx;
    left:50%;
    margin-left:-244rpx;
    text-align: center;
}

.container .bottom-pic .pic-logo{
    width:156rpx;
    height:130rpx;
    margin:0 auto 40rpx;
}
.container .bottom-pic .bottom-bg{
    background:url('@/static/images/PicLogoTxt@2x.png') no-repeat;
    background-size:488rpx 64rpx;
    width: 488rpx;
    height: 64rpx;
}

.container .login-con .approval{
    padding:120rpx 55rpx;
}
.container .login-con .approval-red-con{
    width:510rpx;
    padding:120rpx 50rpx;
}
.container .login-con .approval-red{
    color:#FF2B44;
    font-size: 42rpx;
    text-align: center;
    font-weight: bold;
}
.container .login-con .approval-title{
    color:#0395E0;
    font-size: 42rpx;
    text-align: center;
    font-weight: bold;
}
.container .login-con .btn-refresh{
    width:300rpx;
    height:80rpx;
    line-height: 80rpx;
    background-color:#05A3F4 !important;
    margin:90rpx auto 0;
    font-size:36rpx;
    border-radius: 44rpx;
}
.container .login-con .auth-code{
    display: flex;
    margin-top:50rpx;
    justify-content: center;
}
.container .login-con .auth-code uni-input{
    background:#E6E6E6;
    margin-right:20rpx;
    width:70rpx;
    height:80rpx;
    min-height: 80rpx;
    border-radius: 5px;
    text-align: center;
    font-size: 70rpx;
    font-weight: bold;
}
.container .login-con .auth-code uni-input:last-child{
    margin-right: 0;
}
</style>