<template>
    <div class="classify-page">
        <div class="top-wrap">
            <div class="type-box">
                <!-- 中文分类 -->
                <div class="item active" 
                    v-permission="[
                        permissionBtn.classifyBtn.classifyList_cnClassify,
                        permissionBtn.enClassifyBtn.classifyList_enClassify,
                        'and'
                        ]">
                    {{ $t('ReportManage.CategoryList.chinese_tabs') }}
                </div>
                <!-- 英文分类 -->
                <div class="item" @click="$emit('typeChange','2')" style="margin-left: 20px;"
                    v-permission="permissionBtn.enClassifyBtn.classifyList_enClassify">
                    {{ $t('ReportManage.CategoryList.english_tabs') }}
                </div>
            </div>
            <div style="display:flex;padding:10px;gap:10px">
                <!-- 添加分类 -->
                <el-button 
                    type="primary"
                    @click="addClassify"
                    v-permission="permissionBtn.classifyBtn.classifyList_cnClassify_classifyAdd"
                >
                    {{$t('ReportManage.CategoryList.add_category')}}
                </el-button>
                <el-input :placeholder="$t('ReportManage.CategoryList.category_name')" v-model="searchVal" style="max-width: 262px;" @change="getList" clearable>
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
            </div>
        </div>
        <div class="content-box">
            <el-tree
			    :data="list"
				node-key="Id"
                :props="{
                    label: 'ClassifyName',
                    children: 'Child'
                }"
				check-strictly
				:empty-text="$t('Common.no_classify_msg')"
                draggable
                indent='76'
                :allow-drop="canDropHandle"
                @node-drop="dropOverHandle"
			>
				<div
					class="classify-item-wrap"
					slot-scope="{ data }"
				>
                    <div>
                        <span 
                            :class="['tag', data.Enabled==1?'open':'close']" 
                            @click.stop="handleEnableSet(data)">
                            {{data.Enabled==1?$t('Common.enable'):$t('Common.disable')}}
                        </span>
                        <span>{{data.ClassifyName}}</span>
                    </div>
					
                    <div class="opt-box">
                        <!-- 章节设置 -->
                        <span class="editsty" 
                            v-if="(!data.Child||(data.Child&&!data.Child.length)) && data.ClassifyType===1" 
                            @click="chapterSetting(data)" 
                            v-permission="permissionBtn.classifyBtn.classifyList_cnClassify_chapterSetting">
                            {{ $t('ReportManage.CategoryList.section_settings') }}
                        </span>

                        <el-button
                            v-if="data.ReportNum===0&&permissionBtn.checkPermissionBtn(permissionBtn.classifyBtn.classifyList_cnClassify_delete)"
                            type="text" 
                            style="color:#f00" 
                            @click.stop="handleDel(data)"
                        >删除</el-button>
                        <img class="icon-drag" src="~@/assets/img/data_m/move_ico2.png" alt="">
                        <img class="icon-set" src="~@/assets/img/icons/variety_set.png" alt="" @click.stop="handleEdit(data)" v-permission="permissionBtn.classifyBtn.classifyList_cnClassify_classifyEdit">
                    </div>
				</div>
			</el-tree>
        </div>

        <!-- 分类弹窗 -->
        <m-dialog 
            :title="classifyForm.classify_id?$t('ReportManage.CategoryList.edit_category'):$t('ReportManage.CategoryList.add_category')" 
            :show.sync="classifyForm.show" 
            v-if="classifyForm.show"
            width="650px"
        >
            <div style="padding-left: 50px">
                <el-form 
                    :model="classifyForm" 
                    :rules="formRules" 
                    ref="formRef" 
                    hide-required-asterisk
                    label-width="auto">
                    <!-- 分类名称 -->
                    <el-form-item prop="classify_name" :label="$t('ReportManage.CategoryList.category_name')">
                        <el-input 
                            type="text" 
                            v-model="classifyForm.classify_name" 
                            :placeholder="$t('ReportManage.CategoryList.category_name_hint')"
                            style="width:400px;"
                        />
                    </el-form-item>
                    <!-- 上级分类 -->
                    <el-form-item prop="parent_id" :label="$t('ReportManage.CategoryList.parent_category')">

                        <el-cascader
                            v-model="classifyForm.parent_id" 
                            :options="classifyparentArr"
                            :disabled="classifyForm.classify_id"
                            style="width:400px;"
                            ref="classifyRef"
                            :props="{ 
                                checkStrictly: true,
                                value: 'Id',
                                label: 'ClassifyName',
                                children:'Child',
                                emitPath:false
                            }"
                            clearable
                            @change="changeClassify"
                        >
                        </el-cascader>
                    </el-form-item>

                    <!-- 报告类型 -->
                    <el-form-item prop="reportType" label="报告类型">
                        <template slot="label">
                            <span>报告类型</span>
                            <el-tooltip content="研报对应研报中心可选分类，PPT对应PPT中心可选分类">
                                <i class="el-icon-warning"/>
                            </el-tooltip>
                        </template>

                        <el-select v-model="classifyForm.reportType" style="width:400px" :disabled="classifyForm.classify_id||(classifyForm.parent_id&&!classifyForm.hasClassifyChild)">
                            <el-option label="研报" :value="1"/>
                            <el-option label="PPT" :value="2"/>
                        </el-select>
                        
                    </el-form-item>

                    <!-- 可见权限 -->
                    <el-form-item prop="reportType" label="可见权限">
                        <template slot="label">
                            <span>可见权限</span>
                            <el-tooltip content="未设置可见权限表示所有用户可见，设置可见用户后，指定用户可见该分类下报告">
                                <i class="el-icon-warning"/>
                            </el-tooltip>
                        </template>
                        <el-cascader
                            @change="getVal"
                            style="width:400px"
                            :disabled='classifyForm.Child'
                            v-model="classifyForm.VisibleUserIds"
                            :options="userOptions"
                            :props="{
                                value: 'NodeId',
                                label: 'NodeName',
                                children: 'Children',
                                multiple: true,
                                emitPath: false
                            }"
                            :show-all-levels="false"
                            collapse-tags
                            clearable
                            filterable
                            :placeholder="this.$t('SystemManage.OperateAuth.placeholder04')" 
                        />
                        
                    </el-form-item>

                    <!-- 报告提醒 -->
                    <el-form-item prop="warnTime" label="报告提醒">
                        <template slot="label">
                            <span>报告提醒</span>
                            <el-tooltip content="开启后，指定的报告编辑人将在课题结束前定时收到写报告提醒">
                                <i class="el-icon-warning"/>
                            </el-tooltip>
                        </template>
                        <el-switch
                            v-model="classifyForm.isReportWarn"
                            :active-value="1"
                            :inactive-value="0"
                        />
                       <el-time-picker
                            v-if="classifyForm.isReportWarn"
                            v-model="classifyForm.warnTime"
                            format="HH:mm"
                            value-format="HH:mm"
                            style="width:120px;margin-left:20px"
                        >
                        </el-time-picker> 
                    </el-form-item>
                   
                </el-form>
                <div v-html="tips" style="color:#999;"></div>
            </div>
            <div slot="footer" style="margin-top: 20px;">
                <el-button
                @click="cancelClassify"
                style="width: 132px; height: 40px"
                >{{ $t('Dialog.cancel_btn') }}</el-button>
                <el-button
                @click="setClassifyHandle"
                type="primary"
                style="width: 132px; height: 40px"
                >{{ $t('Dialog.confirm_save_btn') }}</el-button>
            </div>
        </m-dialog>

        <!-- 转移报告弹窗 -->
        <m-dialog
            title="分类报告转移"
            :show.sync="isTransferReport"
            width="650px"
        >

            <div>
                <el-form
                    :model="transferForm"
                    hide-required-asterisk
                    label-width="auto"
                >
                    <el-form-item prop="classify_name" label="原分类">
                        <el-cascader
                          v-model="transferForm.oldClassify"
                          @change="filterChange"
                          :options="classifyparentArr"
                          clearable
                          placeholder="请选择分类"
                          style="width:100%;"
                      ></el-cascader>
                    </el-form-item>
                    <!-- 上级分类 -->
                    <el-form-item prop="parent_id" label="转移至分类">

                        <el-cascader
                          v-model="transferForm.newClassify"
                          @change="filterChange"
                          :options="classifyparentArr"
                          clearable
                          placeholder="请选择分类"
                          style="width:100%;"
                      ></el-cascader>
                    </el-form-item>
                    
                </el-form>
            </div>

            <div slot="footer" style="margin-top: 20px;">
                <el-button
                @click="isTransferReport=false"
                style="width: 132px; height: 40px"
                >{{ $t('Dialog.cancel_btn') }}</el-button>
                <el-button
                @click="handleSaveTransferReport"
                type="primary"
                style="width: 132px; height: 40px"
                >{{ $t('Dialog.confirm_save_btn') }}</el-button>
            </div>

        </m-dialog>
    </div>
