<template>
    <div class="syllabus-tree-main">
        <vuescroll>
            <el-tree :data="treeDatas"
                     :props="defaultProps"
                     class="tree"
                     node-key="id"
                     default-expand-all
                     @node-drop="handleDrop"
                     :draggable="editable">
                <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span class="tree-node-lable">
                        {{data.title}}
                        <Icon type="md-images" :title=" '关联资源数:' + (data.resources ? data.resources.length : 0)" @click.stop="onShowContent('resource',data)" />
                        <span class="node-info-num" @click.stop="onShowContent('resource',data)">{{ data.resources ? data.resources.length : 0 }}</span>
                        <Icon type="md-cube" :title=" '关联题目数:' + (data.items ? data.items.length : 0)" @click.stop="onShowContent('question',data)" />
                        <span class="node-info-num" @click.stop="onShowContent('question',data)">{{ data.items ? data.items.length : 0 }}</span>
                    </span>
                    <span class="custom-tree-tools" v-if="editable">
                        <Icon v-show="data.pid !== 'Root'" type="ios-folder-open" size="20" title="内容" @click="onRelatedContent(node,data,$event)" />
                        <Icon v-show="data.pid !== 'Root'" type="md-create" size="20" title="编辑" @click="onEditItem(node,data,$event)" />
                        <Icon type="md-add" size="22" title="添加" @click="onAddNode(data,$event)" />
                        <Icon v-show="data.pid !== 'Root'" type="md-remove" size="22" title="删除" @click="remove(node,data)" />
                    </span>
                </span>
            </el-tree>
        </vuescroll>

        <!-- 新增或者编辑弹窗 -->
        <Modal v-model="isEditOrAdd" width="500" footer-hide class="tree-modal">
            <div class="modal-header" slot="header">{{ isEditItem ? '编辑节点':'新增节点'}}</div>
            <div class="modal-content">
                <p class="node-title">父节点</p>
                <Input v-model="nodeInfo.parent" style="width: 100%" disabled />
                <p class="node-title">节点名称</p>
                <Input v-model="nodeInfo.title" placeholder="请输入节点名称..." style="width: 100%" />
            </div>
            <Button @click="onSubmitNode" class="modal-btn">确认</Button>
        </Modal>

        <!-- 关联内容弹窗 -->
        <Modal v-model="isRelatedContent" width="880" footer-hide class="tree-modal related-modal">
            <div class="modal-header" slot="header">内容关联 （ 当前节点：{{ currentEditData ? currentEditData.title : '' }} ）</div>
            <ChooseContent 
                           @on-file-change="onSelectFile"></ChooseContent>

            <Button class="modal-btn" @click="onSaveNode" :loading="isLoading">确认</Button>
        </Modal>

        <!-- 关联内容弹窗 -->
        <Modal v-model="isShowContent" width="880" footer-hide class="tree-modal tree-content-modal related-modal">
            <div class="modal-header" slot="header">已关联内容</div>
            <Tabs :value="contentIndex">
                <TabPane :label="'资源文件( ' + currentResources.length + ' )'" icon="md-folder" name="resource">
                    <div v-if="currentResources.length === 0">
                        <EmptyData :top="30"></EmptyData>
                    </div>
                    <div class="tree-content-resource-box" v-else>
                        <div class="resource-item"
                             v-for="(item,index) in currentResources" :key="index">
                            <div class="resource-item-img">
                                <img v-if="item.extension === 'ppt'||item.extension === 'pptx'" src="@/assets/icon/ppt50.png" width="40" />
                                <img v-else-if="item.extension === 'doc'||item.extension === 'docx'" src="@/assets/icon/word50.png" width="40" />
                                <img v-else-if="item.extension === 'xls'||item.extension === 'xlsx'" src="@/assets/icon/xls50.png" width="40" />
                                <img v-else-if="item.type === 'picture'" src="@/assets/icon/icon_img.png" width="40" />
                                <img v-else-if="item.type === 'video'" src="@/assets/icon/icon_video.png" width="40" />
                                <img v-else-if="item.extension === 'rar'" src="@/assets/icon/zip50.png" width="40" />
                                <img v-else src="@/assets/icon/prelearn50.png" width="40" />
                            </div>
                            <div class="resource-item-name">
                                <Tooltip>
                                    <p class="file-name">{{ item.fileName }}</p>
                                    <div slot="content" class="file-info">
                                        <p><span>文件名：</span>{{item.fileName}}</p>
                                        <p><span>大小：</span>{{item.size/1024 > 1024 ? (item.size/1024/1204).toFixed(1) + 'M': (item.size/1024).toFixed(1) + 'KB'}}</p>
                                        <p><span>上传时间：</span>{{new Date(item.createTime/10000).toLocaleString()}}</p>
                                    </div>
                                </Tooltip>
                            </div>
                        </div>
                    </div>
                </TabPane>
                <TabPane :label="'题目( ' + currentItems.length + ' )'" icon="md-cube" name="question">
                    <div v-if="currentItems.length === 0">
                        <EmptyData :top="30"></EmptyData>
                    </div>
                    <div class="tree-content-resource-box" v-else>
                        <vuescroll>
                            <BaseQuestionList :items="currentItems"></BaseQuestionList>
                        </vuescroll>
                    </div>
                </TabPane>
            </Tabs>

            <Button class="modal-btn" @click="onSaveNode" :loading="isLoading">确认</Button>
        </Modal>
    </div>
