<template>
    <div class="choose-content">
        <Tabs :value="tabName" type="card" name="chooseContent" @on-click="clickTab">
            <!-- 选择课纲内容 -->
            <TabPane label="课纲" name="syllabus" v-if="showSyllabus" tab="chooseContent">
                <div class="tab-wrap">
                    <div class="content-filter-wrap">
                        <div class="content-filter-item">
                            <span class="content-filter-label">课纲范围：</span>
                            <RadioGroup v-model="syllabusFilter.type" style="display:inline-block;" @on-change="getVolumes">
                                <Radio :label="1" class="radio-width">个人课纲</Radio>
                                <Radio :label="0" class="radio-width">校本课纲</Radio>
                            </RadioGroup>
                        </div>
                        <div class="content-filter-item" v-if="$store.state.user.schoolProfile.school_base">
                            <span class="content-filter-label">学段：</span>
                            <RadioGroup v-model="syllabusFilter.periodId" style="display:inline-block;" @on-change="getSubjectList">
                                <Radio class="radio-width" :key="index" v-for="(item,index) in $store.state.user.schoolProfile.school_base.period" :label="item.id">{{item.name}}</Radio>
                            </RadioGroup>
                        </div>
                        <div class="content-filter-item">
                            <span class="content-filter-label">学科：</span>
                            <RadioGroup v-model="syllabusFilter.subjectId" style="display:inline-block;" @on-change="getVolumes">
                                <Radio class="radio-width" v-for="(item,index) in subjectList" :label="item.id" :key="index">{{item.name}}</Radio>
                            </RadioGroup>
                        </div>
                    </div>
                    <div class="syllabus-content-wrap">
                        <div class="volume-list-wrap">
                            <p class="volume-list-label">
                                <Icon type="md-bookmarks" color="#fff" size="20" />
                                <span style="margin-left:5px;">册别</span>
                            </p>
                            <div :class="index == currentVolumeIndex ? 'volume-item-active volume-item':'volume-item'" v-for="(item,index) in volumeList" :key="index" @click="selectVolume(index)">
                                <p class="volume-name">{{item.volumeName}}</p>
                                <div class="volume-relation-num">
                                    <Icon type="md-folder" title="内容资源数" style="margin-left:0" /> 8
                                    <Icon type="md-cube" title="关联知识点数" /> 10
                                    <Icon type="md-git-branch" title="节点数" /> 15
                                </div>
                            </div>
                            <EmptyData v-if="volumeList.length == 0"></EmptyData>
                        </div>
                        <div class="syllabus-tree-wrap">
                            <!--<Tree  :data="syllabusList"></Tree>-->
                            <div class="syllabus-title-wrap">
                                <Icon type="ios-book" size="22" style="margin-right:5px;" />
                                <span>{{volumeList.length > 0 ? volumeList[currentVolumeIndex].volumeName:'暂无数据'}}</span>
                            </div>
                            <el-tree v-if="syllabusList.length != 0" :data="syllabusList" :props="defaultProps" style="width:100%;" show-checkbox></el-tree>
                            <EmptyData v-if="syllabusList.length == 0"></EmptyData>
                        </div>
                    </div>
                </div>
            </TabPane>
            <!-- 选择资源文件 -->
            <TabPane label="内容" name="content" v-if="showContent" tab="chooseContent">
                <div class="tab-wrap">
                    <div class="content-filter-wrap">
                        <div class="content-filter-item">
                            <span class="content-filter-label">资源范围：</span>
                            <RadioGroup v-model="contentFilter.scope" style="display:inline-block;" @on-change="getFileList">
                                <Radio label="private" class="radio-width">个人资源</Radio>
                                <Radio label="school" class="radio-width">校本资源</Radio>
                            </RadioGroup>
                        </div>
                        <div class="content-filter-item">
                            <span class="content-filter-label">类型：</span>
                            <RadioGroup v-model="contentFilter.fileType" style="display:inline-block;" @on-change="getFileList">
                                <Radio class="radio-width" :key="index" v-for="(item,index) in contentTypeList" :label="item.type">{{item.label}}</Radio>
                            </RadioGroup>
                        </div>
                        <Input v-model="keyWord" class="seach-input" suffix="ios-search" placeholder="关键字搜索" clearable style="width: 240px" size="small" @on-change="searchKeyWord" />
                    </div>
                    <div class="file-content-wrap">
                        <Table ref="fileTable" :columns="fileColumns" :data="fileListShow" max-height="660" class="animated fadeIn" @on-select="selectFile" @on-select-cancel="cancelSelectFile" @on-select-all="selectAllFile" @on-select-all-cancel="cancelSelectAllFile">
                            <template slot-scope="{ row, index }" slot="size">
                                <div>
                                    {{row.size/1024 > 1024 ? (row.size/1024/1024).toFixed(1) + 'M': (row.size/1024).toFixed(1) + 'KB'}}
                                </div>
                            </template>
                            <template slot-scope="{ row, index }" slot="createTime">
                                <div>
                                    {{formatDate(row.createTime)}}
                                </div>
                            </template>
                            <template slot-scope="{ row, index }" slot="name">
                                <div>
                                    <div class="file-icon">
                                        <img v-if="row.extension == 'PPT' || row.extension == 'PPTX'" src="../../assets/icon/ppt50.png" width="15" />
                                        <img v-else-if="row.extension == 'DOC' || row.extension == 'DOCX'" src="../../assets/icon/word50.png" width="15" />
                                        <img v-else-if="row.extension == 'XLS' || row.extension == 'XLSX' || row.extension == 'CSV'" src="../../assets/icon/xls50.png" width="15" />
                                        <img v-else-if="row.extension == 'PDF'" src="../../assets/icon/pdf50.png" width="15" />
                                        <img v-else-if="row.extension == 'ZIP' || row.extension == 'RAR'" src="../../assets/icon/zip50.png" width="15" />
                                        <img v-else-if="row.type == 'image'" src="../../assets/icon/icon_img.png" width="15" />
                                        <img v-else-if="row.type == 'video'" src="../../assets/icon/icon_video.png" width="15" />
                                        <img v-else-if="row.type == 'res'" src="../../assets/icon/htex.png" width="15" />
                                        <img v-else src="../../assets/icon/prelearn50.png" width="15" />
                                    </div>
                                    <span style="margin-left:8px;vertical-align: text-bottom;">{{row.name}}</span>
                                </div>
                            </template>
                        </Table>
                    </div>
                </div>
            </TabPane>
            <!-- 选择题库 -->
            <TabPane label="题目" name="question" v-if="showQuestion" tab="chooseContent">
                <div class="tab-wrap">
                    <vuescroll>
                        <ExerciseList ref="exListRef" @chooseQuChange="chooseQuChange"></ExerciseList>
						<!-- <BaseExerciseList></BaseExerciseList> -->
                    </vuescroll>
                </div>
            </TabPane>
			<!-- 选择试卷 -->
			<TabPane label="试卷" name="paper" v-if="showPaper" tab="chooseContent">
			    <div class="tab-wrap">
			        <vuescroll>
						<BasePaperList ref="paperListRef" chooseModel @previewPaper="onPreviewPaper"></BasePaperList>
			        </vuescroll>
			    </div>
			</TabPane>
        </Tabs>
    </div>
