import { _decorator, Component, Node, sys, url } from 'cc';
import { config } from './config';
import { tools } from './tools';
import { userDataManager } from './manager/userDataManager';
import { SdkUtil } from './sdkUtil';
const { ccclass, property } = _decorator;
@ccclass('http')
export class http {
    public static domain = config.debug?"https://zcapi.xwrun.com":"https://zcapi.hainanmlwl.com"
    public static static_domain = config.debug?"https://zcapi.xwrun.com":"https://zaoca.oss-cn-beijing.aliyuncs.com"
    public static statistics_domain = config.debug?"https://zcapi.xwrun.com":""
    public static post(url,opt, call_back,method:string='POST') {
        var xml = new XMLHttpRequest()
        let request_url = http.domain+url
        xml.open(method,  request_url)
        xml.setRequestHeader('Content-Type', 'application/json');
        if(userDataManager.user_data!=null){
            xml.setRequestHeader('token',userDataManager.user_data.token);
        }
        if(opt==null){
            xml.send();
        }else{
            xml.send(JSON.stringify(opt));
        }
 
        // xml.send(opt);
        var array: String[] = ['loadstart', 'abort', 'error', 'load', 'loadend', 'timeout'];
        array.forEach(function (eventName) {
            xml[('on' + eventName) as 'onloadstart' | 'onabort' | 'onerror' | 'onload' | 'onloadend' | 'ontimeout'] = function () {
                //    var str =  '\nEvent : ' + eventName;
                var lstr = ""
                if (eventName === 'timeout') {
                    lstr += '(timeout)';
                }
                else if (eventName === 'loadend') {
                    lstr += '...loadend!';

                } else if (eventName === 'onerror') {

                }
            };
        });

        // Special event
        xml.onreadystatechange = function () {
            if (xml.readyState === 4 && xml.status >= 200) {
                call_back(null, xml.responseText);
            } else if (xml.status === 404) {
                call_back('404 page not found!', null);
            }
        };
    }

    public static get(url, call_back) {
        var xml = new XMLHttpRequest()
        let request_url = http.static_domain+url
        xml.open('GET', request_url)
        xml.setRequestHeader('Content-Type', 'application/json');
        xml.send();

        var array: String[] = ['loadstart', 'abort', 'error', 'load', 'loadend', 'timeout'];
        array.forEach(function (eventName) {
            xml[('on' + eventName) as 'onloadstart' | 'onabort' | 'onerror' | 'onload' | 'onloadend' | 'ontimeout'] = function () {
                //    var str =  '\nEvent : ' + eventName;
                var lstr = ""
                if (eventName === 'timeout') {
                    lstr += '(timeout)';
                }
                else if (eventName === 'loadend') {
                    lstr += '...loadend!';

                } else if (eventName === 'onerror') {

                }
            };
        });

        // Special event
        xml.onreadystatechange = function () {
            if (xml.readyState === 4 && xml.status >= 200) {
                call_back(null, xml.responseText);
            } else if (xml.status === 404) {
                call_back('404 page not found!', null);
            }
        };
    }

    public static uploadFile(url, filePath, progress_call_back, call_back) {
        let success_cb = ((res)=>{
            // console.log(`uploadFile调用成功 ${res.data}`);
            if (res.statusCode === 200) {
                call_back(null,res.data)
            } else {
                call_back(res.statusCode,null)
            }
        })
        let fail_cb = ((err)=>{
            // console.log(`tt_uploadFile调用失败${err}`);
            call_back(err,null)
        })
        let progress_cb =((res)=>{
            // console.log('progress=',res.progress)
            if(progress_call_back) { progress_call_back(res.progress) }
        })
        let upload_url = http.domain + url
        let name = 'file'
        if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            let task = tt.uploadFile({
                url: upload_url,
                filePath: filePath,
                name: name,
                success(res) { success_cb(res) },
                fail(err) { fail_cb(err) },
            });
            task.onProgressUpdate((res) => { progress_cb(res) }); 
        }
        else if(sys.platform == sys.Platform.WECHAT_GAME) {
            if(SdkUtil.KS_GAME) {
                let task = ks.uploadFile({
                    url: upload_url,
                    filePath: filePath,
                    name: name,
                    success(res) { success_cb(res) },
                    fail(err) { fail_cb(err) },
                });
                task.onProgressUpdate((res) => { progress_cb(res) });
            } else {
                let task = wx.uploadFile({
                    url: upload_url,
                    filePath: filePath,
                    name: name,
                    success(res) { success_cb(res) },
                    fail(err) { fail_cb(err) },
                });
                task.onProgressUpdate((res) => { progress_cb(res) }); 
            }
        }

        // var xml = new XMLHttpRequest()
        // let request_url = http.domain+url
        // console.log('request_url=',request_url)
        // xml.open('POST', request_url, true)
        // xml.setRequestHeader('Content-Type', 'multipart/form-data');
        // if(userDataManager.user_data!=null){
        //     xml.setRequestHeader('token',userDataManager.user_data.token);
        // }

        // //创建一个FormData对象来处理文件上传
        // let formData = new FormData()
        // formData.append("file", filePath)
        // //发送请求
        // xml.send(formData)

        // // 监听上传进度事件
        // xml.upload.onprogress = function(event) {
        //     if (event.lengthComputable) {
        //         var percentComplete = (event.loaded / event.total) * 100;
        //         console.log(Math.round(percentComplete) + "% uploaded");
        //     }
        // };

        // // 监听请求完成事件
        // xml.onload = function() {
        //     if (xml.status === 200) {
        //         console.log("File uploaded successfully");
        //     } else {
        //         console.log("Upload failed with status: " + xml.status);
        //     }
        // }

        // // 监听错误事件
        // xml.onerror = function() {
        //     console.log("Network error occurred");
        // };

        // // Special event
        // xml.onreadystatechange = function () {
        //     console.log('xml.readyState=',xml.readyState,'       xml.status=',xml.status)
        //     if (xml.readyState === 4 && xml.status >= 200) {
        //         call_back(null, xml.responseText);
        //     } else if (xml.status === 404) {
        //         call_back('404 page not found!', null);
        //     }
        // }
    }

}


