Vue.config.devtools = true;

function getQueryVariable(variable)
{
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if(pair[0] == variable){return pair[1];}
    }
    return(false);
}


var v = new Vue({
    el: ".container",
    data: {
        form:{
            fileName:'',
            downloadPath:'',
            fileSize:''
        },
        // 上传文件
        isLogin: false,
        memToken: '',
        memHeadImg: '',
        fileUrl: 'https://files.qkyxzx.com/',
        fileList: [], // 文件列
        showProgress: false, // 进度条的显示
        limit: 1, // 视频条数
        progress: 0, // 进度条数据
        ossClient: null, // oss
        clientJs: null,
        num:'',
        dayNum :'',
        page: 1,
        size: 12,
        total: 0,
        list: []
    },
    created: function () {
        if ($.cookie("memToken")) {
            this.memToken = $.cookie("memToken");
            this.isLogin = 1;
        }
        if ($.cookie("memHeadImg")) {
            this.memHeadImg = $.cookie("memHeadImg");
        }
        if (!checkWebLogin()) {
            // $('.navlogorebox').trigger('click')
            return false;
        }
        this.getIndexData();
        this.client();
        this.getFileNameUUID();
        this.day();
    },
    methods: {
        handleSizeChange(val) {
            this.page = val
            this.getIndexData()
        },
        handleCurrentChange(val) {
            this.page = val
            this.getIndexData()
        },
        getIndexData() {
            var that = this;
            $.ajax({
                type: 'get',
                url: serverHttp + "/courseware/getlistData/forme",
                data: {
                    page: that.page,
                    size: that.size,
                    belongBrandid: getQueryVariable("productId"),
                    memToken: that.memToken
                },
                success: function (data) {
                    if (data.code == 200) {
                        that.list = data.data;
                        that.total = data.totalCount
                    }
                }
            });
        },
        uploadDel(id){
            var that = this;
            $.ajax({
                type: 'post',
                url: serverHttp + "/courseware/delete",
                data: {
                    courseWareId: id,
                    memToken: that.memToken
                },
                success: function (data) {
                    if (data.code == 200) {
                        that.$confirm('是否确认删除', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            that.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            that.page = 1
                            that.getIndexData()
                        }).catch(() => {
                            that.$message({
                                type: 'info',
                                message: '已取消删除'
                            });
                        });
                    }
                }
            });
        },
        uploadDown(id) {
            window.location.href = serverHttp + "/courseware/downFile/ppt/web?id=" + id
        },
        addCourseware(){
            this.fileList = [];
            this.form.fileName = '';
            this.form.downloadPath = '';
            this.form.fileSize = '';
            this.showProgress = false
            this.progress = 0
            $(".addUploadMask").show();
        },
        courseClose(){
            $(".addUploadMask").hide();
        },
        onSubmit(){
            var that = this;
            if(that.form.fileName == '' ||
                that.isEmptyStr(that.form.fileName.trim()) ||
                that.form.downloadPath == ''){
                layer.msg("请完善信息");
                return;
            }
            $.ajax({
                type: 'POST',
                url: serverHttp + "/courseware/add",
                data: {
                    memToken: that.memToken,
                    belongBrandid: getQueryVariable("productId"),
                    fileName: that.form.fileName,
                    downloadPath: that.form.downloadPath,
                    fileSize: that.form.fileSize,
                },
                success: function (data) {
                    if (data.code == 200) {
                        $(".el-upload-list").empty();
                        that.fileList = [];
                        that.form.fileName = '';
                        that.form.downloadPath = '';
                        that.form.fileSize = '';
                        that.showProgress = false
                        that.progress = 0
                        $(".addUploadMask").hide();
                        that.page = 1
                        that.getIndexData();
                    }
                },
                error: function (data) {
                }
            });
        },
        isEmptyStr (str) {
            if ( str == "" ) return true;
            var regu = "^[ ]+$";
            var re = new RegExp(regu);
            return re.test(str);
        },
        lenMin(text, num) {
            if (text.length >= num) {
                layer.msg('最大不超过' + num + '个字符');
            }
        },
        client() {
            var that = this;
            that.clientJs = new OSS.Wrapper({
                // region: 'oss-cn-beijing.aliyuncs.com',
                region: 'oss-cn-beijing',
                accessKeyId: 'LTAI5tHTG5eNAC7pmoqUDghi',
                accessKeySecret: 'K8aZK7RWhqw4LdkP9MtwiC7Rq0avwt',
                bucket: 'qkj-web',
                secure: true
            })
        },
        // 生成随机文件名称  规则八位随机字符，加下划线连接时间戳
        getFileNameUUID(){
            function rx() {
                return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
            }
            this.num = `${+new Date()}_${rx()}${rx()}`
        },
        day() {
            var nowDate = new Date()
            var date = {
                year: nowDate.getFullYear(),
                month: nowDate.getMonth() + 1,
                day: nowDate.getDate()
            }
            this.dayNum = date.year + (date.month >= 10 ? date.month : '0' + date.month) + (date.day >= 10 ? date.day : '0' + date.day)
        },
        // 文件超出个数限制时的钩子
        handleExceed(files, fileList) {
            this.$message.warning(`每次只能上传 ${this.limit} 个文件`)
        },
        // 点击文件列表中已上传的文件时的钩子
        handlePreview(file) {},
        // 删除文件之前的钩子
        beforeRemove(file, fileList) {
            // return this.$confirm(`确定移除11 ${file.name}？`)
        },
        // 文件列表移除文件时的钩子
        handleRemove(file, fileList) {
            this.showProgress = false
            this.progress = 0
            // this.form.fileName = ''
            this.form.downloadPath = ''
            this.form.fileSize = ''
            // if (this.ossClient != null) {
            //     this.clientJs.cancel()
            // }
        },
        // 文件上传成功时的钩子
        handleSuccess(response, file, fileList) {
            this.fileList = fileList
        },
        // 文件上传前的校验
        beforeAvatarUpload(file) {
            var suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
            if (suffix.indexOf('ppt') === -1) {
                this.$message.error('请上传ppt格式文件(ppt、pptx)，上传文件大小不能超过100M!')
                return false
            }
            var isLt100M = file.size / 1024 / 1024 > 0 && file.size / 1024 / 1024 < 100
            if (!isLt100M) {
                this.$message.error('上传文件大小不能超过100M!')
                return false
            }
        },
        // http-request属性来覆盖默认的上传行为（即action="url"），自定义上传的实现
        Upload(file) {
            const that = this
            async function multipartUpload() {
                const temporary = file.file.name.lastIndexOf('.')
                const fileNameLength = file.file.name.length
                const fileFormat = file.file.name.substring(
                    temporary + 1,
                    fileNameLength
                )
                const fileName = that.num + '.' + fileFormat
                const day = that.dayNum
                that.ossClient = that.clientJs.multipartUpload(`courseware/${day}/${fileName}`, file.file).then(res => {
                    // that.showProgress = true
                    // that.progress = 100
                    // 上传成功返回值
                    const url = that.fileUrl + res.name
                    that.form.downloadPath = url
                    that.form.fileSize = file.file.size
                })
            }
            multipartUpload()
        },
    }
})
