/**科汛图片组件 */
Vue.component('KsImage', {
    props: {
        /**图片地址 */
        src: String,
        /**图片类型 defailt | user | logo */
        type: String,
        /*图片如何适应到容器框*/
        fit: {
            type: String,
            default: "cover"
        }
    },
    data: function () {
        var _defaultImg = "/ks_inc/member-center/images/default/default-img.png";
        switch (this.type) {
            case "user":
                _defaultImg = "/ks_inc/member-center/images/default/default-avatar.jpg";
                break;
            case "logo":
                _defaultImg = "/ks_inc/member-center/images/default/default-logo.png";
                break;
            case "exam":
                _defaultImg = "/ks_inc/member-center/images/default/testpsck_bg.png";
                break;
        }
        return {
            imgSrc: this.src,
            defaultImg: _defaultImg
        }
    },
    methods: {
        /**
         * 处理图片加载出错
         */
        onerror: function () {

            this.imgSrc = this.defaultImg;

        }
    },
    watch: {
        src: function (_imgSrc) {

            this.imgSrc = _imgSrc;
        }
    },
    template: '<div class="ks-image"  @click="$emit(\'click\',$event)">' +
        '<img style="width: 100%; height: 100%;" :src="imgSrc" @error="onerror" :style="{objectFit:fit}" />' +
        '<slot />' +
        '</div>'
})
/**个人中心标题组件 */
Vue.component('KsTitle', {
    props: {
        /**标题 */
        title: String,
        /**下划线开关 */
        underline: {
            default: true,
            type: Boolean,
        }
    },
    data: function () {

        return {

        }

    },
    template: '<div class="ks-title" :class="{underline:underline==true}">{{title}}</div>',

})


/**考试学习图表组件 */
Vue.component('echarts', {
    props: {
        width: {
            type: Number,
        },
        height: {
            type: Number,
        },
        dataList: {
            type: Array,
            default: function () {
                return []
            }
        },
        title: String,
        titleColor: String,
        grid: {
            type: Object,
            default: function () {
                return {
                    top: '12%',
                    bottom: '12%',
                    left: '6%',
                    right: '4%'
                }
            }
        },
        axisLine: {
            type: Boolean,
            default: true
        },
        areaStyle: {
            type: Object,
            default: function () {
                return {
                    color: 'rgb(255,255,255)'
                }
            }
        },
        smooth: {
            type: Boolean,
            default: true
        },
        itemType: {
            type: String,
            default: '1'
        }
    },
    data: function () {
        return {
            canvas: '',
            echarts: {
                title: {
                    text: this.title,
                    textStyle: {
                        fontSize: 16,
                        color: this.titleColor,
                        fontWeight: 400
                    }
                },
                backgroundColor: '#FFF',
                grid: {
                    top: this.grid.top,
                    bottom: this.grid.bottom,
                    left: this.grid.left,
                    right: this.grid.right
                },
                tooltip: {
                    trigger: 'axis',
                    label: {
                        show: true
                    }
                },
                xAxis: {
                    boundaryGap: true, //默认，坐标轴留白策略
                    axisLine: {
                        show: this.axisLine
                    },
                    splitLine: {
                        show: false
                    },
                    axisTick: {
                        show: false,
                        alignWithLabel: true
                    },
                    data: [
                        '还没有学习记录'
                    ]
                },
                yAxis: {
                    axisLine: {
                        show: this.axisLine
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            type: 'dashed',
                            color: 'rgba(210,225,251,1)'
                        }
                    },
                    axisTick: {
                        show: false
                    },
                    splitArea: {
                        show: true,
                        areaStyle: {
                            color: this.areaStyle.color
                        }
                    }
                },
                series: {
                    type: 'line',
                    symbol: 'circle',
                    smooth: this.smooth,
                    symbolSize: 7,
                    lineStyle: {
                        color: 'rgb(60,129,249)',
                        shadowBlur: 12,
                        shadowColor: 'rgb(60,129,249,0.9)',
                        shadowOffsetX: 1,
                        shadowOffsetY: 1
                    },
                    itemStyle: {
                        color: 'rgb(60,129,249)',
                        borderWidth: 1,
                        borderColor: '#FFF'
                    },
                    label: {
                        show: false,
                        distance: 1,
                        emphasis: {
                            show: true,
                            offset: [25, -2],
                            //borderWidth:1,
                            // borderColor:'rgb(60,129,249)',
                            //formatter:'{bg|{b}\n数据量:{c}}',
                            backgroundColor: 'rgb(60,129,249)',
                            color: '#FFF',
                            padding: [10, 10, 10, 10],
                            //width:60,
                            // height: 30,
                            formatter: function (params) {
                                var name = params.name;
                                var value = params.data;
                                if (Math.floor(value / 60) == 0) {
                                    if (this.itemType === '1') {

                                        var str = '学习时间：' + value % 60 + '分钟'
                                    } else {
                                        var str = name + '\n学习时间：' + value % 60 + '分钟'
                                    }
                                } else {
                                    if (this.itemType === '1') {

                                        var str = '学习时间：' + Math.floor(value / 60) + '小时' + value % 60 + '分钟'
                                    } else {
                                        var str = name + '\n学习时间：' + Math.floor(value / 60) + '小时' + value % 60 + '分钟'
                                    }
                                }

                                return str;
                            },
                            rich: {
                                bg: {
                                    backgroundColor: {
                                        image: ''
                                    },
                                    width: 78,
                                    //height:42,
                                    color: '#FFF',
                                    padding: [20, 0, 20, 10]
                                },
                                br: {
                                    width: '100%',
                                    height: '100%'
                                }

                            }
                        }
                    },
                    data: [
                        0
                    ]
                }
            },

        }
    },
    watch: {
        'dataList': function (list) {
            var that = this
            if (typeof echarts === 'object') {
                that.ready(list)
            } else {
                var script = document.createElement('script');
                script.src = '/ks_inc/member-center/js/echart/echarts.min.js';
                script.onload = function () {
                    that.ready(list)
                }
                document.body.appendChild(script)

            }

        }
    },
    methods: {

        ready: function (list) {
            this.echarts.xAxis.data = []
            this.echarts.series.data = []
            var datax = []
            var datay = []
            if (list.length > 0) {
                for (var i = 0; i < list.length; i++) {
                    datax.push(list[i].date)
                }
                for (var n = 0; n < list.length; n++) {
                    datay.push(list[n].time)
                }
                this.echarts.xAxis.data = datax
                this.echarts.series.data = datay
            } else {
                this.echarts.xAxis.data = ['还没有学习记录']
                this.echarts.series.data = [0]
            }
            var that = this
            this.$nextTick(function () {

                var myChart = echarts.init(that.$refs.mainChart);
                // 绘制图表
                myChart.setOption(
                    that.echarts, true
                )
            })

        },
    },
    mounted: function () {

    },
    template: '<div class="echarts" ref="mainChart"></div>'

})


