<template>
    <div class="DeviceType">
        <el-button size="mini" type="primary" @click="isShowDialog=true">新建分类</el-button>
        <hr class="hr"/>
        <el-tree
            class="filter-tree"
            :data="typeDataTree"
            :props="defaultProps"
            @node-click="handleNodeClick"
            ref="tree"
        ></el-tree>
        <el-dialog title="新建分类" :visible.sync="isShowDialog" append-to-body>
            <el-form :model="formData" label-width="100px">
                <el-form-item label="父分类：">
                    <el-select
                        :disabled="isRoot"
                        v-for="(arrItem,key) in selectList"
                        :key="key"
                        v-model="selectArr[key]"
                        filterable
                        placeholder="请选择"
                        value-key="id"
                        @change="selectedEvt"
                        @focus="position=key"
                    >
                        <el-option
                            v-for="item in arrItem"
                            :key="item.id"
                            :value="item.id"
                            :label="item.name"
                        ></el-option>
                    </el-select>
                    <el-checkbox v-model="isRoot" style="margin-left: 10px">根目录</el-checkbox>
                </el-form-item>
                <el-form-item label="分类名称：">
                    <el-input v-model="formData.name" placeholder="请输入名称"></el-input>
                </el-form-item>
                <el-form-item label="配置数据：">
                    <el-input type="textarea" v-model="formData.meta" autosize placeholder="请输入内容,JSON格式"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="isShowDialog=false">取 消</el-button>
                <el-button type="primary" @click="handleSave">保 存</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { mapActions } from "vuex";
// tree配置选项 
const defaultProps = { children: "children", label: "name" };

export default {
    name: "DeviceType",
    data() {
        return {
            isShowDialog: false,
            isRoot: false,
            position: null,
            selectArr: [],
            selectList: [],
            formData: {
                name: "",
                meta: ""
            },
            typeDataTree: [], // tree 数据
            selectedItem: null,
            // tree配置选项
            defaultProps
        };
    },
    mounted() {
        this.loadTypes(); //根级别分类
    },
    watch: {
        filterText(val) {
            this.$refs.tree.filter(val);
        },
        selectArr(ov, nv) {
            console.log("selectArr", ov, nv);
        },
        isRoot(ov, nv) {
            console.log("isRoot", ov, nv);
            if (ov) {
                //清理所有选择
                this.selectList.splice(1, this.selectList.length);
                this.selectArr.splice(0, this.selectArr.length);
            }
        }
    },
    methods: {
        ...mapActions(["fetch"]),
        loadTypes(pid) {
            this.fetch({
                api: "/device/device-type/list-parent",
                method: "GET",
                data: { parentId: pid },
                success: res => {
                    console.log(res)
                    if (pid > 0) {
                        let p = this.findTypesByid(
                            { id: -1, children: this.typeDataTree },
                            pid
                        );
                        if (p) this.$set(p, "children", res);
                        //这里的切入点很特别，需要等待截取数据后再加入
                        let arr = [];
                        for (let i = 0; i < res.length; i++) {
                            arr.push({ id: res[i].id, name: res[i].name });
                        }
                        if (arr.length > 0)
                            this.selectList.splice(
                                this.position + 1,
                                this.selectList.length,
                                arr
                            );
                        else
                            this.selectList.splice(
                                this.position + 1,
                                this.selectList.length
                            );
                        this.selectArr.splice(
                            this.position + 1,
                            this.selectArr.length
                        );
                    } else {
                        this.typeDataTree = res;
                        // 初始化第一级
                        let arr = [];
                        for (let i = 0; i < res.length; i++) {
                            arr.push({ id: res[i].id, name: res[i].name });
                        }
                        this.selectList.push(arr);
                    }
                },
                fail: err => {
                    console.log("loadTypes");
                    console.log(err);
                    if (err.errMsg) this.$message.error(err.errMsg);
                    else this.$message.error("服务器发生异常");
                }
            });
        },
        findTypesByid(root, id) {
            if (!root) return null;
            else if (root.id === id) return root;
            else if (root.children) {
                for (let i = 0; i < root.children.length; i++) {
                    let ret = this.findTypesByid(root.children[i], id);
                    if (ret) return ret;
                }
                return null;
            } else return null;
        },
        // 节点被点击时的回调
        handleNodeClick(e) {
            console.log(e);
            // 获取下一级列表
            this.loadTypes(e.id);
            setTimeout(() => {
                // this.handleNodeClick(e)
            }, 1000);
            // let count = 0
            // if(count++ == 0) {
            //     this.handleNodeClick()
            // }else return
        },
        selectedEvt(item) {
            console.log("看看啥", item, this.position);
            // 获取下一级列表
            this.loadTypes(item);
        },
        handleSave(e) {
            console.log(e);
            let data = { name: this.formData.name, meta: this.formData.meta };
            if (!this.isRoot)
                data.parentId = this.selectArr[this.selectArr.length - 1];
            this.fetch({
                api: "/device/device-type/add",
                data,
                success: res => {
                    console.log(res);
                    this.$message.info("添加成功！");
                    this.isShowDialog = false; //关闭
                    //页面所有数据初始化
                    this.init();
                },
                fail: err => {
                    console.log(err);
                    if (err.errMsg) this.$message.error(err.errMsg);
                    else this.$message.error("服务器发生异常");
                }
            });
        },
        init() {
            this.selectArr.splice(0, this.selectArr.length);
            this.selectList.splice(0, this.selectList.length);
            this.position = null;
            this.loadTypes(-1); //加载根
        }
    }
};
</script>

<style lang="scss" scoped>
.DeviceType{
    .hr{
        border-top: 2px solid #eee;
        margin: 10px 0;
    }
}
</style>