</template>

<script>
import mDialog from '@/components/mDialog.vue';
import { classifylist,classifyparent,classifyadd,classifyedit,classifydelete } from 'api/api.js';
import {classifyPermissionInterface} from '@/api/modules/classifyApi.js'
import { departInterence } from '@/api/modules/setApi';
export default {
    components:{mDialog},
    computed: {
        canSetPermission() {
            /* 编辑最小级分类可设置品种 新增分类可设置跑品种 */
            if(!this.permissionBtn.classifyBtn.classifyList_cnClassify_connect_variety) return false
            
            if(this.classifyForm.classify_id) {
                return this.classifyForm.isLastLevel?true:false
            }else {
                return true
            }
        }
    },
    data() {
        return {
            userOptions:[],

            typeVal:1,
            searchVal:'',
            list:[],

            classifyForm:{
                show:false,
                classify_id:0,
                classify_name:"",
                parent_id: 0,
                variety:'',//关联的品种
                reportType: 1,
                isReportWarn: 0,
                warnTime:'09:00',
                hasClassifyChild:false,
                VisibleUserIds:[]
            },
            formRules: {
                classify_name: [{ required:true,message:this.$t('ReportManage.CategoryList.category_name_hint'),trigger:'blur'}]
            },
            classifyparentArr:[],

            reportVarietyList:[],//中文品种列表

            /* 转移报告弹窗 */
            isTransferReport: false,
            transferForm: {},

            tips: `注：若上级分类已关联报告，则新建的第一个子分类默认继承上级分类（父分类）关联的报告。`
        }
    },
    mounted(){
        this.getList()
        this.getUserList()
    },
    methods: {
        getVal(val){
            console.log(val)
        },
        // 递归处理数组
        filterTreeEmpty(arr) {
            function dfs(node) {
                if (Array.isArray(node.Children)) {
                    for (let child of node.Children) {
                        dfs(child);
                    }
                    if(node.Children.length===0) delete node.Children
                }
                //若为叶子节点,且不为用户,禁止选中
                if(!node.Children||!Array.isArray(node.Children)){
                    if(node.NodeType!==3) node.disabled = true
                }
            }
            dfs(arr); 
        },
        // 获取用户可见权限列表
        getUserList(){
            departInterence.getSystemUser({}).then(res=>{
                if(res.Ret===200){
                    this.userOptions=res.Data || []
                    this.filterTreeEmpty({Children:this.userOptions})
                }
            })     
        },
        /* 报告转移 */
        transferReport() {
            this.isTransferReport = true;
            this.transferForm = {
                oldClassify: '',
                newClassify: ''
            }
        },
        
        handleSaveTransferReport() {
            
        },


        async getList(type){
            const res=await classifylist({
                KeyWord:this.searchVal,
            })
            if(res.Ret===200){
                this.list=res.Data.List||[]
                
                this.classifyparentArr=_.cloneDeep(this.list)
                this.filterNodes(this.classifyparentArr)
            }
        },

        /* 添加分类默认关联父级报告类型 */
        async changeClassify(id) {
                let item = this.$refs.classifyRef.getCheckedNodes(true)
                console.log(item)
                if(item&&item[0]) {
                    this.classifyForm.reportType = item[0].data.ClassifyType;
                    this.classifyForm.hasClassifyChild = item[0].data.HasChild ? true : false;
                    this.classifyForm.VisibleUserIds = item[0].data.VisiableUsers?item[0].data.VisiableUsers:[];
                }else {
                    this.classifyForm.hasClassifyChild = false
                }
        },

        // 去设置章节
		chapterSetting(row){
			this.$router.push({path:'chapterSetting',query:{ id:row.Id,classifyName: row.ClassifyName }})
		},

        filterNodes(arr) {
            arr.length && arr.forEach(item => {
                item.Child && item.Child.length && this.filterNodes(item.Child)
                if(!item.Child || (item.Child&&!item.Child.length)  || item.Level===2) {
                    delete item.Child
                }
            })
        },

        async addClassify(){

            this.classifyForm={
                Child:null,
                show:true,
                classify_id:0,
                classify_name:"",
                parent_id: 0,
                variety:'',//关联的品种
                reportType: 1,
                isReportWarn: 0,
                warnTime:'09:00',
                hasClassifyChild:false,
                VisibleUserIds:[]
            }
        },
        async handleEdit(item){
            this.classifyForm={
                Child:item.Child,
                VisibleUserIds:item.VisiableUsers?item.VisiableUsers:[],
                show:true,
                classify_id:item.Id,
                classify_name:item.ClassifyName,
                parent_id: item.ParentId,
                isLastLevel: !item.Child,
                reportType: item.ClassifyType,
                isReportWarn: item.IsRemind,
                warnTime: item.RemindTime,
                hasClassifyChild:false
            }
        },
        async setClassifyHandle(){
            await this.$refs.formRef.validate();
            const { classify_name,parent_id,classify_id,reportType,isReportWarn,warnTime,VisibleUserIds } = this.classifyForm;
            let params = {
                ClassifyName: classify_name,
                ParentId: parent_id,
                ClassifyType: reportType,
                IsRemind: isReportWarn,
                RemindTime: warnTime,
                VisibleUserIds
            }

            const { Ret,Msg } = classify_id 
                ? await classifyedit({...params,ClassifyId: classify_id}) 
                : await classifyadd(params)

            if(Ret !== 200) return
            //this.$message.success(Msg)
            this.$message.success(
                classify_id
                ?this.$t('ReportManage.CategoryList.modification_successful')
                :this.$t('ReportManage.CategoryList.addition_successful')
            )
            this.cancelClassify();
            this.getList();
        },
        /* 取消 */
        cancelClassify() {
            this.$refs.formRef.resetFields();
            this.classifyForm.show = false;
        },

        /* 删除分类 */
        async handleDel(item) {
            console.log(item)
            await this.$confirm('分类删除后不可恢复，是否确认删除？', '提示', {
                type: 'warning'
            })
            const res = await classifydelete({ClassifyId:item.Id})
            
            if(res.Ret!==200) return
            this.$message.success('删除成功')
            this.getList()
            
        },

        //启用\禁用设置
        handleEnableSet(item){
            // 判断权限
            const {classifyBtn,checkPermissionBtn} = this.permissionBtn
            if(!checkPermissionBtn(classifyBtn.classifyList_cnClassify_enable)) return
            
            classifyPermissionInterface.enableSet({
                ClassifyId:item.Id,
                Enabled:item.Enabled==1?0:1
            }).then(res=>{
                if(res.Ret===200){
                    //设置成功
                    this.$message.success(this.$t('ReportManage.CategoryList.setup_successful'))
                    this.getList()
                }
            })
        },

        //控制只能同级拖动
        canDropHandle(draggingNode, dropNode, type){
            if(type==='inner') return false //禁止向内部拖动
            if(draggingNode.level!=dropNode.level) return false
            if(draggingNode.data.ParentId!=dropNode.data.ParentId) return false
            return true
        },

        //拖动结束
        dropOverHandle(b,a,i,e) {
            // 被拖拽节点对应的 Node、结束拖拽时最后进入的节点、被拖拽节点的放置位置
            const classifyId=b.data.Id
            let list=a.parent.childNodes;
            let PrevClassifyId=0,NextClassifyId=0,targetIndex=0;
            list.forEach((item,index) => {
                if(item.data.Id===classifyId){
                    targetIndex=index
                }
            });
            if(targetIndex===0){
                NextClassifyId=list[1].data.Id
            }else if(targetIndex===list.length-1){
                PrevClassifyId=list[list.length-1].data.Id
            }else{
                PrevClassifyId=list[targetIndex-1].data.Id
                NextClassifyId=list[targetIndex+1].data.Id
            }

            const params={
                ClassifyId:classifyId,
                PrevClassifyId,
                NextClassifyId
            }
            console.log(params);
            classifyPermissionInterface.moveSort(params).then(res=>{
                if(res.Ret===200){
                    this.$message.success(this.$t('ReportManage.CategoryList.move_successful'))
                }else{
                    this.getList()
                }
            })
        },
        
    },
}
</script>

