/**
 * FIXME 环境配置
 *
 * baseUrl
 * - 线上环境："https://epp.only4.work/"
 * - 开发环境："/"
 * envVersion
 * - 线上环境："release"
 * - 开发环境："develop"
 */
// 定义常量
const baseUrl = "/"
const url = baseUrl + "access/wechat/getUnlimitedQRCode"
const page = "pages/index/index" // "pages/scan/entrance"
const envVersion = "release" // 正式版为 "release"，体验版为 "trial"，开发版为 "develop"
const autoColor = true
const isHyaline = false
const width = 500

// 页面上的元素
const image = document.getElementById('qrcode')
const noQrInfo = document.getElementById('no-qrcode')
const refreshTimeCountDown = document.getElementById('refreshTimeCountDown')
const DOMGateList = document.getElementById('gate-list')

// 大门列表
window.gateList = []

// 当前大门
window.currentGate = null

// 获取 Url 参数
function getUrlParams() {
    let params = {}
    location.search.substring(1).split("&").map(param => {
        let a = param.indexOf("=")
        if (a < 0)
            params[param] = ''
        else
            params[param.substring(0, a)] = decodeURIComponent(param.substring(a + 1))
    })
    // console.log(params)
    return params
}

// 获取 url 参数
let urlParams = getUrlParams()
console.log("urlParams", urlParams)

// 是否在 electron 中
const inElectron = urlParams['inElectron']

// 点击全屏
document.getElementById("fullscreen-button").addEventListener("click", function () {
    if (document.fullscreenElement) {
        document.exitFullscreen();
    } else {
        if (inElectron) {
            // electron 中
            const message = JSON.stringify({
                action: 'fullscreen'
            });
            window.parent.postMessage(message, '*');
        } else {
            // 浏览器中
            document.body.requestFullscreen()
        }
    }
})

// 定时更新页面上的小程序码
let i = 0, refreshTime = 10 + 1

function updateQRCode() {
    // 取消图片隐藏
    image.style.visibility = '';
    image.style.display = '';
    noQrInfo.style.display = 'none';

    if (i % refreshTime == 0) {
        // scene 最长支支持 32 位，所以这里不传入时间戳
        let scene = encodeURIComponent(`guard;${window.currentGate.id}`); // &${Date.now()}
        image.src = `${url}?page=${page}&scene=${scene}&envVersion=${envVersion}&width=${width}&autoColor=${autoColor}&isHyaline=${isHyaline}`
        console.log(image.src)
        refreshTimeCountDown.innerHTML = `&nbsp;`
    } else {
        refreshTimeCountDown.textContent = `${refreshTime - i}秒后刷新`
    }
    i = i % refreshTime + 1
}

// 挂载到 window 上
window.updateQRCode = updateQRCode

// 弹窗中修改 item
function changePanelSelectGate(gateId) {
    // 删除旧的 active
    let activeList = document.querySelectorAll('.gate-list-item.active')
    for (let a of activeList) {
        a.classList.remove('active')
    }

    // 添加新的 active
    let newActiveItem = document.getElementById(`gate-list-${gateId}`)
    if (newActiveItem) {
        newActiveItem.classList.add('active')
        window.selectGateId = gateId
    }
}

// 挂载到 window 上
window.changePanelSelectGate = changePanelSelectGate

// 发送请求，获取大门列表
async function getGateList() {
    const response = await fetch(baseUrl + 'access/gate/guard-client/getGateList');
    const data = await response.json();
    return data.data;
}

window.onload = async function () {

    // 当前的门禁端
    let gateId = urlParams['gateId'] || ""

    // 获取大门列表
    window.gateList = await getGateList()
    console.log("gateList", window.gateList)

    let domList = []
    for (let gate of window.gateList) {
        domList.push(`
            <div id="gate-list-${gate.id}" class="gate-list-item" onclick="window.changePanelSelectGate('${gate.id}')">
                <p>${gate.name}</p>
                <p class="status ${gate.open ? 'open' : 'closed'}">
                    ${gate.open ? '开放' : '封闭'}
                </p>
            </div>
        `)
    }
    DOMGateList.innerHTML = domList.join('')

    // 通过id 找门禁
    window.currentGate = gateList.find((gate) => gate.id === gateId)

    if (!window.currentGate) {
        // 弹出选择框
        window.showSettingPanel && window.showSettingPanel()
    } else {
        // 显示大门名称及状态
        document.querySelector('#gate-name').innerHTML = `
        <span>${window.currentGate.name}</span>
        <span style="font-weight: bold; color: ${window.currentGate.open ? '#40f940' : 'red'};">${window.currentGate.open ? '允许通行' : '禁止通行'}</span>`

        // 开始更新图片
        updateQRCode()
        setInterval(updateQRCode, 1000)
    }
}