</template>
<script>
import JSONPath from 'jsonpath'
import BlobTool from '@/utils/blobTool.js'
import E from '@/utils/wangEditor.js'
import ExerciseList from '@/components/selflearn/ExerciseList.vue'
import BasePaperList from '@/view/evaluation/bank/TestPaperList.vue'
import BaseExerciseList from '@/view/evaluation/bank/ExerciseList.vue'
export default {
    components: {
        ExerciseList,
		BasePaperList,
    },
    props: {
        questionSize: {
            type: Number,
            default: 100
        },
        showSyllabus: {
            type: Boolean,
            default: true
        },
        showContent: {
            type: Boolean,
            default: true
        },
        showQuestion: {
            type: Boolean,
            default: true
        },
		showPaper: {
		    type: Boolean,
		    default: true
		},
        showOther: {
            type: Boolean,
            default: true
        },
        //默认选中文件
        defaultFiles: {
            type: Array,
            default: () => {
                return [
                    // {
                    //     url: 'https://teammodelstorage.blob.core.chinacloudapi.cn/hbcn/audio/sound/001.mp3'
                    // }
                ]
            }
        }
    },
    data() {
        return {
			tabName:'content',
            questionList: [],
            pageNum: 1,
            pageSize: 20,
            questionConfig: {
                showSelect: true
            },
            isLoading: false,
            exersicesDiff: this.$GLOBAL.EXERCISE_DIFFS(),
            questionFilter: {
                code: '',
                type: ['all'],
                level: ['all'],
                periodId: '',
                subjectId: '',
                gradeIds: []
            },
            syllabusFilter: {
                type: 1,
                periodId: '',
                subjectId: '',
                status: 1,
                code: this.$store.state.userInfo.schoolCode,
                TEAMModelId: this.$store.state.userInfo.TEAMModelId
            },
            syllabusList: [],
            volumeList: [],
            subjectList: [],
            defaultProps: {
                children: 'children',
                label: 'title'
            },
            contentFilter: {
                scope: 'private',
                fileType: 'image'
            },
            keyWord: '',
            contentTypeList: [
                // {
                //     label: '教材',
                //     type: 'res',
                // },
                {
                    label: this.$t('teachContent.filterPicture'),
                    type: 'image',
                },
                {
                    label: this.$t('teachContent.filterVideo'),
                    type: 'video',
                },
                {
                    label: '音频',
                    type: 'audio',
                },
                {
                    label: this.$t('teachContent.filterDoc'),
                    type: 'doc',
                },
                {
                    label: this.$t('teachContent.filterOther'),
                    type: 'other',
                }
            ],
            fileList: {
                school: {
                    res: [],
                    image: [],
                    video: [],
                    audio: [],
                    doc: [],
                    other: []
                },
                private: {
                    res: [],
                    image: [],
                    video: [],
                    audio: [],
                    doc: [],
                    other: []
                }
            },
            selectedFiles: [],
            fileListShow: [],
            searchBefore: [],
            fileColumns: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: this.$t('teachContent.tableC1'),
                    slot: 'name',
                },
                {
                    title: this.$t('teachContent.tableC4'),
                    slot: 'size',
                    width: 150,
                    align: 'center',
                    sortable: true
                },
                {
                    title: this.$t('teachContent.tableC6'),
                    slot: 'createTime',
                    width: 200,
                    sortable: true
                }
            ],
        }
    },
    methods: {
		onPreviewPaper(paper){
			this.$emit('previewPaper',paper)
		},
        //选择题目
        chooseQuChange(qus){
            this.$emit('quChange',qus)
        },
        //初始化数据
        initData() {
            this.questionFilter.code = this.$store.state.userInfo.TEAMModelId
            this.$store.dispatch('user/getSchoolProfile').then(res => {
                if (res.school_base) {
                    this.questionFilter.periodId = res.school_base.period[0].id
                    this.questionFilter.subjectId = res.school_base.period[0].subjects[0].id
                    this.questionFilter.gradeIds = [res.school_base.period[0].grades[0].id]
                }
            })
        },
        /**
         * 选择全部逻辑
         * @param data:选中数据
         * @param field:字段名
         */
        checkAll(data, field) {
            if (this.questionFilter[field].length !== 1 && this.questionFilter[field].indexOf('all') === 0) {
                this.questionFilter[field].splice(this.questionFilter[field].indexOf('all'), 1)
            } else if (this.questionFilter[field].indexOf('all') > 0) {
                this.questionFilter[field].length = 0
                this.$set(this.questionFilter[field], 0, 'all')
            }
            this.pageNum = 1
            this.getResultCount()
            this.queryQuestionByPage()
        },
        deleteAll(data) {
            if (data.length == 1) {
                if (data[0] == 'all') {
                    return []
                } else {
                    return data
                }
            } else {
                return data
            }
        },
        /**
         * 获取题库数量
         */
        getResultCount() {
            let findCountParams = {
                "collectionName": "ItemInfo",
                "queryDict": {
                    'code': this.questionFilter.code,
                    'periodId': this.questionFilter.periodId == "" ? [] : [this.questionFilter.periodId],
                    'level': this.deleteAll(this.questionFilter.level),
                    'type': this.deleteAll(this.questionFilter.type),
                    'gradeIds[*]': this.questionFilter.gradeIds,
                    'subjectId': this.questionFilter.subjectId == "" ? [] : [this.questionFilter.subjectId],
                    'field': [],
                }
            }
        },
        /**
         * 选择学科、学段后刷新
         * */
        refreshQuestionList() {
            this.pageNum = 1
            this.getResultCount()
            this.queryQuestionByPage()
        },
        //题库学科筛选条件
        getQSubjectList() {
            let result = JSONPath.query(this.$store.state.user.schoolProfile.school_base.period, "$..[?(@.id=='" + this.questionFilter.periodId + "')]")
            if (result.length > 0) {
                this.subjectList = result[0].subjects
                if (this.subjectList.length > 0) {
                    this.questionFilter.subjectId = this.subjectList[0].id
                    this.refreshQuestionList()
                }
            } else {
                this.subjectList.length = 0
            }
        },
        /**
         * 分页查询题目
         */
        queryQuestionByPage() {
            let queryData = {
                //'@CURRPAGE': this.pageNum,
                //'@PAGESIZE': this.pageSize,
                '@DESC': "createTime",
                'code': this.questionFilter.code,
                'scope': this.questionFilter.code == this.$store.state.userInfo.TEAMModelId ? 'private' : 'school',
                'periodId': this.questionFilter.periodId == "" ? [] : [this.questionFilter.periodId],
                'level': this.deleteAll(this.questionFilter.level),
                'type': this.deleteAll(this.questionFilter.type),
                'gradeIds[*]': this.questionFilter.gradeIds,
                'subjectId': this.questionFilter.subjectId == "" ? [] : [this.questionFilter.subjectId],
            }
            this.isLoading = true
            this.$api.newEvaluation.FindExerciseList(queryData).then(res => {

                /* 拿到Summary的题目之后要通过每个题目的JSON URL 换取完整题目数据 */
                let list = res.items
                this.$evTools.getFullItem(list).then(
                    (res) => {
                        this.questionList = res
                    },
                    (err) => {
                        this.$Message.error('题库获取失败')
                    }
                )


            }).finally(() => {
                setTimeout(() => {
                    this.isLoading = false
                }, 500)
            })
        },
        //Tab切换事件
        clickTab(name) {
			console.log(name)
			this.tabName = name
            switch (name) {
                case 'content':
                    this.getFileList()
                    break
                case 'question':
                    this.queryQuestionByPage()
                    break
                default:
                    break
            }
        },
        formatDate(timestamp) {
            let date = new Date(timestamp)
            return date.toLocaleString()
        },
        //处理文件选中状态
        handleCheckStatus() {
            this.$nextTick(() => {
                let urls = this.selectedFiles.map(item => { return item.url })
                for (let i in this.$refs.fileTable.$refs.tbody.objData) {
                    if (this.selectedFiles.length) {
                        if (urls.indexOf(this.$refs.fileTable.$refs.tbody.objData[i].url) > -1) {
                            this.$refs.fileTable.$refs.tbody.objData[i]._isChecked = true
                        } else {
                            this.$refs.fileTable.$refs.tbody.objData[i]._isChecked = false
                        }
                    } else {
                        this.$refs.fileTable.$refs.tbody.objData[i]._isChecked = false
                    }
                }
            })
        },
        //处理选择文件事件
        selectFile(selection, row) {
            row.scope = this.contentFilter.scope
            this.selectedFiles.push(row)
            this.$emit('on-file-change', {
                files: this.selectedFiles
            })
        },
        cancelSelectFile(selection, row) {
            for (let i in this.selectedFiles) {
                if (this.selectedFiles[i].url == row.url) {
                    this.selectedFiles.splice(i, 1)
                    break
                }
            }
            this.$emit('on-file-change', {
                files: this.selectedFiles
            })
        },
        selectAllFile(selection) {
            this.$Message.warning('暂未处理全选功能')
            //let str = JSON.stringify(this.selectedFiles)
            //for (let i in selection) {
            //    if (str.indexOf(selection[i]) == -1) {
            //        this.selectedFiles.push(selection[i])
            //    } else {
            //        console.log()
            //    }
            //}
            //this.$emit('on-file-change', {
            //    files: this.selectedFiles
            //})
        },
        cancelSelectAllFile(selection) {
            this.$Message.warning('暂未处理取消全选功能')
        },
        /**
         * 关键字搜索文件
         * */
        searchKeyWord() {
            if (this.keyWord === '') {
                this.fileListShow = this.searchBefore
            } else {
                let searchResult = this.searchBefore.filter(item => {
                    return item.name.indexOf(this.keyWord) !== -1
                })
                this.fileListShow = searchResult
            }
        },
        /**
         * 通过文件类型筛选文件
         * */
        filterContentByType() {
            this.model = []
            this.fileListShow = []
            this.fileListShow = this.fileList[this.contentFilter.scope][this.contentFilter.fileType]
            this.searchBefore = this.fileListShow
            this.keyWord = ''
            this.handleCheckStatus()
        },
        //获取文件列表
        async getFileList() {
            if (this.fileList[this.contentFilter.scope][this.contentFilter.fileType].length == 0) {
                let sasRes
                if (this.contentFilter.scope == 'private') {
                    sasRes = await this.$tools.getPrivateSas()
                } else if (this.contentFilter.scope == 'school') {
                    sasRes = await this.$tools.getSchoolSas()
                }
                if (sasRes) {
                    let op1 = new BlobTool(sasRes.url, sasRes.name, sasRes.sas, this.contentFilter.scope)
                    op1.listBlob({
                        prefix: this.contentFilter.fileType
                    }).then(
                        (res) => {
                            this.fileList[this.contentFilter.scope][this.contentFilter.fileType] = res.blobList
                            this.fileListShow = this.fileList[this.contentFilter.scope][this.contentFilter.fileType]
                            this.searchBefore = [...this.fileListShow]
                            this.handleCheckStatus()
                        },
                        (err) => {
                            this.$Message.error('API Error')
                        }
                    )
                } else {
                    this.$Message.error('获取Blob授权信息失败')
                }
            } else {
                this.fileListShow = this.fileList[this.contentFilter.scope][this.contentFilter.fileType]
                this.searchBefore = [...this.fileListShow]
                this.handleCheckStatus()
            }
        },

        selectVolume(index) {
            this.currentVolumeIndex = index
            this.volumeCode = this.volumeList[this.currentVolumeIndex].volumeCode
            this.getSyllabus()
        },
        //获取区班校基础数据
        getSchoolBaseInfo() {
            this.$store.dispatch('user/getSchoolProfile').then(
                res => {
                    if (res.school_base) {
                        if (res.school_base.period.length > 0) {
                            this.syllabusFilter.periodCode = res.school_base.period[0].id
                            this.subjectList = res.school_base.period[0].subjects
                            if (this.subjectList.length > 0) {
                                this.syllabusFilter.subjectCode = this.subjectList[0].subjectCode
                            }
                        }
                    } else {
                        // this.$Message.warning('尚未加入学校，没有学校相关信息')
                    }
                }
            )

            //this.getVolumes()
        },
        //获取册别
        getVolumes() {
            this.currentVolumeIndex = 0
            this.$api.syllabus.GetVolumes(this.syllabusFilter).then(
                (res) => {
                    if (res.error == null) {
                        this.volumeList = res.volumes
                        if (this.volumeList.length == 0) {
                            this.syllabusList.length = []
                        } else {
                            this.volumeCode = this.volumeList[this.currentVolumeIndex].volumeCode
                            this.getSyllabus()
                        }
                    } else {
                        this.$Message.error('API error111！')
                    }
                },
                (err) => {
                    this.$Message.error('API error222！')
                }
            )
        },
        //获取课纲
        getSyllabus() {
            this.$api.syllabus.GetTreeByVolume({
                code: this.volumeCode
            }).then(
                (res) => {
                    if (!res.error) {
                        this.syllabusList = res
                    } else {
                        this.$Message.error('API error！')
                    }
                },
                (err) => {
                    this.$Message.error('API error！')
                }
            )
        },
        //课纲学科筛选条件
        getSubjectList() {
            let result = JSONPath.query(this.$store.state.user.schoolProfile.school_base.period, "$..[?(@.id=='" + this.syllabusFilter.periodId + "')]")
            if (result.length > 0) {
                this.subjectList = result[0].subjects
                if (this.subjectList.length > 0) {
                    this.syllabusFilter.subjectId = this.subjectList[0].id
                    this.getVolumes()
                }
            } else {
                this.subjectList.length = 0
                this.volumeList.length = 0
                this.syllabusList.length = 0
            }
        },
    },
    mounted() {
        setTimeout(() => {
            this.initData()
        }, 1500)
    },
    created() {
        Date.prototype.toLocaleString = function () {
            return this.getFullYear() + "/" + (this.getMonth() + 1) + "/" + this.getDate();
        }
        this.getSchoolBaseInfo()
    },
    watch: {
        defaultFiles: {
            handler() {
                this.selectedFiles = [...this.defaultFiles]
                this.handleCheckStatus()
            },
            deep: true,
            immediate: true
        }
    }
}
</script>
<style lang="less" scoped>
@import "./ChooseContent.less";
</style>
<style lang="less">
.choose-content
    .ivu-tabs.ivu-tabs-card
    > .ivu-tabs-bar
    .ivu-tabs-nav-container {
    height: auto;
}