/**个人中心标题组件 */
Vue.component('ExamSort', {
    props: {
        sort: Boolean
    },
    data: function () {
        return {
            /**窗口开关 */
            visible: true,
        }
    },
    methods: {
        getExam: function (isrand) {
            this.$emit('openExam', isrand)
        },
        handleClose: function () {
            this.$emit('close')
            this.visible = true
        }
    },
    mounted: function () {

    },
    template: '<el-dialog title="选择做题模式" visible="visible" :before-close="handleClose" width="750px">' +
        '<div class="exam-sort">' +
        '<div class="exam-sort__box1" @click="getExam(0)">' +
        '<div class="exam-sort__box1-img"></div>' +
        '<p>顺序练习</p>' +
        '</div>' +
        '<div class="exam-sort__box2" @click="getExam(1)">' +
        '<div class="exam-sort__box2-img"></div>' +
        '<p>随机练习</p>' +
        '</div>' +
        '</div>' +
        '</el-dialog>',

})

/**个人中心证书组件 */
Vue.component('kszrender', {
    props: {
        ratio: {
            type: Number,
            default: 1
        },
        avatar: {
            type: Array,
            defailt: 1
        },
        nameText: {
            type: Array,
            defailt: 1
        },
        qrcode: {
            type: Array,
            defailt: 1
        },
        jsoninfo: {
            type: Array,
            defailt: 1
        },
        box: {
            type: Array,
            defailt: 1
        },
        canvasImg:String,
        backgroundimg: String,
        canvasImgId:Number
    },
    data: function () {
        return {
            state: "",
            qrcodes: "",
            picture: "",
        }
    },
    methods: {
        clickpreview: function () {
            var that = this
            var img = document.createElement('img')
            img.src = that.backgroundimg
            img.onload = function(){
            var zr = zrender.init(that.$refs.zrenderid, {
                renderer: 'canvas',       //渲染方式 支持'canvas','svg','vml'
                devicePixelRatio: 1,      //画布大小与容器大小之比，仅当 renderer 为 'canvas' 时有效
                width: that.box.width*2,            //画布宽度
                height: that.box.height*2,           //画布高度
            });
            var Image = new zrender.Image({
                shape: {},
                style: {
                    image: that.backgroundimg,
                    x: '0',
                    y: '0',
                    width: that.box.width*2,     
                    height: that.box.height*2,
                },
                z: 1
            });
            that.jsoninfo.map(function (res) {
                var val = res.value || ''
				var maxWidth = Math.max(res.width*2,res.size*2)
				var newVal = ''
				var w = 0;
				for(var i=0;i<val.length;i++){
				  var reg = /^[^\x00-\xff]$/
				  var str = val[i];
				  var strWidth = reg.test(str) ? res.size*2 : res.size;
				  
				  if(w+strWidth <= maxWidth){
					newVal += str
					w += strWidth
				  }else{
					newVal += '\n'+str
					w = strWidth
				  }
				}
                if(res.type == 'text' && res.iscustomize){
                    var text = new zrender.Text({
                      style: {
                        text:newVal,
                        x: res.x*2,
                        y: res.y*2,
                        fontSize: res.size*2,
                        // textLineHeight: 28, //字体行高
                        fontFamily: "华文仿宋",
                      },
                      z: 2
                    });
                    zr.add(text);
                  }
                  if(res.type == 'image' && res.iscustomize){
                     var qrcode = new zrender.Image({
                      shape: {},
                      style: {
                        image: res.value,
                        x: res.x*2,
                        y: res.y*2,
                        width: res.width*2,
                        height: res.height*2
                      },
                      z: 2
                    });
                    zr.add(qrcode);
                    zr.add(Image);
                  }
                  if(res.type == 'uqimage'){
                    var qrcode = new zrender.Image({
                      shape: {},
                      style: {
                        image:res.url,
                        x: res.x*2,
                        y: res.y*2,
                        width: res.width*2,
                        height: res.height*2
                      },
                      z: 2
                    });
                    zr.add(qrcode);
                    zr.add(Image);
                  }
              });
              that.getCanvas(zr).then(function (canvas) {
                setTimeout(function () {
                    var img = canvas.toDataURL('image/jpg');
                that.$emit('update:canvasImg',img)
                }, 500)
            })
          }
        },
        getCanvas: function (zr) {
            var that = this;
            return new Promise(function (resolve) {
                var canvas = zr.dom.querySelector('canvas');
                if (canvas) {
                    resolve(canvas)
                } else {
                    setTimeout(function () {
                        that.getCanvas(zr).then(function (canvas) {
                            resolve(canvas)
                        })
                    }, 500)
                }
            })
        }
    },
    mounted: function () {
        this.clickpreview()
    },
    template: '<div><div class="zrcred" ref="zrenderid" style="display:none"></div><el-image :src="canvasImg" :class="canvasImg ? \'credimg\':\'credimgss\' " v-loading="!canvasImg" :id="canvasImgId" /></el-image></div>',
})

