<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)" 
                            @click="chapterSetting(data)" 
                            v-permission="permissionBtn.classifyBtn.classifyList_cnClassify_chapterSetting">
                            {{ $t('ReportManage.CategoryList.section_settings') }}
                        </span>
                        <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>
                <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 } from 'api/api.js';
import {reportVarietyInterence} from '@/api/modules/reportVariety'
import {classifyPermissionInterface} from '@/api/modules/classifyApi.js'
import { reportV2Interface } from '@/api/modules/reportV2.js'
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 {
            typeVal:1,
            searchVal:'',
            list:[],

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

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

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

            tips: `注：若上级分类已关联报告，则新建的第一个子分类默认继承上级分类（父分类）关联的品种、报告、审批流。`
        }
    },
    mounted(){
        this.getList()
    },
    methods: {
        /* 报告转移 */
        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) {
            if(!this.classifyForm.classify_id) {
                let item = this.$refs.classifyRef.getCheckedNodes(true)
                console.log(item)
            }
        },

        // 去设置章节
		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={
                show:true,
                classify_id:0,
                classify_name:"",
                parent_id: 0,
                variety:'',//关联的品种
            }
        },
        async handleEdit(item){
            
            this.classifyForm={
                show:true,
                classify_id:item.Id,
                classify_name:item.ClassifyName,
                parent_id: item.ParentId,
                isLastLevel: !item.Child
            }
        },
        async setClassifyHandle(){
            await this.$refs.formRef.validate();
            const { classify_name,parent_id,classify_id } = this.classifyForm;
            let params = {
                ClassifyName: classify_name,
                ParentId: parent_id,
            }

            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;
        },

        //启用\禁用设置
        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{
            .icon-drag,.icon-set{
                width: 16px;
                height: 16px;
                margin-left: 10px;
            }
        }
    } 
}
</style>