<template>
    <div class="box" v-if="!isScanning">
        <div class="box-zx">
            <!-- 顶部 -->
            <div :style="isMobile ? 'width: 100%; ' : 'width: 100%; background: #ffffff'">
                <!-- <div style="height: 64px" v-if="isMobile"></div> -->
                <div class="top-box" @click.stop>
                    <div
                        :style="
                            isMobile
                                ? 'display: flex; align-items: center; width: 260px; font-size: 18px; color: #1f1f1f'
                                : 'display: flex; align-items: center; width: 460px; font-size: 18px; color: #1f1f1f'
                        "
                    >
                        {{ languageObj.title }}
                    </div>
                    <el-dropdown trigger="click" class="dropdown-box" @click.stop>
                        <span class="el-dropdown-link">
                            {{ dropdown }}<el-icon class="el-icon--right"><arrow-down /></el-icon>
                        </span>

                        <template #dropdown>
                            <el-dropdown-menu @click.stop>
                                <el-dropdown-item @click.stop="handleCommand(1)">China-中文简体</el-dropdown-item>
                                <el-dropdown-item @click.stop="handleCommand(2)">USA-English</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
            </div>

            <div class="container-box">
                <div class="container">
                    <div class="center" :style="isMobile ? 'min-width:311px;max-width:434px' : ''">
                        <el-form
                            ref="ruleFormRef"
                            :model="ruleForm"
                            :rules="rules"
                            label-width="auto"
                            class="demo-ruleForm"
                            @submit.prevent
                        >
                            <!-- PC端 -->
                            <el-form-item
                                prop="code"
                                v-if="!isMobile"
                                style="position: relative; display: flex; font-weight: 900"
                            >
                                <div class="left" v-if="!isMobile">
                                    <img src="@/assets/images/yz.png" class="img-left" width="120" height="93.6" />
                                </div>
                                <span style="margin-right: 18px; font-size: 18px">{{ languageObj.label }}</span>
                                <el-input
                                    v-model="ruleForm.code"
                                    @keyup.enter="submitForm(ruleFormRef)"
                                    style="width: 338px; height: 124px"
                                    ref="pcInput"
                                    maxlength="30"
                                    class="borderless"
                                    clearable
                                    suffix-icon="el-icon-circle-close"
                                    :placeholder="languageObj.placeholder"
                                >
                                    <template #suffix
                                        ><img src="@/assets/images/syspc.png" class="img-left" width="40" height="40"
                                    /></template>
                                </el-input>
                            </el-form-item>
                            <div class="ts" v-if="!isMobile" :style="resultMsgStatus === 3 ? ' color:red ' : 'color:#1F1F1F'">
                                <el-icon v-if="resultMsgStatus === 3"><Warning /></el-icon>
                                <span>{{ languageObj.ts }}</span>
                            </div>
                            <!-- PC端 -->
                            <div
                                :style="
                                    languageType === 1
                                        ? 'display: flex; justify-content: center; width: 338px; margin-left: 252px'
                                        : 'display: flex; justify-content: center; width: 338px; margin-left: 303px'
                                "
                                v-if="!isMobile"
                            >
                                <el-button
                                    type="primary"
                                    @click="submitForm(ruleFormRef)"
                                    @keyup.enter="submitForm(ruleFormRef)"
                                    style="
                                        width: 144px;
                                        height: 44px;
                                        font-size: 16px;
                                        background: linear-gradient(90deg, #008eff 0%, #002fff 100%);
                                    "
                                >
                                    {{ languageObj.btnConfirmName }}
                                </el-button>
                                <!-- style="width: 144px; height: 44px" -->
                                <el-button @click="resetForm(ruleFormRef)" style="width: 144px; height: 44px; font-size: 16px">{{
                                    languageObj.btnClearName
                                }}</el-button>
                            </div>
                            <!-- 移动端 -->
                            <el-form-item prop="code" v-if="isMobile">
                                <div class="mobile-label">
                                    {{ languageObj.label }}
                                </div>
                                <div style="display: flex; width: 100%" @click.stop>
                                    <el-input
                                        maxlength="30"
                                        v-model="ruleForm.code"
                                        ref="h5Input"
                                        style="height: 104px"
                                        :placeholder="languageObj.placeholder"
                                        clearable
                                        suffix-icon="el-icon-circle-close"
                                        @click.stop
                                    >
                                        <template #suffix>
                                            <div @click.stop style="width: 40px; height: 40px">
                                                <!-- prevent -->
                                                <img
                                                    @click.stop="getCameras"
                                                    src="@/assets/images/syspc.png"
                                                    class="img-left"
                                                    width="40"
                                                    height="40"
                                                />
                                            </div>
                                        </template>
                                    </el-input>
                                </div>
                            </el-form-item>
                            <div class="ts" v-if="isMobile" :style="resultMsgStatus === 3 ? ' color:red ' : 'color:#1F1F1F'">
                                <el-icon v-if="resultMsgStatus === 3"><Warning /></el-icon>
                                <span>{{ languageObj.ts }}</span>
                            </div>
                            <!-- 移动端 -->
                            <div v-if="isMobile" style="display: flex; justify-content: space-between">
                                <el-button
                                    type="primary"
                                    @click="submitForm(ruleFormRef)"
                                    @keyup.enter="submitForm(ruleFormRef)"
                                    style="
                                        width: 147px;
                                        height: 40px;
                                        font-size: 14px;
                                        background: linear-gradient(90deg, #008eff 0%, #002fff 100%);
                                        border-radius: 6px;
                                    "
                                >
                                    {{ languageObj.btnConfirmName }}
                                </el-button>
                                <el-button
                                    style="width: 147px; height: 40px; font-size: 14px; border-radius: 6px"
                                    @click="resetForm(ruleFormRef)"
                                    class="btn2"
                                    >{{ languageObj.btnClearName }}</el-button
                                >
                            </div>
                        </el-form>
                    </div>
                    <!-- :border-style="{ border: '1px dashed #E2E2E2' }"  -->
                    <el-divider v-if="isMobile" border-style="dashed" />
                    <div class="right">
                        <div :style="isMobile ? 'padding-bottom: 10px' : 'padding: 20px 0'">
                            <div>
                                <div class="introduceTitle">
                                    {{ languageObj.introduceTitle }}
                                </div>
                                <!-- <div
                                    v-if="languageType === 2"
                                    :style="
                                        isMobile
                                            ? 'margin-bottom: 5px; font-size: 12px; color: #5b5d60;padding-bottom:8px;'
                                            : 'margin-bottom: 5px; font-size: 16px; color: #5b5d60;padding-bottom:5px;'
                                    "
                                >
                                    The first method:
                                </div> -->
                                <div class="introduceContent">
                                    {{ languageObj.introduceContent }}
                                </div>
                            </div>
                            <div class="introduceImg">
                                <img src="@/assets/images/code.png" class="introduceImg-code" />
                            </div>
                        </div>
                        <!-- <div>
                            <div
                                v-if="languageType === 2"
                                :style="
                                    isMobile
                                        ? 'margin-bottom: 5px; font-size: 12px; color: #5b5d60;'
                                        : 'margin-bottom: 5px; font-size: 16px; color: #5b5d60;padding-bottom:5px;'
                                "
                            >
                                The second method:
                            </div>
                            <div class="yp">{{ languageObj.introduceTitle1 }}</div>
                            <img src="@/assets/images/yp.png" class="yp-img" />
                        </div> -->
                    </div>
                </div>
            </div>
            <div style="height: 70px" v-if="isMobile"></div>
            <!-- 底部 -->
            <div class="footer">
                <div class="footer-content">
                    <div style="width: 20px; height: 1px; margin-right: 10px; background: #d2dceb" v-if="isMobile"></div>

                    Copyright © {{ languageObj.gs }}(<a href="https://beian.miit.gov.cn" style="color: #96989b"
                        >粤ICP备15025109号-24</a
                    >)
                    <div style="width: 20px; height: 1px; margin-left: 10px; background: #d2dceb" v-if="isMobile"></div>
                </div>
            </div>
        </div>
    </div>
    <div v-show="isScanning">
        <div class="container11">
            <div style="position: absolute; top: 20px; left: 10px; z-index: 999">
                <img src="@/assets/images/go.png" width="40" height="40" @click="handleGo" />
            </div>
            <div id="reader"></div>
        </div>
    </div>
</template>

<script setup lang="ts" name="index">
import { getSecurityApi } from "@/api/modules/home";
import { reactive, ref, nextTick } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { useRoute } from "vue-router";
import { deviceDetection } from "./init";
import { zh, en } from "./language/index";
import { Html5Qrcode } from "html5-qrcode";
import { useLanguage } from "@/stores/modules/language";
import { cloneDeep } from "lodash-es";
const languageStore = useLanguage();
const $route = useRoute();
console.log($route.query.type, "=================type================");
let value = $route.query.type ? Number(Number($route.query.type)) : 1;
console.log(value, "==============value====================");
interface RuleForm {
    code: string;
}
// 表单ref对象
const ruleFormRef: any = ref<FormInstance>();
// const route = useRoute();
const isClick = ref(false);
// 语言类型 1=中文 2=英文
const languageType = ref(value);
console.log(languageType, "=languageType=");
// 表单数据
const ruleForm = reactive<RuleForm>({
    code: ""
});
const pcInput: any = ref(null);
const h5Input: any = ref(null);

// 设备区分 移动=true,pc=false
const isMobile = ref(false);
const isScanning = ref(false);
// const dateTime: any = ref<{ year: string; month: string; day: string; hour: string; minute: string; second: string } | null>(
//     null
// );
const languageDropdown: any = {
    1: "China-中文简体",
    2: "USA-English"
};

const queryTime: any = ref(null);
const resultMsgStatus = ref(0);
const dropdown: any = ref(languageDropdown[value]); //
let html5QrcodeScanner: any = null;

// 表单验证(只显示红色的框)
const rules = reactive<FormRules<RuleForm>>({
    code: [{ required: true, message: "", trigger: "blur" }]
});

// const splitDateTime: any = (dateTimeString: any) => {
//     const [datePart, timePart] = dateTimeString.split(" ");
//     const [year, month, day] = datePart.split("-");
//     const [hour, minute, second] = timePart.split(":");

//     dateTime.value = {
//         year,
//         month,
//         day,
//         hour,
//         minute,
//         second
//     };
// };

const inputFocus = () => {
    isMobile.value ? h5Input.value.focus() : pcInput.value.focus();
};
const stop = () => {
    html5QrcodeScanner
        .stop()
        .then((ignore: any) => {
            // QR Code scanning is stopped.
            console.log(`QR Code scanning stopped.${ignore}`);
        })
        .catch((err: any) => {
            // Stop failed, handle it.
            console.log(`Unable to stop scanning.${err}`);
        });
    isScanning.value = false;
};
//关闭扫码接口
const handleGo = () => {
    isScanning.value = false;
};
// 查询接口
const getSecurity = async (params: any) => {
    if (isClick.value) {
        return;
    }

    isClick.value = true;
    let paramsClone = cloneDeep(params);
    ruleForm.code = cloneDeep(paramsClone);

    const result = await getSecurityApi(params);
    paramsClone = null;
    if (result.status === 200) {
        const { data } = result;
        setTimeout(() => {
            isClick.value = false;
        }, 1000);
        // 没有查询到
        if (!data.security) {
            resultMsgStatus.value = 3;
        }
        // 第一次查询
        if (data.isOneQuery) {
            resultMsgStatus.value = 1;
        }
        // 不是第一次查询
        if (!data.isOneQuery && data.queryCount > 1) {
            resultMsgStatus.value = 2;
            queryTime.value = data.queryTime;
            //   splitDateTime(data.queryTime);
        }
        if (html5QrcodeScanner) {
            stop();
        }
    } else {
        isClick.value = false;
    }
};
// 表单提交
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) {
        return;
    }
    await formEl.validate((valid, fields) => {
        if (valid) {
            getSecurity(ruleForm.code);
        } else {
            inputFocus();
            console.log("error submit!", fields);
            isClick.value = false;
        }
    });
};
// 表单重置
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
    resultMsgStatus.value = 0;
    ruleForm.code = "";
    isClick.value = false;
    setTimeout(() => {
        inputFocus();
    }, 300);
};
// 语言选择 type为1=中文,2=英文
const handleCommand = (type: any) => {
    languageType.value = type;
    dropdown.value = type === 1 ? "China-中文简体" : "USA-English";
    if (ruleForm.code) {
        setTimeout(() => {
            inputFocus();
        }, 300);
        return;
    }
    resetForm(ruleFormRef.value);
    setTimeout(() => {
        inputFocus();
    }, 300);
};

