<template>
  <div>
    <!-- 右键菜单栏 -->
    <div v-show="menuVisible" id="menu" :style="'left:'+coordinate.menuX+';top:'+coordinate.menuY">
        <ul class="menu" style="width:120px">
            <li class="menu_item padding_35" v-show="menuMode !== 'blank'" @click="clickFile">打开</li>
            <li class="menu_item padding_35" v-show="menuMode !== 'blank' && !currentIsFiLe" @click="handleEdit">编辑</li>
            <li class="menu_item padding_35" v-show="menuMode !== 'blank' && !currentIsFiLe" @click="deleteVisible = true">删除</li>
            <li class="menu_item" style="text-align:center" v-show="menuMode === 'blank' && !currentIsFiLe" @click="prepareCreate">新建文件夹</li>
        </ul>
        <!-- <ul class="menu" style='width:230px'  v-show="menuMode === 'blank' && currentIsFiLe">
            <li class="menu_item" style="text-align:center">合并所有文档到新文件夹</li>
        </ul> -->
    </div>

    <!-- 新建文件夹窗口 -->
    <el-dialog title="新建个人文件夹" class="newfile-dialog" :visible.sync="newFolderVisible" width="750px" :close-on-click-modal="false">
        <el-form :model="ruleForm" :rules="ruleForm.folderType === 'usual'?usualRules:taskRules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="文件夹名称" prop="name">
                <el-input placeholder="请输入..." v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="文件夹类型" prop="folderType">
                <el-radio-group v-model="ruleForm.folderType">
                    <el-radio label="usual">常规文件夹</el-radio>
                    <el-radio label="task">任务文件夹</el-radio>
                </el-radio-group>
                <el-alert
                    type="info"
                    class="tips"
                    :closable="false"
                    :description="ruleForm.folderType === 'usual'?tipsText.usual:tipsText.task"
                    show-icon>
                </el-alert>
            </el-form-item>
            <el-form-item label="公开/不公开" prop="private">
                <el-radio-group v-model="ruleForm.private">
                    <el-radio label="private">不公开</el-radio>
                    <el-radio label="publicToAll">对所有教师公开</el-radio>
                    <el-radio label="publickToPart">对部分教师公开</el-radio>
                </el-radio-group>
                <span style="display:inline-block;margin:0 10px;" class="add-teacher-ctn" v-if="ruleForm.private === 'publickToPart'">
                    <el-button class="person-btn" icon="el-icon-plus" @click="handleSelect('publicTeacher')">添加教师</el-button>
                    <span class="person-count">已选择 <span style="color:blue">{{ ruleForm.publicTeacher.length }}</span> 人</span>
                </span>
            </el-form-item>
            <el-form-item class="limit-ctn" v-if="ruleForm.folderType === 'task'" label="每人上传数" prop="limitCount">
                <el-radio-group v-model="ruleForm.limitCount">
                    <el-radio label="limit">限制数量</el-radio>
                    <span style="display:inline-block;width:100px" v-if="ruleForm.limitCount === 'limit'"><el-input type="number" v-model="ruleForm.limitCountNumber" placeholder="请输入..."></el-input></span>
                    <el-radio label="noLimit">不限制数量</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="管理者" prop="manager">
                <div class="header-ctn">
                    <el-button class="person-btn" icon="el-icon-plus" @click="handleSelect('manager')">添加教师</el-button>
                    <span class="person-count">已选择 <span style="color:blue">{{ ruleForm.manager.length }}</span> 人</span>
                </div>
                <div class="tag-ctn">
                    <el-tag
                        v-for="(tag, index) in ruleForm.manager"
                        :key="index"
                        effect="dark"
                        type="info"
                        color="#F2F2F2"
                        size="medium"
                        @close="deleteManagerUser(index)"
                        closable>
                        {{tag.realname}}
                    </el-tag>
                </div>
            </el-form-item>
            <el-form-item v-if="ruleForm.folderType === 'task'" label="上传教师" prop="uploadTeacher">
                <div class="header-ctn">
                    <el-button class="person-btn" icon="el-icon-plus" @click="handleSelect('uploadTeacher')">添加教师</el-button>
                    <span class="person-count">已选择 <span style="color:blue">{{ ruleForm.uploadTeacher.length }}</span> 人</span>
                </div>
                <!-- <div class="tag-ctn">
                    <el-tag
                        v-for="(tag, index) in ruleForm.uploadTeacher"
                        :key="index"
                        effect="dark"
                        type="info"
                        color="#F2F2F2"
                        size="medium"
                        closable>
                        {{tag.name}}
                    </el-tag>
                </div> -->
            </el-form-item>
            <el-form-item class="submit-ctn">
                <el-button size="medium" type="primary" @click="hanlderCreateOrUpdate('ruleForm')">保存</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <!-- 删除文件窗口 -->
    <el-dialog title="删除确认" :visible.sync="deleteVisible" width="500px">
        <h3>删除文件夹同时会将文件夹下的所有资源全部删除，请谨慎操作！</h3>
        <div slot="footer" class="dialog-footer">
            <el-button @click="deleteVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleDelete">确 定</el-button>
        </div>
    </el-dialog>
    <userselector
        :mode="userSelector.mode"
        :list="userSelector.list"
        :visible.sync="userSelector.visible"
        @submit="selectUser"
    />

  </div>