/**无内容提示组件 */
Vue.component('KsEmpty', {
    props: {
        msg: String,
        type: String
    },
    data: function () {
        return {

        }
    },

    template: '<div class="ks-empty" :class="\'ks-empty--\'+(type || \'default\')">' +
        '{{msg}}' +
        '<slot />' +
        '</div>',

})

/**各种东西预览 */
Vue.component('media-preview', {
    name:'mediaPreview',
    props: {
        /**查看类型 image | video | audio */
        type: String,
        info: {
            type: Object,
            default:function() {
                return {};
            }
        },
        ispreview: {
            type: Boolean,
            default:function() {
                return true;
            }
        }
    },
    data:function(){
        return {

        }
    },
    methods: {
        //去除
        wipe:function(i) {
          this.info.list.splice(i, 1);
          var val = this.info.list
          this.$emit('getlist',val)
        },
    },
    mounted:function() {
        var val = this.info.list
        this.$emit('getlist',val)
    },
    template: '<div class="MediaPreview"><div class="preview-image mt10" v-if="type === \'image\'">' +
    '<div :class="info.list.length === 1 && \'atlas\'" style="width: 530px;">' +
    '<span v-for="(img,i) in info.list" :key="i" class="preview-span">' +
    '<img class="preview" :src="img.src" />' +
    '<i v-if="ispreview" class="el-icon-delete preview-span__i" @click="wipe(i)"></i></span></div></div>' +
    '<div class="preview-video mt10" v-else-if="type === \'video\'">' +
    '<div v-for="(img,i) in info.list" :key="i" class="preview-span">' +
    '<video class="video" :src="img.src" controls controlslist="nodownload" ></video>' +
    '<i v-if="ispreview" class="el-icon-delete preview-span__i" @click="wipe(i)"></i></div></div>' +
    '<div class="preview-video mt10" v-else-if="type === \'audio\'">'+
    '<div v-for="(img,i) in info.list" :key="i" class="preview-span">'+
    '<audio class="audio" :src="img.src" controls controlslist="nodownload" ></audio>'+
    '<i v-if="ispreview" class="el-icon-delete preview-span__i" @click="wipe(i)"></i></div></div>'+
    '<div class="preview-video mt10" v-else-if="type === \'word\'">' +
    '<div v-for="(img,i) in info.list" :key="i" class="preview-span">' +
    '<iframe :src="\'https://api.idocv.com/view/url?url=\'+ img.src" width="700" height="800" frameborder="no" border="0" marginwidth="0" marginheight="0" allowtransparency="yes">' +
    '<p>你的浏览器不支持。</p>' +
    '</iframe><i v-if="ispreview" class="el-icon-delete preview-span__i" @click="wipe(i)"></i></div></div></div>',
})