.choose-content .ivu-tabs.ivu-tabs-card > .ivu-tabs-bar .ivu-tabs-tab {
    padding-top: 3px;
    height: auto;
}

.choose-content .ivu-tabs-bar {
    border-color: #404040;
}

.choose-content .ivu-tabs.ivu-tabs-card > .ivu-tabs-bar .ivu-tabs-tab {
    border: none;
    background-color: transparent;
    color: white;
    margin-right: 2px;
}

.choose-content .ivu-tabs.ivu-tabs-card > .ivu-tabs-bar .ivu-tabs-tab-active {
    background-color: #606060;
    color: white;
    font-weight: 600;
}

.choose-content .ivu-tabs,
.choose-content .ivu-tabs .ivu-tabs-content-animated {
    height: 100%;
}

.choose-content .ivu-tabs-bar {
    margin-bottom: 0px;
}

.volume-relation-num .ivu-icon {
    margin-left: 15px;
}

.syllabus-tree-wrap .el-tree {
    color: white;
    background: none;
    padding-top: 10px;
    padding-bottom: 100px;
}

.syllabus-tree-wrap .el-tree-node__content {
    height: 50px;
}

.syllabus-tree-wrap .el-tree-node__content:hover {
    height: 50px;
    background: #313131;
}

.syllabus-tree-wrap .el-tree-node:focus > .el-tree-node__content {
    background: #313131;
}

.syllabus-tree-wrap .el-tree__empty-block {
    display: none;
}

.file-content-wrap .ivu-table,
.file-content-wrap .ivu-table td,
.file-content-wrap .ivu-table th,
.content-file-list .ivu-table:before {
    background: none;
    color: white;
    border-color: #424242;
}

.file-content-wrap .ivu-table-row-hover .item-tools {
    opacity: 1;
    transition: opacity 1s;
}

.file-content-wrap .ivu-table-row-hover {
    background: #303030;
}

.file-content-wrap .ivu-table:before {
    height: 0px;
}

.content-filter-wrap .ivu-input {
    background: none;
    color: white;
    border-color: #606060;
    border-radius: 15px;
}

.file-content-wrap .ivu-table-overflowY {
    &::-webkit-scrollbar {
        /*滚动条整体样式*/
        width: 5px; /*高宽分别对应横竖滚动条的尺寸*/
        height: 1px;
    }

    &::-webkit-scrollbar-thumb {
        /*滚动条里面小方块*/
        -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        background: rgb(124, 124, 124);
    }

    &::-webkit-scrollbar-track {
        /*滚动条里面轨道*/
        -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        background: rgba(68, 68, 68, 0.5);
    }
}
</style>