<template>
    <div id="app">
        <!-- <el-button type="primary" @click="horizontal = !horizontal">切换tree方向</el-button> -->
        <div style="overflow: hidden">
            <span style="font-size: 14px;font-weight: 700; color: #333; margin: 0 10px 0 0">{{ this.$t('sidebar.GroupClassification') }} </span>
            <!-- <span style="font-size: 14px; color: #606266; margin: 0 10px 0 0">{{  this.$t('sidebar.GroupClassification')}}: </span> 
            <el-select
                v-model="dataForm.journal_id"
                placeholder="Please select a journal"
                @change="handleSelectJournal"
                style="width: 220px; margin-right: 35px"
            >
                <el-option v-for="item in df_jour" :label="item.title" :key="item.journal_id" :value="item.journal_id"></el-option>
            </el-select> -->

            <div
                @click="toggleExpand(data, true)"
                style="float: right; line-height: 32px; color: #006699; font-size: 12px; font-weight: 700; margin-right: 20px"
            >
                {{ $t('GroupClassification.ExpandAll') }}
            </div>
        </div>
        <org-tree
            id="orgTreeNode"
            :data="data"
            :horizontal="horizontal"
            collapsable
            :render-content="renderContent"
            @on-expand="onExpand"
            @on-node-mouseover="onMouseover"
            @on-node-mouseout="onMouseout"
            @on-expand-mouseover="Mouseover"
            @on-expand-mouseout="Mouseout"
            @on-node-click="cccc"
        >
        </org-tree>
        <div
            class="floating"
            v-show="isShowF && bd && this.currentTreeData.id != 'abc0'"
            @mouseover="
                () => {
                    isShowF = true;
                }
            "
            @mouseout="
                () => {
                    isShowF = false;
                }
            "
            @mousewheel.prevent="mouseWheelDia"
        >
            <p @click="addOrEdit(0)">{{ $t('GroupClassification.add') }}</p>

            <p @click="addOrEdit(1)">{{ $t('GroupClassification.edit') }}</p>

            <p @click="del">{{ $t('GroupClassification.delete') }}</p>
            <p @click="openJournal">{{ $t('GroupClassification.AssociatedJournal') }}</p>
        </div>
        <!-- 增加/编辑弹层 -->
        <el-dialog
            :title="isEdit == 0 ? $t('GroupClassification.add') : $t('GroupClassification.edit')"
            v-if="dialogVisible"
            :visible="dialogVisible"
            @close="clearDialog"
            show-close
            :close-on-click-modal="false"
            custom-class="addOrEditDia"
            width="35%"
        >
            <div class="tips">
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm" @submit.native.prevent label-width="120px">
                    <el-form-item :label="$t('GroupClassification.major_current')" v-if="isEdit == 0">
                        {{ this.currentTreeData.label }}
                    </el-form-item>
                    <el-form-item prop="major_title" :label="$t('GroupClassification.major_title')">
                        <el-input
                            v-focus
                            :placeholder="$t('GroupClassification.enter')"
                            clearable
                            v-model="ruleForm.major_title"
                            @keyup.enter.native="confirm"
                        ></el-input>
                    </el-form-item>
                    <el-form-item prop="nickname" :label="$t('GroupClassification.nickname')">
                        <el-input
                            v-focus
                            :placeholder="$t('GroupClassification.enter')"
                            clearable
                            v-model="ruleForm.nickname"
                            @keyup.enter.native="confirm"
                        ></el-input>
                    </el-form-item>
                    <el-form-item prop="major_sort" :label="$t('GroupClassification.sort')">
                        <el-input
                            v-focus
                            :placeholder="$t('GroupClassification.enter')"
                            clearable
                            v-model="ruleForm.major_sort"
                            @keyup.enter.native="confirm"
                        ></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <div class="tip-left">
                    <el-button size="small" type="info" @click="dialogVisible = false">{{ $t('GroupClassification.cancel') }}</el-button>
                    <el-button size="small" type="primary" @click="confirm">{{ $t('GroupClassification.submit') }}</el-button>
                </div>
            </span>
        </el-dialog>
        <!-- 删除 -->
        <el-dialog
            :title="$t('GroupClassification.delete')"
            v-if="dialogVisible2"
            :visible="dialogVisible2"
            @close="clearDialog"
            custom-class="delDia" :close-on-click-modal="false"
            width="35%"
        >
            <div class="tips">
                <p style="text-align: left">{{ $t('GroupClassification.deleteInfo') }} 【{{ this.currentTreeData.label }} 】?</p>
            </div>
            <span slot="footer" class="dialog-footer">
                <div class="tip-left">
                    <el-button size="mini" type="info" @click="dialogVisible2 = false">{{ $t('GroupClassification.cancel') }}</el-button>
                    <el-button size="mini" type="primary" @click="confimdelete">{{ $t('GroupClassification.submit') }}</el-button>
                </div>
            </span>
        </el-dialog>

        <el-drawer
            :title="this.currentTreeData.label + '   ' + $t('GroupClassification.AssociatedJournal')"      :wrapperClosable="false"
            :visible.sync="drawer"
            direction="rtl"
            :before-close="handleClose"
            size="50%"
        >
            <div style="padding: 0 20px; box-sizing: border-box">
                <el-table
                    :data="AssociatedJournalList"
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    empty-text="New messages (0)"
                >
                    <el-table-column label="No." align="center" width="50">
                        <template slot-scope="scop">
                            {{ scop.$index + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="title" label="title"></el-table-column>
                    <el-table-column prop="issn" width="160" label="issn"></el-table-column>

                    <el-table-column label=" " width="80" align="center">
                        <template slot-scope="scope">
                            <!-- <el-button plain type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)">Edit Message</el-button> -->
                            <!-- <p @click="addOrEdit(0)" v-if="scope.row.selected==0">{{ $t('GroupClassification.bind') }}</p> -->

                            <p
                                @click="
                                    changeBind({
                                        ...scope.row,
                                        selected: 1
                                    })
                                "
                                style="color: red; cursor: pointer"
                            >
                                {{ $t('GroupClassification.Unbind') }}
                            </p>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-drawer>
    </div>
</template>

<script>
import OrgTree from '@/components/org-tree';
import bus from '@/components/common/bus';
export default {
    name: 'app',
    components: {
        OrgTree
    },
    directives: {
        focus: {
            inserted: function (el) {
                el.querySelector('input').focus();
            }
        }
    },
    data() {
        return {
            AssociatedJournalList: [],
            drawer: false,
            bd: true,
            ruleForm: {
                major_title: '',
                nickname: ''
            },
            rules: {
                major_title: [{ required: true, message: this.$t('GroupClassification.enter'), trigger: 'change' }]
                // nickname: [{ required: true, message: this.$t('GroupClassification.enter'), trigger: 'change' }]
            },
            dialogVisible: false,
            dialogVisible2: false,
            isShowF: false,
            data: {
                id: 'abc0',
                label: this.$t('sidebar.GroupClassification'),
                leave: 1, // tree层级
                children: []
            },
            horizontal: true,
            collapsable: true,
            isEdit: 0,
            currentTreeData: {},
            lastId: 11,
            labelClassName: 'bg-white',
            urlList: {
                list: 'api/Major/getMajorList',
                add: 'api/Major/addMajor',
                edit: 'api/Major/editMajor',
                delete: 'api/Major/delMajor',
                AssociatedJournalList: 'api/Major/getJournalsForMajor',
                bind: 'api/Major/addJournalMajor',
                unbind: 'api/Major/delJournalMajor'
            }
        };
    },
    watch: {
        dialogVisible: {
            handler(newV, oldV) {
                if (newV == false) {
                    this.ruleForm = {};
                }
            }
        }
    },
    async created() {
        const a = this.numFormatter(9999999999);
        console.log(a);
        await this.getDate();
    },
    async activated() {
        await this.getDate();
    },
    methods: {
        changeBind(b) {
            var BindInfo = b.selected == 0 ? this.$t('GroupClassification.BindInfo') : this.$t('GroupClassification.UnBindInfo');
            this.$confirm(`${this.$t('GroupClassification.JournalBindInfo')} ${b.title}${BindInfo}`, '提示', {
                confirmButtonText: this.$t('GroupClassification.submit'),
                dangerouslyUseHTMLString: true,
                cancelButtonText: this.$t('GroupClassification.cancel'),
                type: 'warning'
            })
                .then(() => {
                    var url = '';
                    if (b.selected == 1) {
                        url = this.urlList.unbind;
                    } else if (b.selected == 0) {
                        url = this.urlList.bind;
                    }
                    url;
                    console.log('url at line 278:', url);
                    this.$api
                        .post(url, {
                            journal_issn: b.issn,
                            major_id: this.currentTreeData.major_id
                        })
                        .then(async (res) => {
                            if (res.code == 0) {
                                this.$message({
                                    type: 'success',
                                    message: res.msg
                                });
                            } else {
                                this.$message({
                                    type: 'error',
                                    message: res.msg
                                });
                            }
                        });

                    this.$nextTick(async () => {
                        setTimeout(async () => {
                            await this.getAssociatedJournalList();
                        }, 200);
                    });
                })
                .catch(() => {
                    // this.$message({
                    //     type: 'info',
                    //     message: this.$t('GroupClassification.cancel')
                    // });
                });
        },
        handleClose() {
            this.drawer = false;
        },
        getAssociatedJournalList() {
            this.$api
                .post(this.urlList.AssociatedJournalList, {
                    major_id: this.currentTreeData.major_id
                })
                .then(async (res) => {
                    if (res.code == 0) {
                        this.AssociatedJournalList = res.data.list;
                        console.log('this.AssociatedJournalList at line 234:', this.AssociatedJournalList);
                    } else {
                        this.$message.error(res.msg);
                    }
                })
                .catch((err) => {
                    this.$message.error(err);
                });
        },
        openJournal() {
            this.drawer = true;
            // AssociatedJournalList

            this.getAssociatedJournalList();
        },
        renameKeys(obj, oldKey, newKey) {
            if (obj[oldKey]) {
                obj[newKey] = obj[oldKey];
                delete obj[oldKey];
            }
            for (let k in obj) {
                if (typeof obj[k] === 'object') {
                    this.renameKeys(obj[k], oldKey, newKey);
                }
            }
        },
        // 获取数据
        async getDate() {
            this.$api
                .post(this.urlList.list, {})
                .then(async (res) => {
                    if (res.code == 0) {
                        this.data.children = res.data.majors;

                        await this.renameKeys(this.data.children, 'major_title', 'label');
                        await this.toggleExpand(this.data, true); // 调用全部展开
                    } else {
                        this.$message.error(res.msg);
                    }
                })
                .catch((err) => {
                    this.$message.error(err);
                });
        },

        // 增加千分位
        numFormatter(num) {
            let res = num;
            if (num && num !== null) {
                res = num.toString().replace(/\d+/, (n) => {
                    return n.replace(/(\d)(?=(\d{3})+$)/g, ($1) => {
                        return $1 + ',';
                    });
                });
            }
            return res;
        },
        cccc(a, b) {
            // console.log(a);
            // console.log(b);
        },
        mouseWheelDia() {
            // bugfix 鼠标移入弹层，滚动鼠标不能缩放bug
            this.isShowF = false;
        },
        Mouseover() {
            // 鼠标移入缩放icon
            this.bd = false;
        },
        Mouseout() {
            // 鼠标移出缩放icon
            this.bd = true;
        },
        clearDialog() {
            // 关闭添加/编辑/删除弹层
            this.dialogVisible = false;
            this.dialogVisible2 = false;
            this.ruleForm.major_title = '';
        },
        addOrEdit(val) {
            // 点击添加/编辑
            // 新增val：0，编辑val：1
            this.dialogVisible = true;
            this.isEdit = val;
            // eslint-disable-next-line eqeqeq
            if (val == 1) {
                // 编辑回显
                this.ruleForm = {
                    major_title: this.currentTreeData.label,
                    major_sort: this.currentTreeData.major_sort,
                    major_id: this.currentTreeData.major_id,
                    nickname: this.currentTreeData.nickname
                };
            } else {
                this.ruleForm.pid = this.currentTreeData.major_id;
            }
        },
        async confirm() {
            // 添加/编辑的确定
            this.$refs.ruleForm.validate(async (valid) => {
                if (valid) {
                    if (this.isEdit == 1) {
                        // 编辑
                        // this.ruleForm.major_title =
                        // data.id = this.treeData.id;
                        // this.currentTreeData.label = data.label;

                        this.$api
                            .post(this.urlList.edit, {
                                major_title: this.ruleForm.major_title,
                                major_id: this.ruleForm.major_id,
                                major_sort: this.ruleForm.major_sort,
                                nickname: this.ruleForm.nickname
                            })
                            .then(async (res) => {
                                if (res.code == 0) {
                                    this.$message({
                                        type: 'success',
                                        message: res.msg
                                    });
                                    this.clearDialog();
                                } else {
                                    this.$message({
                                        type: 'error',
                                        message: res.msg
                                    });
                                }
                            });

                        // 前端编辑数据

                        // loading.close();
                    } else {
                        this.$api
                            .post(this.urlList.add, {
                                major_title: this.ruleForm.major_title,
                                pid: this.ruleForm.pid,
                                major_sort: this.ruleForm.major_sort,
                                nickname: this.ruleForm.nickname
                            })
                            .then(async (res) => {
                                if (res.code == 0) {
                                    this.$message({
                                        type: 'success',
                                        message: res.msg
                                    });
                                    this.clearDialog();
                                } else {
                                    this.$message({
                                        type: 'error',
                                        message: res.msg
                                    });
                                }
                            });
                        // 添加
                        // 前端添加数据,需要自己生成子级id,可以传数据的时候把最后一级id传过来,进行累加
                        // data.id = this.lastId++;
                        // // data.level = this.currentTreeData.level + 1;
                        // data.label = this.ruleForm.major_title;
                        // data.expand = true;
                        // const render = (formData) => {
                        //     formData.some((item) => {
                        //         if (item.id === this.currentTreeData.id) {
                        //             if (item.children) {
                        //                 item.children.push(data);
                        //             } else {
                        //                 this.$set(item, 'children', [data]);
                        //             }
                        //         } else if (item.children) {
                        //             render(item.children);
                        //         }
                        //     });
                        // };
                        // const arr = [this.data];
                        // render(arr);
                        // this.data = arr[0];

                        // loading.close();
                    }
                    this.$nextTick(async () => {
                        setTimeout(async () => {
                            await this.getDate();
                        }, 200);
                    });
                } else {
                    // loading.close();
                }
            });
        },
        del() {
            this.dialogVisible2 = true;
        },
        async confimdelete() {
            // 是否确定删除当前节点
            // 前端删除 遍历原数据,删除匹配id数据
            this.$api
                .post(this.urlList.delete, {
                    major_id: this.currentTreeData.major_id
                })
                .then(async (res) => {
                    if (res.code == 0) {
                        this.$message({
                            type: 'success',
                            message: res.msg
                        });
                        this.clearDialog();
                    } else {
                        this.$message({
                            type: 'error',
                            message: res.msg
                        });
                    }

                    this.$nextTick(async () => {
                        setTimeout(async () => {
                            await this.getDate();
                        }, 200);
                    });
                });
            // const deleteData = (data) => {
            //     data.some((item, i) => {
            //         if (item.id === this.currentTreeData.id) {
            //             data.splice(i, 1);
            //         } else if (item.children) {
            //             deleteData(item.children);
            //         }
            //     });
            // };
            // const arr = [this.data];
            // deleteData(arr);
            // this.data = arr[0] ? arr[0] : {};
            // this.dialogVisible2 = false;
            // this.$message({
            //     type: 'success',
            //     message: '节点删除成功！'
            // });
        },
        onMouseover(e, data) {
            var collapse = localStorage.getItem('collapse');
            var width = Number(e.clientX - (!collapse || collapse == 'false' ? 260 : 40));

            // 鼠标移入树节点
            this.currentTreeData = data; // 鼠标移入，该节点的所有数据

            this.isShowF = true;
            var floating = document.getElementsByClassName('floating')[0];
            if (floating) {
                floating.style.left = width + 'px';
                floating.style.top = e.clientY - 80 + 'px';
            }
        },
        onMouseout(e, data) {
            // 鼠标移出树节点
            this.isShowF = false;
        },
        renderContent(h, data) {
            return data.label;
        },
        onExpand(e, data) {
            // 节点展开收缩
            // eslint-disable-next-line eqeqeq
            if (data.leave == 1 && data.expand == true) {
                // bugfix
                var dom = document.getElementById('ddd');
                (dom.style.top = '50%'), (dom.style.left = '8%');
            }
            if ('expand' in data) {
                data.expand = !data.expand;
                if (!data.expand && data.children) {
                    this.collapse(data.children);
                }
            } else {
                this.$set(data, 'expand', true);
            }
        },
        collapse(list) {
            list.forEach((child) => {
                if (child.expand) {
                    child.expand = false;
                }

                child.children && this.collapse(child.children);
            });
        },
        toggleExpand(data, val) {
            // 节点默认全部展开
            var _this = this;
            // console.log(data);
            if (Array.isArray(data)) {
                data.forEach(function (item) {
                    _this.$set(item, 'expand', val);
                    if (item.children) {
                        _this.toggleExpand(item.children, val);
                    }
                });
            } else {
                this.$set(data, 'expand', val);
                if (data.children) {
                    _this.toggleExpand(data.children, val);
                }
            }
        }
    }
};
</script>
<style lang="less" scoped>
.floating {
    background: rgba(0, 0, 0, 0.7);
    box-shadow: rgba(0, 0, 0, 0.2);
    width: auto;
    // height: 45px;
    line-height: 24px;
    // display: flex;
    // justify-content: space-around;
    position: absolute;
    color: #fff;
    border-radius: 5px;
    box-sizing: border-box;
    left: 0;
    top: 0;
    transition: all 0.3s;
    z-index: 999;
    font-size: 12px;
    padding: 6px;
    span {
        cursor: pointer;
    }
}
</style>
<style lang="less">
.addOrEditDia,
.delDia {
    padding: 14px 18px 10px 18px;
    border-radius: 4px !important;
    .el-dialog__header {
        display: flex;
        justify-content: space-between;
        padding: 20px 0 !important;
    }
    .el-dialog__body {
        padding: 0;
        padding-top: 20px;
        // margin-top: 37px;
    }
    .el-dialog__footer {
        padding: 27px 0 9px 0 !important;
    }
    .el-dialog__headerbtn {
        position: static !important;
    }
}
.bg-white {
    background-color: white;
}
.bg-orange {
    background-color: orange;
}
.bg-gold {
    background-color: gold;
}
.bg-gray {
    background-color: gray;
}
.bg-lightpink {
    background-color: lightpink;
}
.bg-chocolate {
    background-color: chocolate;
}
.bg-tomato {
    background-color: tomato;
}
.outBox {
    height: calc(100% - 100px) !important;
    margin-top: 10px;
    width: calc(100% - 40px) !important;
    overflow: auto !important;
}
</style>