var editorIndex = 0;
var editorJsLoaded = false;
/**富文本组件 */
Vue.component('KsEditor', {
    props: {
        /**标题 */
        title: String,
        /**编辑器内容 */
        content: String,
        /**编辑器高度 */
        height: {
            type: Number,
            default: 100
        },
        /**字数限制 */
        maximumWords: {
            type: Number,
            default: 10000
        },
        /**是否开启字数统计 */
        wordCount: {
            type: Boolean,
            default: false
        },
        /**编辑器浮层高度 */
        zIndex: {
            type: Number,
            default: 9999
        }
    },
    model: {
        prop: "content",
        event: "change"
    },
    data: function () {
        editorIndex++;
        return {
            id: editorIndex
        };
    },
    mounted: function () {
        this.createEditor(this.id);
    },
    methods: {
        /**
         * 创建编辑器
         */
        createEditor: function (id) {
            var that = this
            this.editor = UE.getEditor('KsEditor' + id, {
                initialFrameWidth: "100%",
                initialFrameHeight: this.height,
                maximumWords: this.maximumWords,
                wordCount: this.wordCount,
                zIndex: this.zIndex,
                toolbars: [
                    [
                        "fullscreen",
                        "myinsertimage",
                        "|",
                        // "fontsize",
                        // "forecolor",
                        "bold",
                        "italic",
                        "underline",
                        "strikethrough",
                        "|",
                        "superscript",
                        "subscript",
                        "removeformat"
                    ]
                ]
            });
            /**修改图片点击操作 */
            this.editor.commands["myinsertimage"] = {
                execCommand: function () {
                    that.$uploadImages(function (res) {
                        that.editor.setContent('<img src="${res.defaultpic}" />', true);
                        var _content = that.editor.getContent();
                        that.$emit("change", _content);
                    });
                }
            };
            this.editor.addListener("ready", function (e) {
                that.editor.setContent(that.content);
                that.editor.addListener("blur", function (e) {
                    var _content = that.editor.getContent();
                    that.$emit("change", _content);
                });
            });
        }
    },
    watch: {
        content: function (_content) {
            this.editor.setContent(_content);
        }
    },
    template: '<div class="ks-editor"><div :id="\'KsEditor\'+id"></div></div>',
})