const start = () => {
    isScanning.value = true;
    html5QrcodeScanner = new Html5Qrcode("reader");
    html5QrcodeScanner
        .start(
            // environment后置摄像头 user前置摄像头
            { facingMode: "environment" },
            {
                fps: 20, // 可选，每秒帧扫描二维码
                qrbox: { width: 250, height: 250 }
            },
            // /decodedResult: any
            (decodedText: any) => {
                // do something when code is read
                getSecurity(decodedText);
                inputFocus();
            }
        )
        .catch((err: any) => {
            // 错误信息处理仅供参考，具体情况看输出！！！
            if (typeof err == "string") {
                // this.$toast(err)
            } else {
                // if (err.name == 'NotAllowedError') return this.$toast("您需要授予相机访问权限")
                // if (err.name == 'NotFoundError') return this.$toast('这个设备上没有摄像头')
                // if (err.name == 'NotSupportedError') return this.$toast('摄像头访问只支持在安全的上下文中，如https或localhost')
                // if (err.name == 'NotReadableError') return this.$toast('相机被占用')
                // if (err.name == 'OverconstrainedError') return this.$toast('安装摄像头不合适')
                // if (err.name == 'StreamApiNotSupportedError') return this.$toast('此浏览器不支持流API')
            }
        });
};
const getCameras = () => {
    Html5Qrcode.getCameras()
        .then((devices: any) => {
            if (devices && devices.length) {
                start();
            }
        })
        .catch((err: any) => {
            console.log(err, "=========err===========");
            isScanning.value = false;
            html5QrcodeScanner = new Html5Qrcode("reader");
        });
};

