let classdoc_app = new Vue({
    el: '#classdoc_app',
    data: {
        cos: new COS({
            getAuthorization: function (options, callback) {
                classdoc_app.getCosAuth((ret, data) => {
                    if (ret) {
                        callback({
                            TmpSecretId: data.tmp_secret_id,
                            TmpSecretKey: data.tmp_secret_key,
                            XCosSecurityToken: data.session_token,
                            ExpiredTime: data.expired_time
                        });
                    } else {
                        this.showAlertMsg("获取上传签名失败:" + data);
                    }
                });
            }
        }),
        bucket: '',
        doclist: [],
        wholelist: [],
        showdoclist: [],
        publicdoc: false,
        showUpload: true,
        total: 0,
        index: 1,
        otherpageindex: 1,
        fetchDocIndex: 0,
        searchkey: '',
        loading: true,
        is_show_dialog: false,
        is_file_uploading: false,
        is_window_show: true,
        dialog_title: '',
        dialog_msg: '',
        dialog_button: [],
        dialog_callback: 0,
        uploading_doc: [],
        nodata_t1: '',
        nodata_t2: '',
        nodata_t3: '',
    },
    created: function() {
        this.getCosAuth((ret, data) => {
            if (ret) {
                this.bucket = data.bucket_name + "-1259648581";     // appid     
            } else {
                //this.showAlertMsg("获取上传签名失败:" + data);
                log.error("[TAG-UPLOAD] getCosAuth->fail: "+JSON.stringify(data, null, 2));
            }
        });
    },
    mounted: function () {
        this.getClassDocList(this.publicdoc, 0, true, (success, data) => {
            this.loading = false;
            if (success) {
                this.parseDocListRet(success, data);
            }
        });
        let self = this;
        setInterval(function() {
            self.getClassDocList(self.publicdoc, 0, false, (success, data) => {
                self.loading = false;
                if (success) {
                    for (let doc of data.list) {
                        for (let current of self.wholelist) {
                            if (current.doc_id == doc.doc_id) {
                                if (doc.is_transcode) {
                                    if (doc.transcode_status == 'prepared' || doc.transcode_status == 'queued') {
                                        current.transcode_status = '准备';
                                    }else if (doc.transcode_status == 'processing') {
                                        current.transcode_status = '转码中';
                                    }else if (doc.transcode_status == 'finished' && doc.transcode_result === '') {
                                        current.transcode_status = '转码失败';
                                    }else {
                                        current.transcode_status = '完成';
                                        current.transcode_result = doc.transcode_result;
                                        current.doc_height = doc.doc_height;
                                        current.doc_width = doc.doc_width;
                                        current.pages = doc.pages;
                                    }
                                }
                            }
                        }

                    }
                }
            });
        }, 3000)
    },
    watch: {
        searchkey: function (val) {
            if (val === '') {
                this.doclist = this.wholelist;
            }else {
                this.doclist = [];
                for (item of this.wholelist) {
                    if (item.doc_name.indexOf(val) !== -1) {
                        this.doclist.push(item);
                    }
                }
            }
            this.total = this.doclist.length;
            this.onPageChange(1);
        },
    },
    methods: {
        close: function () {
          if (this.is_file_uploading){
            sendIpcMessage('WIN_DOCLIST:SHOW', false);
          }else{
            sendIpcMessage('WIN_DOCLIST:CLOSE', g_data.classId);
          }
        },
        refresh: function () {
            searchkey = '';
            this.getClassDocList(this.publicdoc, 0, true, (success, data) => {
                this.loading = false;
                if (success) {
                    this.parseDocListRet(success, data);
                    this.onPageChange(1);
                }
            });
        },
        onWindowShow: function(){
          this.is_window_show = true;
        },
        onWindowHide: function(){
          this.is_window_show = false;
        },
        changePublic: function (ispublic) {
            if (this.publicdoc != ispublic) {
                this.getClassDocList(ispublic, 0, true, (success, data) => {
                    this.loading = false;
                    if (success) {
                        this.parseDocListRet(success, data);
                        let tmp = this.index;
                        this.onPageChange(this.otherpageindex);
                        this.otherpageindex = tmp;
                    }
                });
            }
            this.publicdoc = ispublic;
            this.searchkey = '';
            if (this.publicdoc && g_data.env == 'exp'){   // 体验版本禁止上传课件到公共课件库
              this.showUpload = false;
            }else{
              this.showUpload = true;
            }
        },
        onPageChange: function (index) {
            this.index = index;
            --index;
            const start = index * 5;
            let end = start + 5;
            if (end > this.wholelist.length && this.wholelist.length < this.total) {
                ++this.fetchDocIndex;
                // todo
                // this.getClassDocList(this.publicdoc, this.fetchDocIndex, (success, data) => {
                //     if (success) {
                //         this.parseDocListRet(success, data);
                //     }
                // });
            } else {
                end = end > this.doclist.length ? this.doclist.length : end;
                this.showdoclist = this.doclist.slice(start, end);
            }
        },
        getRandomIndex: function() {
            return -1 * (Math.floor(Math.random() * Math.floor(1000)) + 1);
        },
        upload: function () {
            this.$refs.upload_file.click();
        },
        uploadchange: function() {
            if (!this.$refs.upload_file.value) {
                return;
            }
            let file = this.$refs.upload_file.files[0];
            this.$refs.upload_file.value = null;
            let ext = this.getfileext(file.name);
            let validext = ['doc', 'docx', 'pdf', 'ppt', 'pptx', 'jpg', 'png'];
            if (validext.indexOf(ext) == -1) {
                this.showDialog("仅支持ppt，pptx，pdf，doc，docx，jpg，png文件上传", ['确定'], null);
            }else if (fs.statSync(file.path).size == 0){
                this.showDialog("不能上传空文件", ['确定'], null);
            }else {
                this.getFileInfoAndUpload(file);
            }
        },
        getFileInfoAndUpload: function(file) {
            var self = this;
            let rs = fs.createReadStream(file.path);
            let hash = crypto.createHash('md5');
            this.is_file_uploading = true;
            rs.on('data', hash.update.bind(hash));
            rs.on('end', function () {
                self.updateFile(file, hash.digest('hex'));
            });
        },
        removeuploadFile(index) {
            for (let i = 0; i < this.uploading_doc.length; ++i) {
                if (this.uploading_doc[i].doc_index === index) {
                    this.uploading_doc.splice(i, 1);
                    break;
                }
            }
            for (let i = 0; i < this.wholelist.length; ++i) {
                if (this.wholelist[i].doc_index === index) {
                    this.wholelist.splice(i, 1);
                    break;
                }
            }
            this.total -= 1;
        },
        updateFile: function(file, md5) {
            var self = this;
            let index = this.getRandomIndex();
            let item = {
                doc_index: index,
                doc_name: file.name.replace("+", "_"),
                doc_size: this.getfilesize(file.size),
                doc_type: this.getfiletype(file.name),
                upload_time: '',
                transcode_status: '上传中',
                percent: 0,
                is_public: this.publicdoc,
            }
            if (item.doc_name.length > 15) {
                let ext = this.getfileext(item.doc_name);
                item.doc_name = item.doc_name.slice(0, 10) + '....' + ext;
            }
            this.wholelist.unshift(item);
            this.doclist = this.wholelist;
            this.total += 1;
            this.uploading_doc.push(item);
            this.onPageChange(1);
            this.cos.sliceUploadFile({
                Bucket: this.bucket,
                Region: "ap-shanghai",
                Key: file.name.replace("+", "_"),
                Body: file,
                onProgress: (progressData) => {
                    log.info("[TAG-UPLOAD] sliceUploadFile:onProgress->" + JSON.stringify(progressData));
                    item.transcode_status = '上传中(' + Number(progressData.percent*100).toFixed(1) + '%)';
                }
            }, (err, data) => {
                if (!data){
                    this.showAlertMsg("上传课件失败!");
                    log.error("[TAG-UPLOAD] sliceUploadFile->error: "+JSON.stringify(err));
                    return;
                }
                log.info("[TAG-UPLOAD] sliceUploadFile->data:" + JSON.stringify(data));
                self.uploadBussinessDoc(file, md5, "https://" + data.Location, (ret, data) => {
                    self.removeuploadFile(index);
                    self.is_file_uploading = this.uploading_doc.length != 0;
                    if (ret) {
                        if (self.is_window_show){   // 窗口显示则刷新，否则直接关闭
                            self.refresh();
                        }else if (!self.is_file_uploading){
                            sendIpcMessage('WIN_DOCLIST:CLOSE', g_data.classId);
                        }
                    } else {
                        this.showDialog("上传课件" + (ret ? "成功" : "失败"), [], null);
                        self.onPageChange(1);
                    }
                });
            });
        },
        uploadBussinessDoc: function(file, md5, location, callback) {
            let is_transcode = this.getfiletype(file.name) != 1;
            let new_filename = file.name;
            if (new_filename.length > 15) {
                let ext = this.getfileext(new_filename);
                new_filename = new_filename.slice(0, 10) + '....' + ext;
            }
            let data = JSON.stringify({
                doc_name: new_filename,
                doc_url: decodeURI(location),
                doc_ext: this.getfileext(file.name),
                doc_size: file.size,
                doc_md5: md5,
                permission: this.publicdoc ? "public" : "private",
                is_transcode: is_transcode,
            });
            var reqUrl = getServerDomain() + "/saas/v1/document/add?sdkappid=" + g_data.sdkAppId + "&user_id=" + g_data.userId + "&token=" + g_data.token + "&random=" + Math.floor(Math.random() * 10000);
            log.info("[TAG-BUS] uploadBussinessDoc->url: " + reqUrl);
            log.info("[TAG-BUS] uploadBussinessDoc->req: " + data);
            $.ajax({
                headers: {
                    "Content-Type": "application/json"
                },
                type: "POST",
                url: reqUrl,
                data: data,
                success: function (json) {
                    log.info("[TAG-BUS] uploadBussinessDoc->rsp: " + JSON.stringify(json, null, 2));
                    if (json && json.error_code === 0) {
                        callback(true, json);
                    } else {
                        callback(false, JSON.stringify(json));
                    }
                },
                error: function (xhr, status, err) {
                    callback(false, "", xhr.status + ': ' + xhr.statusText);
                    log.info("[TAG-UPLOAD] uploadBussinessDoc->error: " + xhr.status + ': ' + xhr.statusText);
                }
            });
        },
        getfilesize: function (size) {
            if (!size)
                return "";
            const num = 1024.00;
            if (size < num)
                return size + "B";
            if (size < Math.pow(num, 2))
                return (size / num).toFixed(2) + "K";
            if (size < Math.pow(num, 3))
                return (size / Math.pow(num, 2)).toFixed(2) + "M";
            if (size < Math.pow(num, 4))
                return (size / Math.pow(num, 3)).toFixed(2) + "G";
            return (size / Math.pow(num, 4)).toFixed(2) + "T";
        },
        timestampToString: function (timestamp) {
            let date = new Date();
            date.setTime(timestamp * 1000);
            const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: 'numeric', minute: 'numeric' };
            return date.toLocaleDateString('chinese', options);
        },
        getfiletype: function (filename) {
            if (!filename) {
                return 0;
            }
            let ext = this.getfileext(filename);
            const img = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'];
            const ppt = ['ppt', 'pptx'];
            const doc = ['doc', 'docx'];
            const vid = ['mp4', 'mp4', 'avi', 'mpeg', 'mpg'];
            if (img.indexOf(ext) !== -1) {
                return 1;
            } else if (ppt.indexOf(ext) !== -1) {
                return 2;
            } else if (doc.indexOf(ext) !== -1) {
                return 3;
            } else if (ext === 'pdf') {
                return 4;
            } else if (vid.indexOf(ext) !== -1) {
                return 5;
            } else {
                return 0;
            }
        },
        getfileext: function(filename) {
            if (!filename || filename.indexOf('.') == -1) {
                return '';
            }
            let index = filename.lastIndexOf('.');
            let ext = filename.substr(index + 1).toLowerCase();
            return ext;
        },
        iconpath: function (type) {
            switch (type) {
                case 1:
                    return '../img/setting_filetype_img.png';
                case 2:
                    return '../img/setting_filetype_ppt.png';
                case 3:
                    return '../img/setting_filetype_doc.png';
                case 4:
                    return '../img/setting_filetype_pdf.png';
                case 5:
                    return '../img/setting_filetype_vid.png';
                case 0:
                default:
                    return '../img/setting_filetype_img.png';
            }
        },
        onDlgClick: function(index){
            this.is_show_dialog = false;
            this.is_show_msg = false;
            if (null != this.dialog_callback){
                this.dialog_callback(index);
            }          
        },
        showDialog: function(message, buttons, callback){
          this.dialog_title = '课件管理';
          this.dialog_msg = message,
          this.dialog_button = buttons;
          this.dialog_callback = callback;
          this.is_show_dialog = true;
          this.is_show_msg = true;
        },
        showAlertMsg: function(message){
            this.showDialog(message, ['确定'], null);
        },
        parseDocListRet(success, data) {
            if (success) {
                this.handleDoccList(data.list);
                for (let item of this.uploading_doc) {
                    if (item.is_public == this.publicdoc) {
                        this.doclist.unshift(item);
                    }
                }
                this.total = this.doclist.length;
                this.showdoclist = this.doclist.slice(0, 5);
                this.wholelist = this.doclist;
                this.setNoData(this.total == 0);
            }
        },
        getClassDocList(common, index, showloading, callback) {
            this.loading = showloading;
            if (showloading) 
                this.setNoData(false);
            var data = JSON.stringify({
                owner: common ? "" : g_data.userId,
                index: index,
                size: 100,
            });
            var reqUrl = getServerDomain() + "/saas/v1/document/list?sdkappid=" + g_data.sdkAppId + "&user_id=" + g_data.userId + "&token=" + g_data.token + "&random=" + Math.floor(Math.random() * 10000);
            log.info("[TAG-BUS] getClassDocList->url: "+reqUrl);
            log.info("[TAG-BUS] getClassDocList->req: "+data);
            $.ajax({
                headers: {
                    "Content-Type": "application/json"
                },
                type: "POST",
                url: reqUrl,
                data: data,
                success: function (json) {
                  log.info("[TAG-BUS] getClassDocList->rsp: "+JSON.stringify(json, null, 2));
                  if (json && json.error_code === 0) {
                      callback(true, json);
                  } else {
                      callback(false, JSON.stringify(json));
                  }
                },
                error: function (xhr, status, err) {
                    callback(false, "", xhr.status + ': ' + xhr.statusText);
                    log.info("[TAG-BUS] getClassDocList->error: " + xhr.status + ': ' + xhr.statusText);
                }
            });
        },
        deleteClassDoc(docId, callback){
            var data = JSON.stringify({
                doc_ids: [docId]
            });
            var reqUrl = getServerDomain() + "/saas/v1/document/delete?sdkappid=" + g_data.sdkAppId + "&user_id=" + g_data.userId + "&token=" + g_data.token + "&random=" + Math.floor(Math.random() * 10000);
            log.info("[TAG-BUS] deleteDoc->url: "+reqUrl);
            log.info("[TAG-BUS] deleteDoc->req: "+data);
            $.ajax({
                headers: {
                    "Content-Type": "application/json"
                },
                type: "POST",
                url: reqUrl,
                data: data,
                success: function (json) {
                  log.info("[TAG-BUS] deleteDoc->rsp: "+JSON.stringify(json));
                  if (json && json.error_code === 0) {
                      callback(true, json);
                  } else {
                      callback(false, JSON.stringify(json));
                  }
                },
                error: function (xhr, status, err) {
                    callback(false, "", xhr.status + ': ' + xhr.statusText);
                    log.info("[TAG-BUS] deleteDoc->error: " + xhr.status + ': ' + xhr.statusText);
                }
            });
        },
        handleDoccList(doclist) {
            this.doclist = [];
            let index = 0;
            for (let doc of doclist) {
                let processed = {
                    doc_id: doc.doc_id,
                    doc_index: index,
                    doc_name: doc.doc_name,
                    doc_size: this.getfilesize(doc.doc_size),
                    doc_size_origin: doc.doc_size,
                    doc_type: this.getfiletype(doc.doc_name),
                    upload_time: this.timestampToString(doc.upload_time),
                    transcode_status: '完成',
                    doc_url: doc.doc_url,
                    is_transcode: doc.is_transcode,
                    transcode_result: doc.transcode_result,
                    doc_width: doc.doc_width,
                    doc_height: doc.doc_height,
                    pages: doc.pages
                }
                if (processed.doc_name.length > 15) {
                    let ext = this.getfileext(processed.doc_name);
                    processed.doc_name = processed.doc_name.slice(0, 10) + '....' + ext;
                }
                if (doc.is_transcode) {
                    if (doc.transcode_status == 'prepared' || doc.transcode_status == 'queued') {
                        processed.transcode_status = '准备';
                    }else if (doc.transcode_status == 'processing') {
                        processed.transcode_status = '转码中';
                    }else if (doc.transcode_status == 'finished' && doc.transcode_result === '') {
                        processed.transcode_status = '转码失败';
                    }
                }
                this.doclist.push(processed);
                ++index;
            }
        },
        selectDoc(index) {
            if (index < 0 || index >= this.wholelist.length) return;
            let doc = this.wholelist[index];
            if (doc.is_transcode && doc.transcode_status != '完成') {
                return;
            }
            sendIpcMessage('CLASS:OpenDoc',  doc);
            sendIpcMessage('WIN_DOCLIST:CLOSE', g_data.classId);
        },
        deleteDoc(docId){            
            this.showDialog("确认要删除课件吗?", ["确认", "取消"], (index)=>{
                if (index == 0){
                    log.info("[TAG-DOC] deleteDoc->docId: "+docId);
                    this.deleteClassDoc(docId, (ret, json)=>{                        
                        this.refresh();
                        this.showDialog("删除课件"+(ret?"成功":"失败"), ['确定'], null);
                    });
                }
            });
        },
        setNoData(visible) {
            if (visible) {
                this.nodata_t1 = '您的课件列表为空，您可以';
                this.nodata_t2 = '「上传」';
                this.nodata_t3 = '一个课件到这里';
            }else {
                this.nodata_t1 = '';
                this.nodata_t2 = '';
                this.nodata_t3 = '';
            }
        },
        getCosAuth(callback) {
            var self = this;
            let req = JSON.stringify({
                cmd: "open_cos_svc",
                sub_cmd: "get_cos_token",
                duration: 300,
                version: 1
            });
            $.ajax({
                headers: {
                    "Content-Type": "application/json"
                },
                type: "POST",
                url: "https://yun.tim.qq.com/v4/ilvb_edu/cos?SdkAppId=" + g_data.sdkAppId + "&AccountType=35615&Identifier=" + g_data.userId + "&UserSig=" + g_data.userSig,
                data: req,
                success: function (rsp) {
                    var json = rsp;
                    if (json && json.error_code == 0) {
                        log.info("[TAG-UPLOAD]  getCosAuth->success: " + JSON.stringify(json));
                        callback(true, json);
                    } else {
                        log.error("[TAG-UPLOAD]  getCosAuth->req: " + JSON.stringify(req));
                        log.error("[TAG-UPLOAD]  getCosAuth->failed: " + JSON.stringify(json));
                        callback(false, JSON.stringify(json));
                    }
                },
                error: function (xhr, status, err) {
                    callback(false, "" + xhr.status + ': ' + xhr.statusText);
                    log.info("[TAG-UPLOAD] getMemberList->error: " + xhr.status + ': ' + xhr.statusText);
                }
            });
        },
    }
})

ipcRenderer.on('show', function (e, data) {
  classdoc_app.onWindowShow(data);
})

ipcRenderer.on('hide', function (e, data) {
  classdoc_app.onWindowHide(data);
})