/**上传 */
Vue.component('ks-upload', {
    name:'FileUpload',
    props:{
        config:{
            type:Object,
            default:function(){
                return {}
            }
        }
    },
    data:function (){
        return {
            fileList3: [],/**图片数组 */
            imageUrl: '',/**图片数组 */
            fileUrl:this.url,/**上传数据 */
            // errpic: 'this.src="' + require('@/assets/common/nopic.png') + '"'
            loadProgress: 0, // 动态显示进度条
            progressFlag: false, // 关闭进度条
        }
    },
    methods:{
        handleAvatarSuccess:function(res, file) {
            // let resData = JSON.parse(res);
            let resData = res
            var that = this
            if(resData.result){
                if(that.config.type==1 || that.config.type==2){
                    // that.fileUrl = JSON.parse(file.response).fileUrl;
                    that.fileUrl = file.response.fileUrl;
                }else{
                    that.imageUrl = URL.createObjectURL(file.raw);
                }
                that.$emit('update:url',resData.fileUrl)
                that.$emit('uploaded',resData.fileUrl)
            }else{
                that.$message('上传失败');
            }
            
        },
        getSuffix:function(name){
            var index = name.lastIndexOf('.')
            suffix = name.substr(index)
            return suffix.toLowerCase()
        },
        beforeAvatarUpload:function(file) {
            var that = this
            var suffix = this.getSuffix(file.name)
            var fileTypes = that.config.fileType.split(',')
            if(that.config.type==1){
                var isLt30M = file.size / 1024 / 1024 < 30;
                if (!isLt30M) {
                    that.$message.error('上传文件大小不能超过 30MB!');
                    that.imageUrl = ''
                }
                return isLt30M;
            }else{
                if(that.config.fileType != '*'){
                 
                    var isok = fileTypes.indexOf(suffix) > -1;
                    if(!isok){
                        that.$message.error('上传文件只能是' + that.config.fileType + '格式!');
                        return false;
                    }
                }
            }
        },
        uploadVideoProcess(event, file, fileList) {
            this.progressFlag = true; // 显示进度条
            this.loadProgress = parseInt(event.percent); // 动态获取文件上传进度
            if (this.loadProgress >= 100) {
                this.loadProgress = 100
                setTimeout( () => {this.progressFlag = false}, 1000) // 一秒后关闭进度条
            }
        },
        handleChange:function(file, fileList) {
            this.fileList3 = fileList.slice(-3);
        }
    },
    mounted: function(){
        var that = this
        if(that.config.photo !='' ){
            that.imageUrl = that.config.photo
        }
        if(that.config.fileUrl !=''){
            that.fileUrl = that.config.fileUrl
        }
        if(that.config.important){
            that.fileUrl = ''
        }
      },
        template:'<div><div v-if="config.type==1"><el-input v-model="fileUrl" placeholder="" class="file-url" :style="config.width"></el-input>' +
        '<el-upload class="upload-demo" :action="config.actionUrl" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :accept="config.fileType || \'.PDF\'">'+
        '<el-button slot="trigger" size="small" type="primary" class="ml10">选择文件</el-button><span slot="tip" class="el-upload__tip ml10">{{config.name || \'不超过30M,支持pdf\'}}</span></el-upload></div>'+
        '<div v-else-if="config.type==2"><el-input disabled v-model="fileUrl" placeholder="" class="file-url" :style="config.width"></el-input>' +
        '<el-upload class="upload-demo" :on-progress="uploadVideoProcess" :action="config.actionUrl" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :accept="config.fileType || \'.jpg\'">' +    
        '<el-button slot="trigger" type="primary" class="ml10" :disabled="progressFlag">选择文件</el-button></el-upload>' +
        '<el-progress v-if="progressFlag" :percentage="loadProgress"></el-progress>'+
    '</div>' +
    '<div class="upload-img" :style="\'min-width:\'+config.width+\'px;\'" v-else>'+
        '<el-upload class="avatar-uploader" :action="config.actionUrl" :on-success="handleAvatarSuccess" accept=".jpg,.jpeg,.png,.gif" :before-upload="beforeAvatarUpload" :style="\'height:\'+config.height+\'px;\'">' +
            '<img v-if="imageUrl" :src="imageUrl" class="avatar" :style="\'min-height:\'+config.height+\'px;max-width:\'+config.width+\'px;\'" :alt="config.photo"><i v-else class="el-icon-plus avatar-uploader-icon" :style="\'height:\'+config.height+\'px;width:\'+config.width+\'px;line-height:\'+config.height+\'px;\'"></i></el-upload>' +
        '<div class="upload-img-tips">' +
            '<h3><span v-if="imageUrl">请点击更换</span>{{config.name || \'上传图片\'}}</h3>'+
            '<p>合适尺寸（{{config.size || \'200px*200px\'}}）</p>'+
        '</div>'+
    '</div>'+
'</div>'
})