</template>

<script>
export default {
    name: 'ContextMenu',
    props: {
        menuVisible: { // 右键菜单栏显示
            type: Boolean,
            default: false
        },
        currentIsFiLe: { // 当前层次是否为文档列表
            type: Boolean,
            default: false
        },
        rightMenuData: { // 右键文件的数据
            type: Object,
            default: () => {
                return {}
            }
        },
        rightMenuFolder: { // 右键空白所在层的文件夹数据
            type: Array,
            default: () => {
                return []
            }
        },
        coordinate: { // 右键菜单栏坐标
            type: Object,
            default: () => {
                return {}
            }
        },
        menuMode: { // 右键的文件属于那种类型（ blank: 右键空白 ）
            type: String,
            default: ''
        }
    },
    components: {
        userselector: () => import('@/common/userSelector/UserSelector')
    },
    data () {
        return {
            userSelector: {
                mode: 'teacherCheckbox',
                list: [],
                visible: false
            },
            seletorListName: '', // 当前需要选人的用户列表名
            newFolderVisible: false,
            newFolderName: '',
            deleteVisible: false,
            shareVisible: false,
            tipsText: {
                usual: '常规文件夹是专门用来放置学校常规资源，不限制上传浇水，不限制上传文档数量，建好后可以一直使用。',
                task: '任务文件夹是收集任务式的资源，有明确的上传教师范围，有明确的篇数要求，一般都是针对一个学期的文件夹。'
            },
            folderIsEdit: false, // 文件夹操作是否是编辑状态? false: 新建文件夹状态， true：编辑文件夹状态
            ruleForm: {
                name: '',
                folderType: 'usual',
                private: 'private',
                limitCount: 'limit',
                limitCountNumber: 0,
                publicTeacher: [],
                manager: [],
                uploadTeacher: []
            },
            usualRules: {
                name: [
                    { required: true, message: '请输入文件夹名称' }
                ]
            },
            taskRules: {
                name: [
                    { required: true, message: '请输入文件夹名称' }
                ],
                limitCount: [
                    { required: true, message: '请选择是否限制上传数量' }
                ],
                manager: [
                    { required: true, message: '请选择教师' }
                ],
                uploadTeacher: [
                    { required: true, message: '请选择教师' }
                ]
            }
        }
    },
    methods: {
        showUploadMenu (event) {
            // event.stopPropagation()
            this.$emit('showUploadMenu')
        },
        clickFile () {
            let file = this.rightMenuData
            this.$emit('menuOpenFile', file)
        },
        handleSelect (listName) {
            /* 根据选择教师按钮类型来定义接收list的值 */
            this.seletorListName = listName
            this.userSelector.list = this.ruleForm[listName]
            this.userSelector.visible = true
        },
        deleteManagerUser (index) {
            this.ruleForm.manager.splice(index, 1)
        },
        selectUser (list) {
            this.ruleForm[this.seletorListName] = list
        },
        handleEdit () {
            let params = { b_id: this.rightMenuData.b_id }
            this.$api.schoolBasedResourcesApi.getSchoolFolderInfo(params).then(res => {
                this.$handleResponse(res).then(data => {
                    this.folderIsEdit = true
                    this.initEditForm(data)
                    this.newFolderVisible = true
                })
            })
        },
        prepareCreate () {
            this.folderIsEdit = false
            this.clearFormData()
            this.newFolderVisible = true
        },
        hanlderCreateOrUpdate (formName) {
            /* 新建或修改学校文件夹 */
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let data
                    let form = this.ruleForm
                    let folderType = form.folderType === 'usual' ? 1 : 2
                    let isPublic = form.private === 'private' ? 1 : (form.private === 'publicToAll' ? 2 : 3)
                    let publicTeacher = this.userListToString(form.publicTeacher)
                    let manager = this.userListToString(form.manager)
                    let uploadTeacher = this.userListToString(form.uploadTeacher)
                    let uploadCount = folderType === 1 ? 0 : (form.limitCount === 'limit' ? 1 : 2)
                    data = {
                        b_id: this.folderIsEdit ? this.rightMenuData.b_id : undefined,
                        parent_id: this.folderIsEdit ? this.rightMenuData.parent_id : this.rightMenuData.b_id,
                        step_number: this.folderIsEdit ? this.rightMenuData.step_number : (this.rightMenuData.step_number + 1 || 1),
                        folder_name: form.name,
                        folder_type: folderType,
                        is_public: isPublic,
                        public_user_ids: isPublic === 3 ? publicTeacher.userIds : undefined,
                        public_user_names: isPublic === 3 ? publicTeacher.userNames : undefined,
                        manage_user_ids: manager.userIds,
                        manage_user_names: manager.userNames,
                        upload_type: uploadCount,
                        limit_count: uploadCount === 1 ? parseInt(form.limitCountNumber) : undefined,
                        teacher_user_ids: folderType === 2 ? uploadTeacher.userIds : undefined,
                        teacher_user_names: folderType === 2 ? uploadTeacher.userNames : undefined
                    }
                    console.log(data, this.rightMenuData)
                    this.$emit('createOrUpdateFolder', data)
                } else {
                    console.log('提交参数有误!!')
                    return false
                }
            })
        },
        userListToString (userList) {
            /* 把分享用户数组转为字符串 */
            let data = {
                userIds: '',
                userNames: ''
            }
            for (let i = 0; i < userList.length; i++) {
                if (i === 0) {
                    data.userIds += userList[i].id
                    data.userNames += userList[i].realname
                } else {
                    data.userIds += ',' + userList[i].id
                    data.userNames += ',' + userList[i].realname
                }
            }
            return data
        },
        stringToUserList (ids, names) {
            /* 把分享用户字符串转为数组 */
            let idsStr = ids.split(',')
            let namesStr = names.split(',')
            let userList = []
            for (let i = 0; i < idsStr.length; i++) {
                userList.push({ id: idsStr[i], realname: namesStr[i] })
            }
            return userList
        },
        handleDelete () {
            /* 删除学校文件夹 */
            let data = {}
            if (!this.currentIsFiLe) {
                data = {
                    b_id: this.rightMenuData.b_id
                }
                this.$emit('handleDeleteFolder', data)
            }
        },
        initEditForm (data) {
            /* 根据获取的文件夹对象数据改变对应的form表单的值 */
            let ruleForm = this.ruleForm
            ruleForm.name = data.folder_name
            ruleForm.folderType = data.folder_type === 1 ? 'usual' : 'task'
            ruleForm.private = data.is_public === 1 ? 'private' : (data.is_public === 2 ? 'publicToAll' : 'publickToPart')
            ruleForm.limitCount = data.upload_type === 2 ? 'noLimit' : 'limit'
            ruleForm.limitCountNumber = data.limit_count || 0
            ruleForm.publicTeacher = data.public_user_ids ? this.stringToUserList(data.public_user_ids, data.public_user_names) : []
            ruleForm.manager = data.manage_user_ids ? this.stringToUserList(data.manage_user_ids, data.manage_user_names) : []
            ruleForm.uploadTeacher = data.teacher_user_ids ? this.stringToUserList(data.teacher_user_ids, data.teacher_user_names) : []
        },
        clearFormData () {
            /* 初始化表单数据 */
            this.ruleForm = {
                name: '',
                folderType: 'usual',
                private: 'private',
                limitCount: 'limit',
                limitCountNumber: 0,
                publicTeacher: [],
                manager: [],
                uploadTeacher: []
            }
        }
    }
}
</script>