// 设备检测
onMounted(() => {
    isMobile.value = deviceDetection();
    nextTick(() => {
        inputFocus();
    });
});
onUnmounted(() => {
    stop();
});
//ts切换
//语言切换
let languageObj = computed(() => {
    let language = {
        title: "",
        label: "",
        btnConfirmName: "",
        btnClearName: "",
        introduceTitle: "",
        introduceContent: "",
        introduceContent1: "",
        introduceTitle1: "",
        ts: "",
        placeholder: "",
        gs: ""
    };
    languageStore.setLanguageType(languageType.value);
    language.title = languageType.value == 1 ? zh.title : en.title;

    language.btnConfirmName = languageType.value == 1 ? zh.b1 : en.b1;
    language.btnClearName = languageType.value == 1 ? zh.b2 : en.b2;
    language.introduceTitle = languageType.value == 1 ? zh.yd1 : en.yd1;
    language.introduceContent = languageType.value == 1 ? zh.yd2 : en.yd2;
    language.introduceTitle1 = languageType.value == 1 ? zh.yd3 : en.yd3;
    language.gs = languageType.value == 1 ? zh.gs : en.gs;
    // 手机端(PC端和移动的label是不一样的);
    if (isMobile.value) {
        language.label = languageType.value == 1 ? zh.label1 : en.label1;
        language.placeholder = languageType.value == 1 ? zh.placeholder1 : en.placeholder;
    } else {
        //pc端
        language.label = languageType.value == 1 ? zh.label : en.label;
        language.placeholder = languageType.value == 1 ? zh.placeholder : en.placeholder;
    }

    if (languageType.value == 1) {
        if (!resultMsgStatus.value) {
            language.ts = "";
        }
        if (resultMsgStatus.value === 3) {
            language.ts = zh.ts3;
        }
        if (resultMsgStatus.value === 2) {
            language.ts = `尊敬的用户您好：您所查询的防伪码已于“${queryTime.value}”被查询过。如有疑问可联系客服，谢谢。`;
        }
        if (resultMsgStatus.value === 1) {
            language.ts = zh.ts1;
        }
    } else {
        if (!resultMsgStatus.value) {
            language.ts = "";
        }
        if (resultMsgStatus.value === 3) {
            language.ts = en.ts3;
        }
        if (resultMsgStatus.value === 2) {
            language.ts = `Dear user, the anti-counterfeiting code you inquired about has been checked on “${queryTime.value}”. If you have any questions, please contact customer service. Thank you.`;
        }
        if (resultMsgStatus.value === 1) {
            language.ts = en.ts1;
        }
    }
    return language;
});
</script>

<style lang="scss" scoped>
@import "./index.scss";
.container11 {
    position: relative;
    top: 0;
    left: 0;
    z-index: 999;
    box-sizing: border-box;
    box-sizing: border;
    width: 100vw;
    height: 100vh;
    overflow: hidden;
    background: rgba($color: #000000, $alpha: 48%);
}
#reader {
    top: 50%;
    left: 0;
    transform: translateY(-50%);
}
:deep(.el-input-group__append) {
    background: #ffffff !important;
}

/* 去掉小星星 */
:deep(.el-form-item__label::before) {
    // margin-right: 4px;
    // color: var(--el-color-danger);
    content: "" !important;
}
:deep(.el-form-item--default .el-form-item__label) {
    font-size: 18px;
}
:deep(.el-form-item__label-wrap) {
    display: flex;
    align-items: center;
}
</style>