/**支付组件 */
Vue.component('KsPay', {
    props: {
        msg: String,
        type: String,
        data: {
            type: Object,
            default: {}
        }
    },
    data: function () {
        return {
            userInfo: {},
            state: {},
            visible: true,
            activePay: -1,
            payId: 0,
            /**选择器选项 */
            options: [{
                value: '选项1',
                label: '全部'
            }, {
                value: '选项2',
                label: '按学习时间'
            }, {
                value: '选项3',
                label: '按更新时间'
            }],
            /**选择器默认值 */
            value: '全部',
            exchange: false,
        }
    },
    methods: {
        /**选择支付类型 */
        payType: function (i) {
            this.activePay = i
            if (i == -1) {
                this.payId = 0
            } else {
                this.payId = this.paymentList[i].payid
            }
        },
        /**支付 */
        pay: function () {
            this.$emit('pay', this.payId)

        },
    },
    mounted: function () {
        var that = this
        that.$store.ready(function (state) {
            that.userInfo = state.userInfo
            that.state = state
        })
    },
    template: '<el-dialog title="支付订单" :visible.sync="visible" width="800px">' +
        '<div class="ks-pay">' +
        '<div class="ks-pay__row">' +
        '<el-row :gutter="20">' +
        '<el-col :span=\'4\' style="width:180px">' +
        '<img style="width: 100%;height:100%" src="/ks_inc/member-center/images/account/rechargepsck_bg@2x.png" v-if="data.cardtype == 1" />' +
        '<img style="width: 100%;height:100%" src="/ks_inc/member-center/images/account/marketpsck_bg@2x.png" v-else />' +
        '</el-col>' +
        '<el-col :span=\'18\'>' +
        '<p style="color: #2F3133">' +
        '{{data.title}}' +
        '</p>' +
        '<p style="font-size: 14px;color:#888888;" v-if="type==1">' +
        '价格：<i style="font-size: 18px;color:#E91C35;font-style:normal">￥{{data.price}}</i>（原价:<i style="text-decoration:line-through;font-style:normal">{{data.price_market}}</i>）' +
        '</p>' +
        '<p style="font-size: 14px;color:#888888;" v-else-if="type==2">' +
        '早鸟票：<i style="font-size: 18px;color:#E91C35;font-style:normal">￥{{data.price}}</i>（活动报名）' +
        '</p>' +
        '</el-col>' +
        '</el-row>' +
        '<el-row :gutter="20" style="text-align: right;border-bottom: 1px solid #E6E9ED">' +
        '<el-col :span=\'8\' :offset="8">' +
        '<div v-if="type==1">' +
        '<p>金额：</p>' +
        '<p>订单总额：</p>' +
        '</div>' +
        '<div v-else-if="type==2">' +
        '<p>票务金额：</p>' +
        '<p>预付保证金<i style="font-style: normal;color:#cccccc">（签到后可线下退）</i>：</p>' +
        '<p>可用优惠券：</p>' +
        '<p v-if="exchange">&nbsp;</p>' +
        '<p>订单总额：</p>' +
        '</div>' +
        '</el-col>' +
        '<el-col :span=\'5\'>' +
        '<div v-if="type==1">' +
        '<p>￥{{data.price}}</p>' +
        '<p style="color: #E91C35;font-size:24px">￥{{data.price}}</p>' +
        '</div>' +
        '<div v-else-if="type==2">' +
        '<p>￥{{data.price}}</p>' +
        '<p>￥{{data.price}}</p>' +
        '<el-select style="line-height: 40px" v-model="value" placeholder="选择优惠券" size="medium">' +
        '<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">' +
        '</el-option>' +
        '</el-select>' +
        '<el-input v-if="exchange" style="line-height: 40px" placeholder="输入券号" size="medium"></el-input>' +
        '<p style="color: #E91C35;font-size:22px">￥{{data.price}}</p>' +
        '</div>' +
        '</el-col>' +
        '<el-col :span=\'3\' v-if="type==2">' +
        '<p style="margin-top: 80px;text-align: left;color: #3C81F9;cursor: pointer;" @click="exchange = exchange ? false : true">输入券号</p>' +
        '<el-button style="margin-top: 2px;" type="primary" size="medium" v-if="exchange">使用</el-button>' +
        '</el-col>' +
        '</el-row>' +
        '</div>' +
        '<h1>选择支付方式：</h1>' +
        '<div class="ks-pay__list">' +
        '<div class="ks-pay__item" :class="{\'active-pay\':activePay == -1}" @click="payType(-1)">' +
        '<span>余额支付</span>' +
        '<i v-if="activePay == -1"></i>' +
        '</div>' +
        '<div></div>' +
        '<div class="ks-pay__item" v-for="(item,i) in data.payment_list" :key="i" :class="{\'active-pay\':activePay == i}" @click="payType(i)">' +
        '<img :src="item.logo" />' +
        '<i v-if="activePay == i"></i>' +
        '</div>' +
        '</div>' +
        '<div class="ks-used">可用余额￥{{userInfo.Money}}</div>' +

        '<div class="ks-pay__btn">' +
        '<el-button type="warning" @click="pay()">立即支付</el-button>' +
        '</div>' +
        '</div>' +
        '</el-dialog>',

})