</template>

<script>
    import '@/utils/Math.uuid'
    import BaseResource from '@/view/syllabus/newSyllabus/operation/BaseResource'
    import BaseKnowledge from '@/view/syllabus/newSyllabus/operation/BaseKnowledge'
    import BaseQuestionList from '@/common/BaseQuestionList'
    import ChooseContent from '@/components/selflearn/NewChooseContent'
    export default {
        props: ['volume', 'treeData', 'editable'],
        components: { BaseResource, BaseKnowledge, ChooseContent,BaseQuestionList },
        data() {
            return {
                isFalse: false,
                treeDatas: [],
                questionList: [],
                fileList: [],
                defaultProps: {
                    children: 'children',
                    label: 'title'
                },
                isEditOrAdd: false,
                isLoading: false,
                isRelatedContent: false,
                isShowContent: false,
                isEditItem: false,
                contentIndex: '1',
                currentVolume: null,
                currentEditData: null,
                currentParentData: null,
                currentResources: [],
                currentItems: [],
                nodeInfo: {
                    id: null,
                    title: '',
                    expand: true,
                    editable: true,
                    version: '',
                    type: 1,
                    children: [],
                    remark: '',
                    nodeKey: '',
                    pid: '',
                    code: '',
                    status: 1,
                    parent: ''
                }
            }
        },
        created() {
            console.log(this.volume)
        },
        methods: {
            // 拖拽完成回调
            handleDrop(draggingNode, dropNode, dropType) {
                switch (dropType) {
                    case 'before':
                        draggingNode.data.pid = dropNode.data.pid
                        break
                    case 'inner':
                        draggingNode.data.pid = dropNode.data.id
                        break
                    case 'after':
                        draggingNode.data.pid = dropNode.data.pid
                        break
                    default:
                        break
                }
                this.$parent.hasModify = true
            },

            // 删除节点操作
            remove(node, data) {
                this.$Modal.confirm({
                    title: '删除节点',
                    content: '<p>确认删除该节点？</p>',
                    okText: '确认',
                    cancelText: '取消',
                    onOk: () => {
                        const parent = node.parent
                        const children = parent.data.children || parent.data
                        const index = children.findIndex(d => d.id === data.id)
                        children.splice(index, 1)
                        this.$Message.success('删除成功')
                        this.$parent.hasModify = true
                    }
                })
            },

            // 点击添加展开弹窗
            onAddNode(data, e) {
                e.stopPropagation() // 防止点击事件穿透到父层
                this.isEditItem = false
                this.isEditOrAdd = true

                this.currentParentData = data // 当前点击节点即为父节点
                this.nodeInfo.parent = data.title
                this.nodeInfo.title = ''
            },

            // 编辑节点操作
            onEditItem(node, data, e) {
                e.stopPropagation() // 防止点击事件穿透到父层
                this.isEditOrAdd = true
                this.isEditItem = true

                this.currentEditData = data
                this.nodeInfo.parent = node.parent.data.title
                this.nodeInfo.title = node.data.title
            },


            onRelatedContent(node, data, e) {
                e.stopPropagation() // 防止点击事件穿透到父层
                this.isRelatedContent = true
                this.currentEditData = data
            },

            onShowContent(val, data) {
				console.log(data)
                this.contentIndex = val
                this.currentItems = []
                this.currentResources = []
                // data.items.length && this.findQuestionById(data.items)
                data.resources.length && this.findResourceById(data.resources)
                this.isShowContent = true
            },

            /**
             * 通过id查询内容信息
             * */
            findResourceById(ids) {

                this.$api.learnActivity.FindSyllabusResourceById(ids).then(
                    res => {
                        if (!res.error) {
                            this.currentResources = res.result.data
                        } else {
                            this.$Message.error("API ERROR")
                        }
                    },
                    err => {
                        this.$Message.error("API ERROR")

                    }
                )

            },
            /**
             * 通过id查询题目信息
             * */
            findQuestionById(ids) {
                this.$api.learnActivity.FindQuestionById(ids).then(
                    res => {
                        if (!res.error) {
                            this.currentItems = res.result.data
                        } else {
                            this.$Message.error("API ERROR")
                        }
                    },
                    err => {
                        this.$Message.error("API ERROR")

                    }
                )
            },


            // 提交编辑或者新增
            onSubmitNode() {
                if (!this.nodeInfo.title) {
                    this.$Message.warning('节点名称不能为空')
                    return
                }
                if (this.isEditItem) {
                    this.currentEditData.title = this.nodeInfo.title
                } else {
                    let newChild = Object.assign({}, this.nodeInfo) // 创建新节点
                    let parentNode = this.currentParentData
                    newChild.id = Math.uuid()
                    newChild.nodeKey = newChild.id
                    newChild.pid = parentNode.id
                    newChild.code = parentNode.code
                    newChild.children = []
                    newChild.resources = []
                    newChild.knowledges = []
                    if (!this.currentParentData.children) {
                        this.$set(this.currentParentData, 'children', [])
                    }
                    this.currentParentData.children.push(newChild)
                }

                this.isEditOrAdd = false
                this.$parent.hasModify = true
                this.$Message.success(this.isEditItem ? '编辑成功' : '添加成功')
            },


            /**
             * 选择关联题目
             * @param val 当前已选题目
             */
            onSelectQuestion(val) {
                this.questionList = val.questions
            },

            /**
             * 选择关联内容
             * @param val 当前已选内容
             */
            onSelectFile(val) {
                this.fileList = val.files
				console.log(val)
            },

            /** 保存内容与题目关联 */
            onSaveNode() {
                this.isLoading = true
                this.currentEditData.items = this.currentEditData.items ? [...new Set(this.currentEditData.items.concat(this.questionList.map(item => item.id)))] : [...new Set(this.questionList.map(item => item.id))]
                this.currentEditData.resources = this.currentEditData.resources ? [...new Set(this.currentEditData.resources.concat(this.fileList.map(item => item.url)))] : [...new Set(this.fileList.map(item => item.url))]
                this.$api.syllabus.SaveOrUpdateAsNodes([this.currentEditData]).then(res => {
                    if (!res.error && res) {
                        this.isRelatedContent = false
                        this.$emit('onTreeUpdate')
                        this.isLoading = false
                        this.$parent.hasModify = true
                    } else {
                        this.$Message.warning('获取数据失败')
                    }
                })
            },

        },
        watch: {
            // 监听课纲数据变化
            treeData: {
                handler: function (n, o) {
                    // 以下为拼接树形数据以及册别数据
                    let defaultTree = []
                    let volumeParent = {
                        title: this.volume.volumeName,
                        id: this.volume.volumeCode,
                        code: this.volume.volumeCode,
                        pid: 'Root',
                        children: []
                    }
                    volumeParent.children = n
                    defaultTree.push(volumeParent)
                    this.treeDatas = defaultTree
                }
            },
            // 监听课纲数据变化
            volume: {
                handler: function (n, o) {
                    this.volume = n
                }
            }
        }
    }
