<template>
    <div class="classify-page">
        <div class="top-wrap">
            <div class="type-box">
                <div class="item" @click="$emit('typeChange','1')">中文分类</div>
                <div class="item active">英文分类</div>
            </div>
            <div style="display:flex;padding:10px;gap:10px">
            <el-button 
                type="primary"
                @click="addClassify"
                v-permission="permissionBtn.enClassifyBtn.classifyList_enClassify_add"
            >添加分类</el-button>
            <el-input placeholder="分类名称" 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="暂无数据"
                draggable
                indent='76'
                :allow-drop="canDropHandle"
                @node-drop="dropOverHandle"
			>
				<div
					class="classify-item-wrap"
					slot-scope="{ node, data }"
				>
                    <div>
                        <span :class="['tag', data.Enabled==1?'open':'close']" @click.stop="handleEnableSet(data)">{{data.Enabled==1?'启用':'禁用'}}</span>
                        <span>{{data.ClassifyName}}</span>
                    </div>
					
                    <div class="opt-box">
                        <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,node)" v-permission="permissionBtn.enClassifyBtn.classifyList_enClassify_edit">
                    </div>
				</div>
			</el-tree>
        </div>

        <!-- 分类弹窗 -->
        <m-dialog 
            :title="classifyForm.classify_id?'编辑分类':'新增分类'" 
            :show.sync="classifyForm.show" 
            width="650px"
        >
            <div style="padding-left: 50px">
                <el-form 
                    :model="classifyForm" 
                    :rules="formRules" 
                    ref="formRef" 
                    label-position="left"
                    hide-required-asterisk
                    label-width="90px">
                    <el-form-item prop="classify_name" label="分类名称">
                        <el-input 
                            type="text" 
                            v-model="classifyForm.classify_name" 
                            placeholder="请输入分类名称"
                            style="width:400px;"
                        />
                    </el-form-item>
                    <el-form-item prop="parent_id" label="上级分类">
                        <el-cascader :options="classifyparentArr" v-model="classifyForm.parent_id" placeholder="请选择"
                        :props="{value:'Id',label:'ClassifyName',children:'Child',checkStrictly:true,emitPath:false}" style="min-width:400px;"></el-cascader>
                    </el-form-item>
                    <el-form-item prop="variety" label="关联品种" v-if="classifyForm.level==3&&permissionBtn.enClassifyBtn.classifyList_enClassify_connect_variety">
                        <template slot="label">
                            <el-tooltip class="item" effect="dark" content="控制报告阅读权限">
                                <div>
                                    <span>关联品种</span>
                                    <i class="el-icon-info"></i>
                                </div>
                            </el-tooltip>
                        </template>
                        <el-cascader
                            :options="reportVarietyList" 
                            v-model="classifyForm.variety" 
                            placeholder="请选择"
                            collapse-tags
                            :props="{value:'PermissionId',label:'PermissionName',children:'Child',multiple: true,emitPath:false}" 
                            style="min-width:400px;"
                        ></el-cascader>
                    </el-form-item>
                </el-form>
            </div>
            <div slot="footer" style="margin-top: 20px;">
                <el-button
                @click="cancelClassify"
                style="width: 132px; height: 40px"
                >取消</el-button>
                <el-button
                @click="setClassifyHandle"
                type="primary"
                style="width: 132px; height: 40px"
                >保存</el-button>
            </div>
        </m-dialog>
    </div>
</template>

<script>
import draggable from 'vuedraggable';
import mDialog from '@/components/mDialog.vue';
import {reportVarietyENInterence} from '@/api/modules/reportVariety'
import * as classifyEnInterface from "@/api/modules/classifyEnApi.js";
export default {
    components:{draggable,mDialog},
    data() {
        return {
            typeVal:1,
            searchVal:'',
            list:[],

            classifyForm:{
                show:false,
                classify_id:0,
                classify_name:"",
                parent_id: '',
                variety:'',//关联的品种
                level:1
            },
            formRules: {
                classify_name: [{ required:true,message:'请输入分类名称',trigger:'blur'}]
            },
            classifyparentArr:[],

            reportVarietyList:[],//英文品种列表
        }
    },
    mounted(){
        this.getList('init')
        this.getReportVarietyList()
    },
    methods: {
        async getList(type){
            const res=await classifyEnInterface.classifyList({
                KeyWord:this.searchVal
            })
            if(res.Ret===200){
                this.list=res.Data.List||[]
                if(type==='init'){
                    const arr=JSON.parse(JSON.stringify(this.list))
                    this.classifyparentArr=arr.map(item=>{
                        item.Child&&item.Child.forEach(_item=>{
                            _item.Child=null
                        })
                        return {
                            ...item
                        }
                    })
                    this.classifyparentArr.unshift({Id:'0',ClassifyName:'无',Child:null})
                }
            }
        },
        

        //启用\禁用设置
        handleEnableSet(item){
            // 判断权限
            const {enClassifyBtn,checkPermissionBtn} = this.permissionBtn
            if(!checkPermissionBtn(enClassifyBtn.classifyList_enClassify_enable)) return

            classifyEnInterface.enableSet({
                ClassifyId:item.Id,
                Enabled:item.Enabled==1?0:1
            }).then(res=>{
                if(res.Ret===200){
                    this.$message.success('设置成功')
                    this.getList('init')
                }
            })
        },

        addClassify(){
            this.classifyForm={
                show:true,
                classify_id:0,
                classify_name:"",
                parent_id: '0',
                variety:'',//关联的品种
            }
        },
        handleEdit(item,node){
            this.classifyForm={
                show:true,
                classify_id:item.Id,
                classify_name:item.ClassifyName,
                parent_id: item.ParentId||'0',
                variety:item.EnPermissions||'',//关联的品种
                level:node.level
            }
        },
        async setClassifyHandle(){
            await this.$refs.formRef.validate();
            const { classify_name,parent_id,sort,classify_id } = this.classifyForm;
            let params = {
                ClassifyName: classify_name,
                ParentId: Number(parent_id)||0,
                EnPermissions:this.classifyForm.variety||[]
            }
            // console.log(params);

            const { Ret,Msg } = classify_id 
                ? await classifyEnInterface.classifyEdit({...params,ClassifyId: classify_id}) 
                : await classifyEnInterface.classifyAdd(params)

            if(Ret !== 200) return
            this.$message.success(Msg)
            this.cancelClassify();
            this.getList('init');
        },
        /* 取消 */
        cancelClassify() {
            this.$refs.formRef.resetFields();
            this.classifyForm.show = false;
        },

        // 获取品种数据
        getReportVarietyList(){
            reportVarietyENInterence.filterVarietyOpts().then(res=>{
                this.reportVarietyList=res.Data||[]
            })
        },

        //控制只能同级拖动
        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);
            classifyEnInterface.moveSort(params).then(res=>{
                if(res.Ret===200){
                    this.$message.success('移动成功')
                }else{
                    this.getList()
                }
            })
        },
    },
}
</script>

<style lang="scss">
.el-cascader .el-input{
  width: 100%;
}
.classify-page{
    .content-box{
        .el-tree-node__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{
            .icon-drag,.icon-set{
                width: 16px;
                height: 16px;
                margin-left: 10px;
            }
        }
    } 
}
</style>