/**课程目录 */
Vue.component('catalog', {
    name:'catalog',
    props:{
        costype:{
            type:Number,
            default:0
        },
        courseid:{
            type:Number,
            default:0
        },
        courseType:{
            type:String,
            default:''
        }
    },
    data: function () {
        return {
            id:0,
            periods:[],
            allperiods:[],
            liveperiods:[],//组合课程的直播课时列表
            playperiods:[],//组合课程的点播课时列表
            faceperiods:[],//组合课程的面授课时列表
            returnperiods:[],//组合课程的回放课时列表
            periodunlockpercent:0
        }
    },
    watch:{
        costype:{
            handler(query){
                var that = this
                that.changeData()
            },
            deep:true
        }
    },
    methods: {
        
        getMsg: function (msg){
            this.$emit('msg',msg)
        },
        getInfo: function (info){
            info.ishide = !info.ishide
        },
        changeData:function () {
            if(this.costype=='1'){
                this.periods = this.playperiods
            }else if(this.costype=='5'){
                this.periods = this.liveperiods
            }else if(this.costype=='6'){
                this.periods = this.returnperiods
            }else if(this.costype=='0'){
                this.periods = this.faceperiods
            }else{
                this.periods = this.allperiods
            }
        },
        IntData: function (){
            var that = this
            getCourseCatalog({
                courseType:that.courseType,
                courseid:that.id,
                schoolid:0
            },that.$store.state.apiDomain).then(res=>{
                let arr = res.catalog
                if(res.periods&&res.periods.length){
                    that.$emit('periodsNum',res.periods.length)
                }
                
                that.periodunlockpercent = res.catalogData.Course.periodunlockpercent
                arr.map(item=>{
                    if(item.$childs){
                        item.ishide = false
                        if(item.$childs){
                            item.$childs.map(sitem=>{
                                sitem.ishide = false
                            })
                        }
                    }
                    if(item.teachWay=='5'){
                        console.log(item);
                        if(item.isbackplay){
                            that.returnperiods.push(item)
                        }else{
                            that.liveperiods.push(item)
                        }
                        
                    }else if(item.teachWay=='0'){
                        that.faceperiods.push(item)
                    }else if(item.teachWay=='1'){
                        that.playperiods.push(item)
                    }
                })
                that.periods = arr
                that.allperiods = arr
            })
            
        }
    },
    mounted: function () {
        this.id = this.courseid
        this.IntData()
    },
    template: '<div class="ks-catalog ks-catalog--default" v-if="periods && periods.length">'+
			'<div :class="\'ks-catalog-\'+chapter.$enname" v-for="(chapter,c) in periods" :key="c">'+
			'	<periods :costype="costype" :courseType="courseType" :objname="chapter" :courseid="id" :periodunlockpercent="periodunlockpercent" @msg="getMsg"></periods>'+
			'	<div v-if="chapter.$childs && !chapter.ishide">'+
			'		<div :class="\'ks-catalog-\'+section.$enname" v-for="(section,s) in chapter.$childs" :key="s">'+
			'			<periods :costype="costype" :courseType="courseType" :objname="section" :courseid="id" :periodunlockpercent="periodunlockpercent" @msg="getMsg"></periods>'+
			'			<div v-if="section.$childs && !section.ishide">'+
			'				<div class="ks-catalog-period" v-for="(period,p) in section.$childs" :key="p">'+
			'					<periods :costype="costype" :courseType="courseType" :objname="period" :courseid="id" :periodunlockpercent="periodunlockpercent" @msg="getMsg"></periods>'+
			'				</div>'+
			'			</div>'+
			'		</div>'+
			'	</div>'+
			'</div>'+
		'</div>'+
		'<ks-empty type="list" v-else>暂无数据</ks-empty>',

})


