import axios from 'axios';
// 初始化变量
    var session = null;
    var thumbnailSDKMap = new Map();
    var thumbnail_index = 0;
    var mEnableGroupControl = false;
    var regionId = 'cn-shanghai';
    var mResolutionHeight = 0;
    var mResolutionWidth = 0;
    var mDisableOrientation = false;//禁止云侧横竖屏自适应，使用端侧本地旋转
    //缩略图
    class WYThumbnailImg {
        #tryNum = 0;
        thumbnail = null;
        params = null;
        callback = null;
        tryMaxNum = 3;
        url = null;
        #thumbnailDataTimeout = null;

        constructor(params, callback) {
            this.params = params;
            this.callback = callback;
            this.createThumbnail();
        }

        stopThumbnail() {
            try {
                if (this.thumbnail) {
                    console.log(`Thumbnail ${params.appInstanceId}  stop`);
                    this.thumbnail.session.stop();
                    this.thumbnail = null;
                }
            } catch (error) {
            }
        }

        createThumbnail() {
            const { params } = this;
            try {
                this.stopThumbnail();

                this.thumbnail = new window.Wuying.ThumbnailSDK(
                {
                    appInstanceId: params.appInstanceId,
                    ticket: params.ticket,
                    containerId: "",
                    defaultConfig: {
                        width: params.width,
                        height: params.height,
                        fps: params.fps,
                    },
                    connectionConfig: {
                        useCustomIme: true,
                    },
                    lyncChannelConfig: [
                    {
                        lyncChannelName: "lync_adb_shell",
                        callback: (eventName, data) => {
                            console.log(`Thumbnail lync ${params.appInstanceId} eventName:${eventName}, data:`, data);
                        },
                    },
                    ],
                },
                {
                    onConnected: (data) => {
                        console.log(`Thumbnail ${params.appInstanceId}  connected`, data);
                        this.#tryNum = 0;
                        this.thumbnail.session.getLocalConfig().setClipboardEnabled(true);
                    },
                    onDisConnected: (data) => {
                        console.log(`Thumbnail ${params.appInstanceId}  disconnected`, data);
                        if (data == 2000 || data == 2002 || data == 1204 || data == 2240  || data == 2507 || data == 2506) {
                            this.#tryNum = this.tryMaxNum;
                            return;
                        }

                        if (this.#tryNum < this.tryMaxNum) {
                            this.#tryNum += 1;
                            setTimeout(() => this.createThumbnail(), 1000); // 防止快速递归调用
                        } else if (this.callback) {
                            this.callback(params, null, data); // 失败回调
                        }
                    },
                    onThumbnailData: (url) => {
                        url = url;
                        if (this.callback) this.callback(params, url, 0);
                    },
                }
                );
            } catch (error) {
                console.error(`Thumbnail Failed to ${params.appInstanceId} initialize SDK for:`, error);
                if (this.#tryNum < this.tryMaxNum) {
                    this.#tryNum += 1;
                    setTimeout(() => this.createThumbnail(), 1000); // 失败重试
                } else if (this.callback) {
                    this.callback(params, null, -2); // 最终失败回调
                }
            }
        }

        setCallback(callback) {
            this.callback = callback;
            if (this.callback && url) {
                this.callback(params, url, 0);
            }
        }

        canReuse() {
            return this.#tryNum < this.tryMaxNum;
        }
    }

    class ResolutionUtils {
        static TOL = 20;
        static RES_720P  = 1;
        static RES_1080P = 2;
        static RES_2K    = 3;

        static getResType(w, h) {
            const min = Math.min(w, h);
            const max = Math.max(w, h);

            if (Math.abs(min - 720) <= this.TOL && Math.abs(max - 1280) <= this.TOL) {
                return this.RES_720P;
            }
            if (Math.abs(min - 1440) <= this.TOL && Math.abs(max - 2560) <= this.TOL) {
                return this.RES_2K;
            }
            return this.RES_1080P; // default
        }

        // 码率表: [720p, 1080p, 2K] × [LOW, NORMAL, HIGH, SUPER]
        static BITRATES = [
            [ 1_200_000,  2_500_000,  4_000_000,  6_000_000 ], // 720p
            [ 2_800_000,  5_500_000,  8_000_000, 12_000_000 ], // 1080p
            [ 5_000_000, 10_000_000, 15_000_000, 25_000_000 ]  // 2K
        ];

        static getBps(quality, width, height) {
            let resIndex;
            const resType = this.getResType(width, height);
            switch (resType) {
                case this.RES_720P:
                    resIndex = 0;
                    break;
                case this.RES_2K:
                    resIndex = 2;
                    break;
                default: // RES_1080P
                    resIndex = 1;
            }
            let qIndex = 1;
            if (quality === 'low') {
                qIndex = 0;
            } else if (quality === 'normal') {
                qIndex = 1;
            } else if (quality === 'high') {
                qIndex = 2;
            } else if (quality === 'super') {
                qIndex = 3;
            }
            return this.BITRATES[resIndex][qIndex];
        }
    }

    function requestThumbnail(params, callback) {
        if (!params.appInstanceId) {
            console.log(`Thumbnail params appInstanceId is null`);
            if (callback) callback(params, null, -1);
            return;
        }
        if (thumbnailSDKMap.has(params.appInstanceId)) {
            console.log(`Thumbnail ${params.appInstanceId}  reuse`);
            var item = thumbnailSDKMap.get(params.appInstanceId);
            if (item.canReuse()) {
                item.callback = callback;
                return;
            } else {
                item.stopThumbnail();
                thumbnailSDKMap.delete(params.appInstanceId);
            }
        }
        console.log(`Thumbnail ${params.appInstanceId}  new`);
        var item = new WYThumbnailImg(params, callback);
        thumbnailSDKMap.set(params.appInstanceId, item);
    }

    function sendThumbnailClipboardDataToRemote(appInstanceId, msg) {
        if (!appInstanceId) {
            console.log(`Thumbnail send cb data appInstanceId is null`);
            return;
        }
        if (thumbnailSDKMap.has(params.appInstanceId)) {
            console.log(`Thumbnail send cb data ${params.id} ${params.appInstanceId}  reuse`);
            var item = thumbnailSDKMap.get(params.appInstanceId);
            item.thumbnail.session.getClipboardModule().sendClipboardDataToRemote(msg);
        } 
    }

    const OperationMap = {
        'Back': 'input keyevent KEYCODE_BACK',
        'Home': 'input keyevent KEYCODE_HOME',
        'AppSwitch': 'input keyevent KEYCODE_APP_SWITCH',
        'Mute': 'input keyevent 164',
        'VolUp': 'input keyevent KEYCODE_VOLUME_UP',
        'VolDown': 'input keyevent KEYCODE_VOLUME_DOWN',
        'HideNav': 'setprop persist.wy.hasnavibar false; killall com.android.systemui',
        'ShowNav': 'setprop persist.wy.hasnavibar true; killall com.android.systemui',
    };
    // 云手机操作
    function handleCloudPhoneOperation(type) {
        console.log("handleCloudPhoneOperation ", type);
        if (session) {
            console.log("handleCloudPhoneOperation1 ", type);
            session.sendLyncMessage(
                'lync_adb_shell',
                JSON.stringify({
                id: Date.now(), // uuid
                cmd: OperationMap[type],
                }),
            );
        }
    }
    function sendMsgToCloudPhoneOperation(msg) {
        console.log("sendMsgToCloudPhoneOperation ", msg);
        if (session) {
            session.setClipboardModule('sendClipboardDataToRemote', msg) 
        }
        for (const [key, value] of thumbnailSDKMap) {
            console.log('thumbnial sendMsgToCloudPhoneOperation ', key, msg);
            value.thumbnail.session.getClipboardModule().sendClipboardDataToRemote(msg);
        }
    }
    function suspendThumbnailDisplay(appInstanceId) {
      if (!appInstanceId) {
          console.log(`Thumbnail suspendThumbnailDisplay appInstanceId is null`);
          return;
      }
      if (thumbnailSDKMap.has(appInstanceId)) {
          var item = thumbnailSDKMap.get(appInstanceId);
          if (item.canReuse()) {
            console.log(`Thumbnail ${appInstanceId}  suspendThumbnailDisplay`);
            item.thumbnail.session.suspendThumbnailDisplay();
            return;
          }
      }
    }

    function resumeThumbnailDisplay(appInstanceId, width, height, fps) {
      if (!appInstanceId) {
        console.log(`Thumbnail resumeThumbnailDisplay appInstanceId is null`);
        return;
      }
      if (thumbnailSDKMap.has(appInstanceId)) {
          console.log(`Thumbnail ${appInstanceId}  reuse`);
          var item = thumbnailSDKMap.get(appInstanceId);
          if (item.canReuse()) {
            console.log(`Thumbnail ${appInstanceId}  resumeThumbnailDisplay`);
            item.thumbnail.session.resumeThumbnailDisplay(width, height, fps);
            return;
          }
      }
    }

    // 工具函数
    function showNotification(message, type = 'info') {
      const notification = document.getElementById('notification');
      notification.textContent = message;
      notification.className = `notification ${type} show`;
      setTimeout(() => {
        notification.classList.remove('show');
      }, 3000);
    }

    function toggleElement(elementId, show) {
      const element = document.getElementById(elementId);
      if (element) {
        element.style.display = show ? 'block' : 'none';
      }
    }

    // 事件监听器
    document.addEventListener('DOMContentLoaded', function() {
        const useLogin = document.getElementById('use_login');
        const useInput = document.getElementById('use_input');
        const loginCard = document.getElementById('loginCard');
        const inputCard = document.getElementById('inputCard');
        useLogin.checked = true;
        loginCard.style.display = 'block';
        inputCard.style.display = 'none';
        useLogin.addEventListener('change', function () {
            if (this.checked) {
                useInput.checked = false; 
                loginCard.style.display = 'block';
                inputCard.style.display = 'none';
            } else {
                this.checked = true;
            }
        });
        useInput.addEventListener('change', function () {
            if (this.checked) {
                useLogin.checked = false;
                loginCard.style.display = 'none';
                inputCard.style.display = 'block';
            } else {
                this.checked = true;
            }
        });
      // 登录相关
      document.getElementById('login-button').addEventListener('click', onLogin);
      document.getElementById('logout-button').addEventListener('click', onLogout);
      
      // 手动参数切换
      const manualParameter = document.getElementById('manualParameter');
      manualParameter.checked = true;
      manualParameter.addEventListener('change', enableManualParameter);
      document.getElementById('useTicketConn').addEventListener('change', enabelUseTicketConn);
      document.getElementById('useOtherConn').addEventListener('change', enableUseOtherConn);
      document.getElementById("groupcontrol").addEventListener('change', enableGroupControl);
      enableManualParameter();

      // 缩略图按钮事件
      document.getElementById('thumbnailBtn').addEventListener('click', onAddThumbnail);

      // 连接操作
      document.getElementById('connect-button').addEventListener('click', () => onConnect('manual'));
      document.getElementById('clear-button').addEventListener('click', onClear);
      
      // 启动参数操作
      document.getElementById('disconnect-button').addEventListener('click', handleDisconnected);
      document.getElementById('hide-ball-button').addEventListener('click', onHideBall);
      document.getElementById('network-data-button').addEventListener('click', handleNetworkData);
      document.getElementById('resolution-button').addEventListener('click', handleSetResolution);
      document.getElementById('screenshot-button').addEventListener('click', handleGetScreenshot);
      document.getElementById('download-button').addEventListener('click', handleDownloadFileAction);
      document.getElementById('uploadFile').addEventListener('change', handleUploadFileAction);
      document.getElementById('transfer-info-button').addEventListener('click', getFileTransformInfo);
      document.getElementById('graphic-low-button').addEventListener('click', () => handleGraphicConfig('low'));
      document.getElementById('graphic-super-button').addEventListener('click', () => handleGraphicConfig('super'));
      document.getElementById('disable-touch-button').addEventListener('click', () => handleSetTouchEnabled(false, 50));
      
      // 云手机操作
      document.getElementById('vol-down-button').addEventListener('click', () => handleCloudPhoneOperation('VolDown'));
      document.getElementById('vol-up-button').addEventListener('click', () => handleCloudPhoneOperation('VolUp'));
      document.getElementById('mute-button').addEventListener('click', () => handleCloudPhoneOperation('Mute'));
      document.getElementById('back-button').addEventListener('click', () => handleCloudPhoneOperation('Back'));
      document.getElementById('home-button').addEventListener('click', () => handleCloudPhoneOperation('Home'));
      document.getElementById('app-switch-button').addEventListener('click', () => handleCloudPhoneOperation('AppSwitch'));
      document.getElementById('hide-nav-button').addEventListener('click', () => handleCloudPhoneOperation('HideNav'));
      document.getElementById('show-nav-button').addEventListener('click', () => handleCloudPhoneOperation('ShowNav'));
      document.getElementById('clipboard-send-button').addEventListener('click', () => sendMsgToCloudPhoneOperation('测试数据到云机剪贴板'));
      document.getElementById('clipboard-modal-button').addEventListener('click', showInput);
      
      // 云手机列表
      document.getElementById('get-app-list').addEventListener('click', onGetAppList);
      document.getElementById('clear-app-list').addEventListener('click', onClearAppList);
    });

    // 功能函数
    function enableManualParameter() {
      toggleElement('login-session-info', document.getElementById('manualParameter').checked);
    }

    function enabelUseTicketConn() {
        toggleElement('use-ticket-conn-info', document.getElementById('useTicketConn').checked);
        if (this.checked) {
            document.getElementById('useOtherConn').checked = false;
            document.getElementById('use-other-conn-info').style.display = 'none';
        } 
    }

    function enableUseOtherConn() {
        toggleElement('use-other-conn-info', document.getElementById('useOtherConn').checked);
        if (this.checked) {
            useTicketConn.checked = false;
            document.getElementById('use-ticket-conn-info').style.display = 'none';
        }
    }

    function onLogin() {
      const loginId = document.getElementById('loginId').value;
      const username = document.getElementById('username').value;
      const password = document.getElementById('password').value;
      
      if (!loginId || !username || !password) {
        showNotification('请填写所有登录信息', 'error');
        return;
      }
      
      const endpoint = 'https://appstream-center.cn-shanghai.aliyuncs.com/';
      const data = {
        Format: 'JSON',
        product: 'appstream-login',
        Version: '2021-02-20',
        Action: 'GetLoginToken',
        ClientId: '3713a1f1-1272-48be-bb72-6eab72f3bc72',
        Uuid: '3713a1f1-1272-48be-bb72-6eab72f3bc72',
        LoginIdentifier: loginId,
        EndUserId: username,
        Timestamp: new Date().toISOString(),
        CurrentStage: 'ADPassword',
        Password: password
      };

      axios.post(endpoint, paramStringify(data))
        .then(({ data }) => {
          const { LoginToken, SessionId } = data;
          document.getElementById('loginToken').value = LoginToken;
          document.getElementById('sessionId').value = SessionId;
          
          document.getElementById('loginParams').style.display = 'none';
          document.getElementById('logout').style.display = 'block';
          document.getElementById('appsInfos').style.display = 'block';
          document.getElementById('login-user').textContent = username;
          
          showNotification('登录成功', 'success');
        })
        .catch(e => {
          console.error('登录失败:', e);
          showNotification('登录失败，请检查凭证', 'error');
        });
    }

    function onLogout() {
      document.getElementById('loginParams').style.display = 'block';
      document.getElementById('logout').style.display = 'none';
      document.getElementById('appsInfos').style.display = 'none';
      onClearAppList();
      showNotification('已退出登录', 'info');
    }

    function onClear() {
      document.getElementById('loginToken').value = '';
      document.getElementById('sessionId').value = '';
      document.getElementById('authCode').value = '';
      document.getElementById('ticket').value = '';
      document.getElementById('appId_manual').value = '';
      document.getElementById('appVersion_manual').value = '';
      document.getElementById('appInstanceGroupId_manual').value = '';
      document.getElementById('productType_manual').value = '';
      showNotification('已清空参数', 'info');
    }

    function onClearAppList() {
      document.getElementById('applist').innerHTML = '';
    }

    function showInput() {
        showCustomDialog();
        // 点击遮罩层关闭弹框
        document.querySelector('.modal-overlay').addEventListener('click', function (e) {
            if (e.target === this) {
                closeModal();
            }
        });
        // ESC键关闭弹框
        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape') {
                closeModal();
            }
        });
    }

    function closeModal() {
        console.log('closeModal');
        const overlay = document.querySelector('.modal-overlay');
        if (overlay) {
            overlay.style.display = 'none';
            overlay.remove();
        }
    }

    function submitContent() {
        const content = document.querySelector('.input-field').value.trim();
        if (!content) {
            showNotification('请输入内容', 'error');
            return;
        }
        
        sendMsgToCloudPhoneOperation(content);
        closeModal();
        showNotification('内容已发送到云机剪贴板', 'success');
    }

    function showCustomDialog() {
        // 创建模态框背景
        const overlay = document.createElement('div');
        overlay.className = 'modal-overlay';
        // Ensure the modal captures all events and is displayed at the highest level
        overlay.style.pointerEvents = 'all';
        overlay.style.zIndex = '9999';
        
        // Prevent events from propagating to underlying layers
        const stopPropagation = function(e) {
            e.stopPropagation();
    };
    
    overlay.addEventListener('contextmenu', stopPropagation, true);
    
    // Add event listeners to intercept all keyboard events
    overlay.addEventListener('keydown', stopPropagation, true);
    overlay.addEventListener('keyup', stopPropagation, true);
    overlay.addEventListener('keypress', stopPropagation, true);
    
    overlay.innerHTML = `
        <div class="modal">
            <div class="modal-header">
                <h2 class="modal-title">剪贴板</h2>
                <button class="close-btn" onclick="closeModal()">×</button>
            </div>
            
            <div class="input-container">
                <textarea 
                    class="input-field" 
                    placeholder="请输入内容"
                    maxlength="500"
                ></textarea>
            </div>
            
            <button class="submit-btn" onclick="submitContent()">
                立即粘贴
            </button>
        </div>
    `;

    document.body.appendChild(overlay);
    
    // Focus the textarea when the modal opens to ensure keyboard events are captured
    setTimeout(() => {
        const textarea = overlay.querySelector('.input-field');
        if (textarea) {
            textarea.focus();
        }
    }, 100);
  }

    var resetVisible = false
    function onHideBall() {
        var uiConfig = {
        toolbar: {
            visible: !resetVisible,
        }
        };
        resetVisible = !resetVisible;
        session.setUiParams(uiConfig);
    }

  function isClientSupportRtc() {
    let supportRTCPeerConnection = ['RTCPeerConnection', 'webkitRTCPeerConnection', 'mozRTCPeerConnection'].some((item) => {
        return (item in window);
    });
    if (!supportRTCPeerConnection) {
        AspLogger.info("browser support webrtc false!");
    }
    return supportRTCPeerConnection;
  }

  function isUcBrowser() {
      const ua = navigator.userAgent;
      return /UCBrowser|UCWEB/.test(ua);
  }

  function isSafari() {
      return /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  }


  function paramStringify(obj) {
    return Object.keys(obj)
      .filter((k) => obj[k] || +obj[k] === 0)
      .map((k) => {
        let value = obj[k];
        typeof value === "object"
          ? (value = encodeURIComponent(JSON.stringify(value)))
          : (value = encodeURIComponent(value));
        return `${encodeURIComponent(k)}=${value}`;
      })
      .join("&");
  }

  function getFileUploadConfig() {
    var type = 'PDS'
    var driveId = document.getElementById('driveId').value;
    var uploadPath = document.getElementById('uploadPath').value;

    var options = document.querySelector('#uploadType').options;

    var uploadType = [];
    for (let i = 0; i < options.length; i++) {
      if (options[i].selected) {
        uploadType.push(options[i].value)
      }
    }
    console.log(uploadType, 'uploadType')
    return {
      type: "PDS",
      driveId: driveId,
      uploadPath: uploadPath,
      uploadType: uploadType,
      onTransferCallback: (type, data) => {
        console.log(type, data);
        // if (progress >= 80) {
        //   cancelFn();
        // }
      }
    }
  }

  function collectThumbnailData() {
    const appIdInputs = document.querySelectorAll('input[name="thumb_appInstanceId"]');
    const ticketInputs = document.querySelectorAll('input[name="thumb_ticket"]');
    const data = [];
    appIdInputs.forEach((appIdInput, index) => {
      const thumbnailId = appIdInput.dataset.thumbnailId;
      const ticketInput = ticketInputs[index];
      // 确保 appInstanceId 和 ticket 属于同一组
      if (ticketInput && ticketInput.dataset.thumbnailId === thumbnailId) {
        data.push({
          thumbnailId,
          appInstanceId: appIdInput.value.trim(),
          ticket: ticketInput.value.trim(),
        });
      }
    });
    return data;
  }

  function getSelectedFiles() {
    const input = document.getElementById('fileInput');
    const files = input.files;

    if (files.length === 0) {
      console.log("未选择任何文件");
      return [];
    }

    const fileArray = Array.from(files);
    return fileArray;
  }

  async function processJsonFiles() {
    const results = [];
    const selectedFiles = getSelectedFiles();
    for (const file of selectedFiles) {
      if (file.name.endsWith('.json')) {
        try {
          const content = await file.text();
          const data = JSON.parse(content);
          const models = data.InstanceConnectionModels || [];
          results.push(...models); // 收集所有模型
        } catch (error) {
          console.error(`解析失败:`, error);
        }
      }
    }
    return results; // 返回所有解析后的模型
  }

  function onAddThumbnail(name) {
    console.log("onAddThumbnail", name);
    const container = document.getElementById("thumbnail-info");
    if (!container) {
        console.error("AddThumbnail Container element not found!");
        return;
    }
    
    // 生成唯一 ID
    const containerId = `thumbnail_${thumbnail_index++}`;
    const inputTicketId = `${containerId}_ticket`;
    const inputAppId = `${containerId}_appInstanceId`;

    // 创建缩略图配置组容器
    const thumbnailGroup = document.createElement("div");
    thumbnailGroup.className = "thumbnail-group";
    thumbnailGroup.style.cssText = `
        border: 1px solid #e8e8e8;
        border-radius: 8px;
        padding: 16px;
        margin-bottom: 16px;
        background-color: #fafafa;
        position: relative;
    `;

    // App实例ID输入框
    const appIdContainer = document.createElement("div");
    appIdContainer.className = "form-group";
    appIdContainer.style.marginBottom = "12px";

    const label_appId = document.createElement("label");
    label_appId.htmlFor = inputAppId;
    label_appId.textContent = "App实例ID:";
    label_appId.style.cssText = `
        display: block;
        margin-bottom: 6px;
        font-weight: 500;
        color: #333;
        font-size: 14px;
    `;

    const input_appId = document.createElement("input");
    input_appId.type = "text";
    input_appId.id = inputAppId;
    input_appId.name = "thumb_appInstanceId";
    input_appId.placeholder = "必填，值以ai-开头";
    input_appId.dataset.thumbnailId = containerId;
    input_appId.style.cssText = `
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #d9d9d9;
        border-radius: 6px;
        font-size: 14px;
        transition: all 0.3s;
    `;
    
    // 添加焦点效果
    input_appId.addEventListener('focus', function() {
        this.style.borderColor = '#1890ff';
        this.style.boxShadow = '0 0 0 2px rgba(24, 144, 255, 0.2)';
    });
    
    input_appId.addEventListener('blur', function() {
        this.style.borderColor = '#d9d9d9';
        this.style.boxShadow = 'none';
    });

    appIdContainer.appendChild(label_appId);
    appIdContainer.appendChild(input_appId);

    // Ticket输入框
    const ticketContainer = document.createElement("div");
    ticketContainer.className = "form-group";

    const label_ticket = document.createElement("label");
    label_ticket.htmlFor = inputTicketId;
    label_ticket.textContent = "Ticket:";
    label_ticket.style.cssText = `
        display: block;
        margin-bottom: 6px;
        font-weight: 500;
        color: #333;
        font-size: 14px;
    `;

    const input_ticket = document.createElement("input");
    input_ticket.type = "text";
    input_ticket.id = inputTicketId;
    input_ticket.name = "thumb_ticket";
    input_ticket.placeholder = "请输入ticket";
    input_ticket.dataset.thumbnailId = containerId;
    input_ticket.style.cssText = `
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #d9d9d9;
        border-radius: 6px;
        font-size: 14px;
        transition: all 0.3s;
    `;
    
    // 添加焦点效果
    input_ticket.addEventListener('focus', function() {
        this.style.borderColor = '#1890ff';
        this.style.boxShadow = '0 0 0 2px rgba(24, 144, 255, 0.2)';
    });
    
    input_ticket.addEventListener('blur', function() {
        this.style.borderColor = '#d9d9d9';
        this.style.boxShadow = 'none';
    });

    ticketContainer.appendChild(label_ticket);
    ticketContainer.appendChild(input_ticket);

    // 删除按钮
    const deleteBtn = document.createElement("button");
    deleteBtn.type = "button";
    deleteBtn.textContent = "× 删除";
    deleteBtn.style.cssText = `
        position: absolute;
        top: 8px;
        right: 8px;
        background: #ff4d4f;
        color: white;
        border: none;
        border-radius: 4px;
        padding: 4px 8px;
        font-size: 12px;
        cursor: pointer;
        transition: all 0.3s;
    `;
    
    deleteBtn.addEventListener('mouseover', function() {
        this.style.background = '#cf1322';
    });
    
    deleteBtn.addEventListener('mouseout', function() {
        this.style.background = '#ff4d4f';
    });
    
    deleteBtn.addEventListener('click', function() {
        // 从DOM中移除整个组
        thumbnailGroup.remove();
        
        // 从缩略图SDK映射中移除（如果存在）
        const appInstanceId = input_appId.value.trim();
        if (appInstanceId && thumbnailSDKMap.has(appInstanceId)) {
        const thumbnailItem = thumbnailSDKMap.get(appInstanceId);
        if (thumbnailItem) {
            thumbnailItem.stopThumbnail();
        }
        thumbnailSDKMap.delete(appInstanceId);
        }
        
        // 显示通知（如果存在通知函数）
        if (typeof showNotification === 'function') {
        showNotification('已删除缩略图配置', 'info');
        }
    });

    // 组装所有元素
    thumbnailGroup.appendChild(deleteBtn);
    thumbnailGroup.appendChild(appIdContainer);
    thumbnailGroup.appendChild(ticketContainer);
    container.appendChild(thumbnailGroup);

    console.log("Thumbnail to add", containerId);
    
    // 滚动到新添加的元素
    thumbnailGroup.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
  }

  async function onConnect(name) {
    handleDisconnectThumbnail();
    console.log("Thumbnail to connect1");
    var loginToken = document.getElementById('loginToken').value;
    var sessionId = document.getElementById('sessionId').value;
    var authCode = document.getElementById('authCode').value;
    var ticket = document.getElementById('ticket').value;
    var appName = 'Title';
    if (document.getElementById('appName_' + name) && document.getElementById('appName_' + name).innerText) {
      appName = document.getElementById('appName_' + name).innerText.split('|')[0];
    }
    var appId = document.getElementById('appId_' + name)?.value;
    var appInstanceId = document.getElementById('appInstanceId_' + name)?.value;
    var appInstanceGroupId = document.getElementById('appInstanceGroupId_' + name)?.value;
    var appVersion = document.getElementById('appVersion_' + name)?.value;
    var productType = document.getElementById('productType_' + name)?.value;
    var resourceId = document.getElementById('resourceId_' + name)?.value;
    // var connectionProperties = document.getElementById('connectionProperties_' + name)?.value;
    var connectionProperties = JSON.stringify({ authMode: "Session" })

    var openType = document.querySelector('input[name="openType"]:checked')?.value;
    var resourceType = document.querySelector('input[name="resourceType"]:checked')?.value;
    var isOverseas = false;
    var graphicConfigFluent = document.getElementById('graphicConfigFluent')?.checked;
    var connConfig = document.getElementById('connConfig')?.value;
    var hideProgressDialog = document.getElementById('hideProgressDialog')?.checked;
    var setCloudPhoneLoading = document.getElementById('setCloudPhoneLoading')?.checked;

    console.log(loginToken, sessionId, openType, resourceType, appName);

    var iframeId = 'sessionIframe';
    var desktopContainer = document.getElementById('desktop-container');
    var originIframeDom = document.getElementById('sessionIframe');
    if (openType === 'inline-multi') {
      openType = 'inline';
      iframeId = iframeId + name + 'app';
      if (originIframeDom) {
        desktopContainer.removeChild(originIframeDom);
      }
      var singleIframeDom = document.getElementById(iframeId);
      if (!singleIframeDom) {
        var iframeDom = document.createElement('iframe');
        iframeDom.id = iframeId;
        desktopContainer.appendChild(iframeDom);
      }
    } else if (!originIframeDom) {
      desktopContainer.innerHTML = ''
      var iframeDom = document.createElement('iframe');
      iframeDom.id = iframeId;
      desktopContainer.appendChild(iframeDom);
    }

    var userInfo = {
      loginToken: loginToken,
      sessionId: sessionId,
      authCode: authCode,
      ticket: ticket,
    };
    var connConfig = JSON.parse(connConfig || '{}');
    var osType = 'Android';
    //useCustomIme 是否使用本地输入法 disableOrientation 是否禁止云侧横竖屏自适应
    connConfig = {disableCamera: true, decodeType:2, readClipboardDataByUser:isSafari(), useCustomIme:true, disableOrientation:mDisableOrientation,resolutionAdaptive:false}; 
    if (isClientSupportRtc() && !isUcBrowser()) {//不加载无影自研解码器 且 强转使用WEBRTC
        connConfig = {disableCamera: true, decodeType:2, disableLoadWYDecoder: true, readClipboardDataByUser:isSafari(), useCustomIme:true, disableOrientation:mDisableOrientation,resolutionAdaptive:false}; 
    } 

    var appInfo = {
      appId: appId,
      appVersion: appVersion,
      appInstanceId,
      loginRegionId: regionId,
      appName: appName,
      productType: productType,
      appInstanceGroupId,
      resourceId: resourceId,
      connectionProperties: connectionProperties,
      connConfig: connConfig,
      osType: osType
    };
    var fileTransferConfig
    var sessionParam = {
      openType: openType,
      iframeId: iframeId,
      resourceType: resourceType,
      connectType: 'app',
      userInfo: userInfo,
      appInfo: appInfo,
      regionId,
      isOverseas,
      uiConfig: {
        toolbar: {
          visible: false,
          // // 管理菜单
          // adminMenu: true,
          // // 偏好设置菜单
          // perferenceSettingTab: true,
          // // 显示菜单
          // displayTab: true,
          // // 画面菜单
          // graphicTab: true,
          // // 鼠标操控菜单
          // mouseControlTab: true,
          // // 上传菜单
          // uploadMenu: true,
          // // 下载菜单
          // downloadMenu: true,
          // statefulInspectionMenu: false
        },
        rotateDegree:0,
        hideProgressDialog,
        vconsoleVisible: true,
      },
      lyncChannelConfig: [
        {
          lyncChannelName: 'lync_adb_shell',
        },
      ],
      dataChannelConfig: [{
        dataChannelName: 'wy_vdagent_default_dc',
      }]
    };

    if (graphicConfigFluent) {
      sessionParam.uiConfig.graphicConfig = 'fluent';
    }

    var wuyingSdk = Wuying.WebSDK;
    session = wuyingSdk.createSession('appstream', sessionParam);
    console.log(session);
    session.addHandle('getConnectionTicketInfo', (data) => {
      console.log("getConnectionTicketInfo:",data);
      parseConnectionInfo(data);
    });
    session.addHandle('onClipBoardReadData', (data) => {
      console.log('onClipBoardReadData', data);
    });
    session.addHandle('onClipBoardWriteData', (data) => {
      console.log('callback invoke onClipBoardWriteData',data);
    });
    session.addHandle('onConnected', (data) => {
      console.log('connected', data);
      session.setLocalConfig('setClipboardEnabled', true)
      session.enableGroupControl(mEnableGroupControl)
      // 监听数据通道消息
      session.addDataChannelListener('wy_vdagent_default_dc', 'data', data => {
        console.log('data from wy_vdagent_default_dc', data)
        parseCommand(data)
      });
      // 监听adb命令回调
      session.addLyncListener('lync_adb_shell', 'onReceivedLyncData', data => console.log('data from lync_adb_shell', data));
      session.addLyncListener('lync_adb_shell', 'onConnectionStateChange', data => console.log('lync_adb_shell onConnectionStateChange ', data));

      // 发送数据通道消息消息
      // 入参： 通道名称  消息内容
      // setTimeout(() => {
      //   session.sendDataChannelMessage('wy_vdagent_default_dc', new Uint8Array([1, 2, 3, 4]));
      // }, 5000)
    });

    session.addHandle('onDisConnected', (data) => {
      console.log('disconnect', data);
    });

    session.addAudioListener(console.log);

    session.addConnectionListener('onFirstFrameDecodeSuccess', (eventName, data) => {
      console.log('获取到connection连接回调信息： ', eventName, data);
    });
    session.start();

    const thumbnail_list = collectThumbnailData();
    const allModels = await processJsonFiles();
    allModels.forEach((model, index) => {
      console.log("Thumbnail add ", model.InstanceId, model.AppInstanceId);
      thumbnail_list.push({
        thumbnailId: model.InstanceId,
        appInstanceId: model.AppInstanceId,
        ticket: model.Ticket,
      });
    });
    const container = document.getElementById("thumbnail-container");
    if (!container) {
      console.error("Thumbnail Container element not found!");
      return;
    }
    const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        const { target, isIntersecting } = entry;
        const div = entry.target;
        const index = div.id.replace('thumbnail_', '');
        const thumbnail = thumbnail_list[index];
        if (isIntersecting) {
          // 元素进入视口（可见）
          console.log(`${target.id} 现在可见了！${thumbnail.appInstanceId}`);
          resumeThumbnailDisplay(thumbnail.appInstanceId, 200, 360, 1);
          const img = div.querySelector('img');
          const params = {
            appInstanceId: thumbnail.appInstanceId,
            ticket: thumbnail.ticket,
            width: 200,
            height: 360,
            fps: 1
          };
          
          requestThumbnail(params, (params, url, errorCode) => {
            if (!errorCode) {
              img.src = url;
            } else {
              console.error("缩略图生成失败:", errorCode);
            }
          });
        } else {
          // 元素离开视口（不可见）
          suspendThumbnailDisplay(thumbnail.appInstanceId);
          console.log(`${target.id} 不可见了 ${thumbnail.appInstanceId}`);
        }
      });
    }, {
      threshold: 0.1 // 当 10% 的元素可见时就算“进入视口”
    });
    thumbnail_list.forEach((thumbnail, index) => {
        const containerId = `thumbnail_${index}`;
        const imgId = `img_${containerId}`;
        // 创建 div 元素并设置 ID
        const div = document.createElement("div");
        div.id = containerId;
        div.style.width = "200px";      // 固定宽度
        div.style.height = "360px";     // 固定高度
        div.style.border = "1px solid #ccc"; // 可选：边框
        container.appendChild(div);
        if (mEnableGroupControl) window.Wuying.ThumbnailSDK.groupControlIds.push(thumbnail.appInstanceId);

        const img = document.createElement("img");
        img.id = imgId;
        img.style.width = "200px";      // 固定宽度
        img.style.height = "360px";     // 固定高度
        img.style.border = "1px solid #ccc"; // 可选：边框
        div.appendChild(img);

        observer.observe(div);
    });
  }

  async function onReconnect() {
    if (session) {
      console.log("onReconnect");
    var loginToken = document.getElementById('loginToken').value;
    var sessionId = document.getElementById('sessionId').value;
    var authCode = document.getElementById('authCode').value;
    var ticket = document.getElementById('ticket').value;
    session.refreshConnect({
      loginToken,
      sessionId,
      authCode,
      ticket,
    });
    }
  }
  function parseConnectionInfo(data) {
    try {
          mResolutionHeight = parseInt(data.Policy.ResolutionHeight, 10);
          mResolutionWidth = parseInt(data.Policy.ResolutionWidth, 10);
          var quality = document.querySelector('input[name="quality"]:checked')?.value;
          handleGraphicConfig(quality);
      } catch (e) {
          console.error("解析失败:", data, e);
      }
  }
  function parseCommand(data) {
      try {
          const jsonStr = data.replace(/^data:/, '').trim();
          const json = JSON.parse(jsonStr);
          if (json.action !== undefined) {
              handleCommand(json.action, json);
          } else if (json.cmd !== undefined) {
              handleCommand(json.cmd, json);
          } else {
              console.warn("无效命令格式:", jsonStr);
          }
      } catch (e) {
          console.error("解析失败:", data, e);
      }
  }

  function handleCommand(cmd, json) {
      try {
          switch (cmd) {
              case "authorizeCamera": 
                  if (session != null) {
                    console.log(`setCameraCanUse true`);
                    session.setLocalConfig('setCameraCanUse', true);
                  }
                  break;
              case "rotation":
                  const rotationValue = parseInt(json.value, 10) ;
                  //禁止云侧横竖屏自适应，使用端侧本地旋转
                  if (session != null && mDisableOrientation) {
                    var rotate = rotationValue * 90; 
                    if (rotationValue === 1) {
                        rotate = 270;
                    } else if (rotationValue === 3) {
                        rotate = 90;
                    }
                    console.info("setRotate:", rotate);
                    session.setUiParams({ rotateDegree: rotate })
                }
                  break;
              default:
                  break;
          }
      } catch (e) {
          console.error("命令处理失败:", cmd, e);
      }
  }

  function startPingDiagnosis(name) {
    var loginToken = document.getElementById('loginToken').value;
    var sessionId = document.getElementById('sessionId').value;

    var appId = document.getElementById('appId_' + name)?.value;
    var appVersion = document.getElementById('appVersion_' + name)?.value;
    var openType = document.querySelector('input[name="openType"]:checked')?.value;
    var resourceType = document.querySelector('input[name="resourceType"]:checked')?.value;
    var productType = document.getElementById('productType_' + name)?.value;
    var resourceId = document.getElementById('resourceId_' + name)?.value;
    var connectionProperties = document.getElementById('connectionProperties_' + name)?.value;

    var iframeId = 'sessionIframe';
    var userInfo = {
      loginToken: loginToken,
      sessionId: sessionId,
    };

    var appInfo = {
      appId: appId,
      appVersion: appVersion,
      loginRegionId: regionId,
      productType: productType,
      resourceId: resourceId,
      connectionProperties: connectionProperties,
    };
    var sessionParam = {
      openType: openType,
      iframeId: iframeId,
      resourceType: resourceType,
      connectType: 'app',
      userInfo: userInfo,
      appInfo: appInfo,
      regionId,
    };
    var wuyingSdk = Wuying.WebSDK;
    session = wuyingSdk.createSession('appstream', sessionParam);
    console.log(session);

    session.startPingDiagnosis({ callback: console.log })
  }

  function onGetAppList(e) {
    var loginToken = document.getElementById('loginToken').value;
    var sessionId = document.getElementById('sessionId').value;
    var data = {
      Format: "JSON",
      product: 'ecd',
      Version: '2020-10-02',
      Action: 'DescribeUserResources',
      ClientId: '3713a1f1-1272-48be-bb72-6eab72f3bc72',
      Timestamp: new Date().toISOString(),
      LoginToken: loginToken,
      SessionId: sessionId,
      ["ResourceTypes.1"]: "App",
      ProductType: 'ecd',
    }

    axios.post("https://ecd.cn-shanghai.aliyuncs.com/DescribeUserResources", paramStringify(data)).then(
      ({ data }) => {
        console.log('success', data);
        onClearAppList();
        data.Resources.forEach((v, idx) => {
            console.log(v);
            var appLists = v;
            var appId = "android";
            var appVersion = appLists.Version;
            var appName = appLists.ResourceName;
            var productType = appLists.ProductType;
            var resourceId = appLists.ResourceId;
            var connectionProperties = appLists.ConnectionProperties;
            
            // 创建应用卡片容器
            const appCard = document.createElement('div');
            appCard.className = 'app-item';
            
            // 应用名称
            const appNameDiv = document.createElement('div');
            appNameDiv.className = 'app-name';
            appNameDiv.textContent = appName;
            appCard.appendChild(appNameDiv);
            
            // 应用详情容器
            const appDetails = document.createElement('div');
            appDetails.className = 'app-details';
            
            // 创建详情项的辅助函数
            function createDetail(labelText, value, inputId, inputName) {
                const detailDiv = document.createElement('div');
                detailDiv.className = 'app-detail';
                
                const label = document.createElement('label');
                label.textContent = labelText + ':';
                
                const input = document.createElement('input');
                input.type = 'text';
                input.id = inputId;
                input.name = inputName;
                input.value = value || '';
                input.readOnly = true; // 设为只读，避免用户误修改
                input.style.cssText = `
                flex: 1;
                padding: 6px 8px;
                border: 1px solid #e8e8e8;
                border-radius: 4px;
                background-color: #fafafa;
                font-size: 13px;
                margin-left: 8px;
                `;
                
                detailDiv.appendChild(label);
                detailDiv.appendChild(input);
                return detailDiv;
            }
            
            // 添加各个详情项
            appDetails.appendChild(createDetail('appId', appId, `appId_${idx}`, 'appId'));
            appDetails.appendChild(createDetail('appVersion', appVersion, `appVersion_${idx}`, 'appVersion'));
            appDetails.appendChild(createDetail('productType', productType, `productType_${idx}`, 'productType'));
            appDetails.appendChild(createDetail('resourceId', resourceId, `resourceId_${idx}`, 'resourceId'));
            appDetails.appendChild(createDetail('connectionProperties', connectionProperties, `connectionProperties_${idx}`, 'connectionProperties'));
            
            appCard.appendChild(appDetails);
            
            // 操作按钮容器
            const appActions = document.createElement('div');
            appActions.className = 'app-actions';
            
            // 创建按钮的辅助函数
            function createButton(text, onClickHandler, className = 'btn') {
                const button = document.createElement('button');
                button.type = 'button';
                button.className = className;
                button.textContent = text;
                button.addEventListener('click', onClickHandler);
                return button;
            }
            
            // 连接按钮
            const connectBtn = createButton('连接', () => onConnect(idx), 'btn');
            // 重连按钮
            const reconnectBtn = createButton('重连', () => onReconnect(idx), 'btn btn-secondary');
            
            appActions.appendChild(connectBtn);
            appActions.appendChild(reconnectBtn);
            
            appCard.appendChild(appActions);
            
            // 添加到应用列表
            document.querySelector('#applist').appendChild(appCard);
        });
      }
    ).catch(e => {
      console.log('error', e);
    })
  }

  function enableGroupControl() {
    mEnableGroupControl = document.getElementById('groupcontrol').checked;
    console.log('enableGroupControl: ', mEnableGroupControl);
  }

  function init() {
    var x = document.getElementById('password');
    var style = window.getComputedStyle(x);
    if (style.webkitTextSecurity) {
    } else {
      x.setAttribute("type", "password");
    }
  }

  function handleDownloadFileAction() {
    if (session) {
      session.downloadFileAction(true);
    }
  }

  function handleUploadFileAction(e) {
    const files = Array.from(e.target.files);
    console.log('选中上传的文件： ', files);
    if (session) {
      session.uploadFileAction(files, true);
    }
  }

  function getFileTransformInfo() {
    if (session) {
      // 监听文件列表传输进度等信息
      session.getFileTransformInfo((eventName, data) => {
        console.log('获取到文件传输信息： ', eventName, data);
      });
    }
  }

  function handleSetResolution() {
    if (session) {
      session.setResolution(700, 1080, 0);
    }
  }

  function handleNetworkData() {
    if (session) {
      session.addHandle('networkData', (data) => {
        console.log('networkData', data);
      });
    }
  }

  //端侧截屏数据
  function handleGetScreenshot() {
    if (session) {
        /**
         * 获取当前截图
         * @param callback - 回调函数，可获取截图的blob
         * @param immediate - 设置为true时直接下载到本地
         */
        session.getScreenshot(console.log, true);
    }
  }

  function handleDisconnected() {
    if (session) {
      session.stopConnection();
    }
    handleDisconnectThumbnail();
  }

  function handleDisconnectThumbnail() {
    for (const [key, value] of thumbnailSDKMap) {
        console.log('thumbnial stop', key);
        value.thumbnail.session.stop();
    }
    thumbnailSDKMap.clear();
    const container = document.getElementById("thumbnail-container");
    if (container) {
      container.innerHTML = ""; // 清空所有子元素
    }
  }

  function handleGraphicConfig(quality) {
    var bps = ResolutionUtils.getBps(quality, mResolutionWidth, mResolutionHeight);
    console.info("parseConnectionInfo W:", mResolutionWidth, ",H:", mResolutionHeight, ",quality:", quality, ",bps:", bps);
    if (session) {
        session.customASPAction('setGraphicsBitrate', [bps])
        // ASP_IMAGE_QUALITY_LOSSLESS: 0,
        // ASP_IMAGE_QUALITY_HIGH: 1,
        // ASP_IMAGE_QUALITY_MEDIUM: 2,
        // ASP_IMAGE_QUALITY_LOW: 3,
        // ASP_IMAGE_QUALITY_AUTO: 4
        let qIndex = 2;
        if (quality === 'low') {
            qIndex = 3;
        } else if (quality === 'normal') {
            qIndex = 2;
        } else if (quality === 'high') {
            qIndex = 1;
        } else if (quality === 'super') {
            qIndex = 0;
        }
        session.customASPAction('setImageQuality', [qIndex])
    }
  }

  function handleSetTouchEnabled(enable, delay) {
    if (session) {
      session.setLocalConfig('setTouchEnabled', enable, delay);
    }
  }

  window.onload = function () {
    init();
    // 阻止双击放大
    var lastTouchEnd = 0;
    document.addEventListener('touchstart', function (event) {
      if (event.touches.length > 1) {
        event.preventDefault();
      }
    });
    document.addEventListener('touchend', function (event) {
      var now = (new Date()).getTime();
      if (now - lastTouchEnd <= 300) {
        event.preventDefault();
      }
      lastTouchEnd = now;
    }, false);
    // 阻止双指放大
    document.addEventListener('gesturestart', function (event) {
      event.preventDefault();
    });
  }