<style lang="scss">
.el-cascader .el-input{
  width: 100%;
}
.classify-page{
    .content-box{
        .el-tree-node__content{
            height: fit-content;
            padding-top: 10px;
            padding-bottom: 10px;
            border-bottom: 1px solid #C8CDD9;
        }
    }
}

</style>
<style lang="scss" scoped>
.top-wrap{
    display: flex;
    justify-content: space-between;
    background: #FFFFFF;
    border-radius: 4px;
    .type-box{
        display: flex;
        .item{
            position: relative;
            cursor: pointer;
            color: #666;
            min-width: 88px;
            line-height: 60px;
            text-align: center;
           
        }
        .active{
            color: #0052D9;
            &::after{
                content: '';
                display: block;
                width: 100%;
                height: 2px;
                position: absolute;
                bottom: 0px;
                left: 0;
                background-color: #0052D9;
            }
        }
    }
}
.content-box{
    padding: 20px;
    margin-top: 20px;
    height: calc(100vh - 230px);
    overflow-y: auto;
    background-color: #FFFFFF;
    .classify-item-wrap{
        flex: 1;
        padding-right: 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .tag{
            display: inline-block;
            min-width: 76px;
            line-height: 30px;
            text-align: center;
            &.open{
                background-color: #ECF2FE;
                color: #0052D9;
            }
            &.close{
                background-color: #0052D9;
                color: #fff;
            }
        }
        .opt-box{
            display: flex;
            align-items: center;
            gap: 10px;
            .icon-drag,.icon-set{
                width: 16px;
                height: 16px;
                margin-left: 10px;
            }
        }
    } 
}
</style>