/**课时 */
Vue.component('periods', {
    name:'periods',
    props:{
        costype:{
            type:Number,
            default:0
        },
        courseid:{
            type:Number,
            default:0
        },
        objname:{
            type:Object,
        },
        courseType:{
            type:String,
            default:''
        },
        periodunlockpercent:{
            type:Number,
            default:0
        }
    },
    data: function () {
        return {
            id:0,
        }
    },
    methods: {
        open: function (item){
            console.log(item);
            if(item.$enname == 'period'){
                console.log(item.periodlock);
                if(item.periodlock=='true'){
                    this.$emit('msg','该课时需要上个课时学习达到'+periodunlockpercent+'%才能开启')
                    return false
                }else if(item.$isCanLearn==1||item.$isCanLearn==3){
                    if(item.$liveState == 0){
                        return false
                    }else{
                        window.open(item.url);
                    }
                }else{
                    this.$store.ready(state=>{
                        if(state.userInfo.UserID > 0){
                            //提示购买
                            this.$emit('msg','还未购买该课程，请先购买')
                        }else{
                            //跳去登录
                            window.open(state.url_login);
                        }
                    })
                }
            }
            
        },
        expand: function (){
            this.objname.ishide = !this.objname.ishide
        },
    },
    mounted: function () {
        this.id = this.courseid
    },
    template: '<div class="ks-catalog-title" @click="open(objname)">'+
                '<div class="ks-catalog-title__th" :class="objname.$url && \'ks-catalog-title__th--pointer\'">'+
                    '   <div v-if="objname.$enname == \'period\'">'+
                    '	   <div class="ks-catalog-title__lock" v-if="objname.periodlock == \'true\'" :style="\'background-image: url(/KS_Inc/member-center/images/catalog/lesson_icon_lock.png);\'"></div>'+
                    '	   <div v-if="objname.$showLiveTime" :class="\'ks-catalog-title__time ks-catalog-title__type-live\'" :style="\'background: url(/KS_Inc/member-center/images/catalog/lesson_icon_live.png) no-repeat 100% 50%;\'">'+	
                    '			<span v-if="objname.$liveState == 0" style="font-size: 10px;"> {{objname.$livetime}} ~ {{objname.$invaliddate}}</span>'+
                    '			<span v-else-if="objname.$liveState == 1" style="font-size: 10px;">'+
                    '				正在直播'+
                    '			</span>'+
                    '			<span v-else-if="objname.$liveState == 2" style="font-size: 10px;">'+
                    '				无限次播放'+
                    '			</span>'+
                    '	   </div>'+
                    '	   <div v-else-if="courseType == \'face\'">'+
                    '		   <div v-if="objname.isfree == 1">'+
                    '				<div class="ks-catalog-title__money"></div>'+
                    '		   </div>'+
                    '		   <div v-else-if="objname.$money" class="ks-catalog-title__money">¥{{objname.$money}}</div>'+
                    '		   <div v-if="objname.starttime" class="ks-catalog-title__time">开课时间：{{objname.starttime}} - {{objname.endtime}}</div>'+
                    '	   </div>'+					
                    '	   <div v-else :class="\'ks-catalog-title__time ks-catalog-title__type\'+objname.type" :style="(objname.type==0&&\'background: url(/KS_Inc/member-center/images/catalog/lesson_icon_video.png) no-repeat 100% 50%;\')||(objname.type==1&&\'background: url(/KS_Inc/member-center/images/catalog/lesson_icon_audio.png) no-repeat 100% 50%;\')||(objname.type==2&&\'background: url(/KS_Inc/member-center/images/catalog/lesson_icon_picture.png) no-repeat 100% 50%;\')||(objname.type==3&&\'background: url(/KS_Inc/member-center/images/catalog/lesson_icon_pdf.png) no-repeat 100% 50%;\')||(objname.type==\'-live\'&&\'background: url(/KS_Inc/member-center/images/catalog/lesson_icon_live.png) no-repeat 100% 50%;\')">{{objname.$duration}}</div>'+
                    '   </div>'+
                    '   <div class="ks-catalog-title__arrow" v-if="objname.$childs" :style="objname.ishide?\'background: url(/KS_Inc/member-center/images/catalog/common_icon_pullup.png) no-repeat 50% 50%;\':\'background: url(/KS_Inc/member-center/images/catalog/common_icon_pulldown.png) no-repeat 50% 50%;\'" @click="expand"></div>'+
                    '   <span class="ks-catalog-title__periodname">{{objname.$unit}}：{{objname.periodname}}</span>'+
                    '   <span class="ks-catalog-learnednum" v-if="objname.$enname == \'chapter\'||objname.$enname == \'section\'">{{objname.$learnednum}}/{{objname.$periodnum}}课时</span><div class="sprogress" v-if="objname.$enname == \'chapter\'||objname.$enname == \'section\'"><el-progress color="#3C81F9" :stroke-width="4" :show-text="false" :percentage="Math.round(objname.$learnednum/objname.$periodnum*100)"></el-progress></div>'+
                    '   <div v-if="objname.$isCanLearn == 3" class="ks-catalog-title__try ks-tag ks-tag--small ks-tag--primary">试看</div>'+
                '</div>'+
                '<div v-if="objname.$enname == \'period\' && objname.$btns.length">'+
                    '	<div class="ks-catalog-title__btns">'+
                    '		<a :class="\'ks-catalog-title__btn \'+bt.className" v-for="(bt,b) in objname.$btns" :key="b" :style="(bt.type==0&&\'background-image: url(/KS_Inc/member-center/images/catalog/lesson_icon_lx.png)\')||(bt.type==1&&\'background-image: url(/KS_Inc/member-center/images/catalog/lesson_icon_record.png)\')||(bt.type==2&&\'background-image: url(/KS_Inc/member-center/images/catalog/lesson_icon_down.png)\')">{{bt.text}}</a>'+
                    '	</div>'+
                    '	<div class="ks-catalog-schedule" v-if="objname.haslearnpercent > 0">'+
                    '	    <div class="ks-catalog-schedule__learned" :style="{width: objname.haslearnpercent+\'%\'}"></div>'+
                    '	</div>'+
                '</div>'+
            '</div>',

})