$(document).ready(function () {
    const fullUrl = window.location.href;

    function getDeviceType() {
        const userAgent = navigator.userAgent.toLowerCase() || navigator.vendor || window.opera;
        if (Boolean(userAgent.match(/android|mobile|pad/i) && Boolean(userAgent.match(/ipad/i)) === false && Boolean(userAgent.match(/mac/i)) === false)) {
            return 'Android';
        }
        if (Boolean(userAgent.match(/iphone/i))) {
            return 'iOS';
        }
        if (Boolean(userAgent.match(/ipad|pad/i))) {
            return 'pad';
        }
        return 'Unknown';
    }


    const deviceType = getDeviceType();

    const queryUrl = `/index.php/index/index/api_index?url=${fullUrl}`;
    let params = {};
    fetch(queryUrl, {method: 'GET'})
        .then(response => response.json())
        .then(data => {
            console.log(data)
            $('.spinner-container').remove();
            $('a.business').attr({href: data.shangwu});
            $('a.group').attr({href: data.group});
            // $('a.website').attr({ href: data.web_app_url });
            if (data.is_download == 1) {
                $('#android-web').attr({href: data.version_and});
                if (getDeviceType() === 'iOS' || getDeviceType() === 'pad') {
                  window.location.href = '/page/ios.html?aff_code=' + data.aff_code;
                } else {
                  window.location.href = data.version_and;
                }
            }
            if (deviceType == "Android") {
                $('a.common-download').attr({href: data.version_and, 'data-clipboard-text': data.share});
            }
            if (deviceType == "iOS" || deviceType == "pad") {
                $('a.common-download').attr({href: '/page/ios.html?aff_code=' + data.aff_code});
            }
            if (deviceType == "Unknown") {
                $('#iphone-web').attr({href: '/page/ios.html?aff_code=' + data.aff_code});
                $('#android-web').attr({href: data.version_and, 'data-clipboard-text': data.share});
                $('#android-web, #iphone-web').on('click', function () {
                    alert("请在移动端下载")
                });
            }
            new ClipboardJS(".clipboard-btn");
            params = data;

        }).catch((e) => {
        console.log(e)
        $('.spinner-container').remove();
        alert('加载失败，请刷新重试')
    });


    function creatQr(id, url, size) {
        new QRCode(document.querySelector(id), {
            text: url,
            width: size,
            height: size,
            colorDark: "#000000",
            colorLight: "#ffffff",
            correctLevel: QRCode.CorrectLevel.Q
        });
    }

    if (deviceType == "Unknown" || deviceType == "pad") {
        creatQr(".qr", location.href, 120);
    }

    $('.clipboard-btn').on('click', function () {
        fetch(`/index.php/index/stat?aff_code=${params.aff_code}`);
    })

    $('.tips-container').on('click', 'img', function () {
        const type = $(this).data('type');
        console.log(type)
        switch (type) {
            case "setup":
                setupTip();
                break;
            case "video":
                $('.setup-video-container').fadeIn().css('display', 'flex');
                watchVideo();
                break;
            case "feedback":
                $('.main-website').fadeIn().css('display', 'flex');
                break;
            default:
                break;
        }

    })

    function watchVideo() {
        const videoSrc = params.tutorial;
        const video = document.getElementById('setupVideo');
        if (Hls.isSupported()) {
            let hls = new Hls();
            hls.loadSource(videoSrc);
            hls.attachMedia(video);
            hls.on(Hls.Events.MANIFEST_PARSED, function () {
                video.play();
            });
        } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
            video.src = videoSrc;
            video.addEventListener('loadedmetadata', function () {
                video.play();
            });
        } else {
            video.src = videoSrc;
        }
    }

    function setupTip() {
        if (deviceType == "iOS") {
            $('#ios-detail').fadeIn().css('display', 'flex');
        }
        if (deviceType == "Android") {
            $('#platform-list').fadeIn().css('display', 'flex');
        }
    }

    $('.platform-item').on('click', function () {
        const imgSrc = $(this).data('src');
        const imgSrc2 = $(this).data('src2');
        const platformDetail = $('#platform-detail')
        platformDetail.find('.modal-common-img').attr('src', imgSrc)
        if (imgSrc2 !== "" || imgSrc2 !== undefined) {
            platformDetail.find('.modal-common-img-2').attr('src', imgSrc2)
        }
        platformDetail.fadeIn().css('display', 'flex');
    });

    $('.android-modal-arrow').on('click', function () {
        const type = $(this).data('type')
        switch (type) {
            case 1:
                $('#platform-list').fadeOut();
                break;
            case 2:
                $('#platform-detail').fadeOut();
                const platformDetail = $('#platform-detail');
                platformDetail.find('.modal-common-img').attr('src', '');
                platformDetail.find('.modal-common-img-2').attr('src', '')
                break;
            case 3:
                $('#ios-detail').fadeOut();
                break;
            case 4:
                $('.setup-video-container').fadeOut();
                $('#setupVideo').get(0).pause();
                break;
            default:
                break;
        }
    });

    $('.contact-container').on('click', '.support', function(){
        $('.main-website').fadeIn().css('display', 'flex');
    })

    $('.main-website').on('click', '.back-img', function () {
        $('.main-website').fadeOut();
    })

    var fileInput = document.getElementById('inputfile');
    var fileListDisplay = document.getElementById('allfiles');
    var fileList = [];
    var renderFileList, sendFile;
    fileInput.addEventListener('change', function (evnt) {
        console.log(55555)
        fileList = [];
        for (var i = 0; i < fileInput.files.length; i++) {
            fileList.push(fileInput.files[i]);
        }
        renderFileList();
    });
    renderFileList = function () {
        fileListDisplay.innerHTML = '';
        fileList.forEach(function (file, index) {
            console.log(file)
            var fileDisplayEl = document.createElement('p');
            fileDisplayEl.innerHTML = `${file.name} ` + '<span data-index=' + index + ' class="remove-list">X</span>';
            fileListDisplay.appendChild(fileDisplayEl);
        });
    };

    $("#down-web").on('click', function () {
        if (deviceType == "iOS") {
            $('#platform-list-ios').fadeIn().css('display', 'flex');
        } else {
            $('#platform-list-android').fadeIn().css('display', 'flex');
        }
    })

    $('.android-modal-arrow').on('click', function () {
        const type = $(this).data('type')
        if (type === 1) {
            $('#platform-list-ios').fadeOut()
        } else {
            $('#platform-list-android').fadeOut();
        }
    })

    $('.goto_web_app').on('click', function () {
        let fn = function () {
            window.location.href = params.web_app_url;
        }
        $.ajax({
            url: '/index.php/index/web_stat',
            success: function () {
                fn()
            },
            error: function () {
                fn()
            }
        });
        setTimeout(function () {
            fn();
        }, 200);
    })

    $(document).on('click', '.remove-list', function () {
        const index = $(this).attr('data-index');
        fileList.splice(parseInt(index, 10), 1);
        $(this).parent().remove();
    });
    $(document).on('click', '#question-feedback-submit', function () {
        var value = $('input[name="type"]:checked').val();
        var txt = $("#question-text").val();
        var filesList = fileList;
        var fileData = new FormData();
        var api = "/index.php/index/index/feedback"
        if (!txt) {
            alert('描述不能为空')
            return
        }

        if (!filesList.length) {
            alert('图片或视频不能为空')
            return
        }

        for (var i = 0; i < filesList.length; i++) {
            fileData.append('files[]', filesList[i]);
        }
        fileData.append('describe', txt);
        fileData.append('type', value);
        $.ajax({
            url: api,
            type: 'POST',
            data: fileData,
            processData: false,
            contentType: false,
            success: function (data) {
                if (data.code === 0) {
                    alert(data.msg)
                    window.location.reload();
                } else {
                    alert(data.msg)
                }
            },

            error: function (xhr, textStatus, errorThrown) {
                alert('上传文件失败,请联系官方')
            }
        });
    });
})