<style lang="less" scoped>
#menu {
    position: absolute;
    z-index: 999;
    border-radius: 3px;
    background-color: white;
    border: 1px solid rgb(235, 235, 235);

    .menu {
        width: 120px;
        .menu_item {
            line-height: 35px;
            border-bottom: 1px solid rgb(235, 235, 235);
            font-size:13px;
            cursor: pointer;
            &:hover {
                background-color: #1790ff;
                color: white;
            }

            .upload_line {
                padding: 0 6px 0 10px;
                .upload-icon {
                    font-size: 22px;
                    vertical-align: middle;
                }
            }
        }

        .padding_35 {
            padding-left: 40px;
        }
    }
}

/deep/ .dialog-footer {
    text-align: center;
    .el-button {
        width: 100px;
        height: 35px;
    }
}

.newfile-dialog {
    z-index: 50;
    /deep/ .el-dialog__body {
        padding-top: 10px;
        .el-form-item {
            margin: 25px 0;
        }
    }

    /deep/ .limit-ctn {
        position: relative;
        .el-radio:first-child {
            margin-right: 5px;
        }
        .el-radio:last-child {
            margin-left: 20px;
        }
    }

    /deep/ .submit-ctn {
        .el-button {
            margin-left: 220px;
            margin-top: 50px;
        }
    }

    /deep/ .tips {
        background: #E6F7FF;

        .el-alert__icon {
            color: #409EFF;
        }
        .el-alert__description {
            color: rgb(100, 100, 100);
            font-size: 13px;
        }
    }

    .header-ctn {
        .person-btn {
            font-size: 14px;
        }

        .person-count {
            margin-left: 5px;
        }
    }
    /deep/ .tag-ctn {
        .el-tag {
            border: none;
            margin: 5px;
            color: rgb(46, 46, 46);
            font-size: 14px;
            vertical-align: middle;
            line-height: 32px;

            .el-tag__close {
                font-size: 18px;
                color: rgb(168, 168, 168);
            }
        }
    }
}

</style>