</script>


<style scoped>

    .syllabus-tree-main {
        width: 100%;
        height: 100%;
        padding-left: 50px;
    }

        .syllabus-tree-main .el-tree {
            background: transparent;
            color: #fff;
            padding-top: 10px;
            padding-bottom: 100px;
        }

        .syllabus-tree-main .el-tree-node__content {
            height: 50px;
            padding-left:0 !important;
        }

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

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

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

    .custom-tree-node {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
    }

        .custom-tree-node .tree-node-lable .ivu-icon {
            margin-left: 10px;
            font-size: 18px;
            color: rgb(11, 151, 117);
            display: none;
        }

    .custom-tree-tools, .node-info-num {
        display: none;
        margin-left: 5px;
        color: rgb(11, 151, 117);
    }

    .custom-tree-node:hover .custom-tree-tools,
    .custom-tree-node:hover .tree-node-lable .ivu-icon,
    .custom-tree-node:hover .tree-node-lable .node-info-num {
        display: unset;
    }

    .custom-tree-tools .ivu-icon {
        margin-right: 20px;
        color: #ccc;
    }

    /* 修改iview Modal样式 */

    .tree-modal .ivu-modal-content {
        background: #3c3c3c;
        overflow: hidden;
        color: #fff;
    }

    .tree-modal .ivu-modal-body {
        height: 400px;
        padding: 20px;
    }


    .tree-modal .ivu-modal-header {
        border-bottom: none;
        font-size: 18px;
        font-weight: bold;
        padding: 25px;
    }

    .tree-modal .modal-content {
        padding: 0 35px 30px 35px;
    }

        .tree-modal .modal-content .node-title {
            color: #fff;
            margin: 30px 0;
            font-size: 14px;
        }

        .tree-modal .modal-content .ivu-input {
            background: #575757;
            border-color: transparent;
            height: 35px;
            color: #fff;
        }

            .tree-modal .modal-content .ivu-input::-webkit-input-placeholder {
                color: #808080;
            }

    .tree-modal .modal-btn {
        margin-left: 2%;
        width: 96%;
        height: 40px;
        background: rgb(11, 151, 117);
        border: none;
        color: #fff;
        margin-top: 30px;
    }

    .tree-modal .choose-content {
        height: 85%;
    }

    /*修改iview Tab标签页样式重写*/
    .tree-content-modal .ivu-tabs-nav {
        width: 100%;
    }

    .tree-content-modal .ivu-tabs {
        height: 100%;
    }

    .tree-content-modal .ivu-tabs-nav .ivu-icon {
        font-size: 20px;
        margin-right: 15px;
    }

    .tree-content-modal .ivu-tabs-nav .ivu-tabs-tab {
        width: 50%;
        text-align: center;
        color: #fff;
        margin: 0;
        padding-bottom: 20px;
    }

    .tree-content-modal .ivu-tabs-bar {
        border-bottom: none;
    }

    .tree-content-modal .ivu-tabs-nav-container:focus .ivu-tabs-tab-focused {
        border-color: rgb(11, 151, 117) !important;
    }

    .tree-content-modal .ivu-tabs-ink-bar {
        background: rgb(11, 151, 117) !important;
        height: 4px;
        bottom: 0;
    }

    .tree-content-modal .ivu-tabs-content {
        height: 100%;
    }

    /* 资源文件样式 */
    .tree-content-resource-box {
        display: flex;
        flex-wrap: wrap;
        overflow: hidden;
        height: 100%;
    }

    .tree-content-modal .resource-item {
        margin: 10px;
        width: 180px;
        height: 120px;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background: #545454;
        box-shadow: 11px 11px 5px #383838;
        color: #fff;
        border-radius: 3px;
        cursor: pointer;
    }

        .tree-content-modal .resource-item .resource-item-img {
            margin: 0 30px;
            position: relative;
        }

            .tree-content-modal .resource-item .resource-item-img .icon-close {
                position: absolute;
                right: -50px;
                top: -10px;
                font-size: 20px;
                color: #a7a7a7;
            }

    .tree-content-modal .resource-item-name {
        width: 80%;
    }

        .tree-content-modal .resource-item-name .file-name {
            display: inline-block;
            width: 150px;
            margin-top: 5px;
            text-align: center;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

    .tree-content-modal .resource-item .file-info p {
        white-space: normal;
        word-break: break-all;
        color: #EEEEEE;
    }
</style>


<style scoped>

    .tree /deep/ .el-tree-node {
        position: relative;
        padding-left: 16px;
    }

    .tree /deep/ .el-tree-node__children {
        padding-left: 16px;
    }

    .tree /deep/ .el-tree-node :last-child:before {
        height: 38px;
    }

    .tree /deep/ .el-tree > .el-tree-node:before {
        border-left: none;
    }

    .tree-container /deep/ .el-tree > .el-tree-node:after {
        border-top: none;
    }

    .tree /deep/ .el-tree-node:before {
        content: "";
        left: -4px;
        position: absolute;
        right: auto;
        border-width: 1px;
    }

    .tree /deep/ .el-tree-node:after {
        content: "";
        left: -4px;
        position: absolute;
        right: auto;
        border-width: 1px;
    }

    .tree /deep/ .el-tree-node:before {
        border-left: 1px dashed #959595;
        bottom: 0px;
        height: 100%;
        top: -12px;
        width: 1px;
    }

    .tree /deep/ .el-tree-node:after {
        border-top: 1px dashed #959595;
        height: 20px;
        top: 26px;
        width: 24px;
    }

</style>
