<template>
    <div class="AreaInfo">
        <el-button class="top_btn" size="mini" type="primary" @click="isShowDialog=true">区域信息管理</el-button>

        <el-tree
            class="filter-tree"
            :data="areaInfoTree"
            :props="defaultProps"
            @node-contextmenu="mouseRightCilck"
            ref="tree"
            slot="reference"
        ></el-tree>

        <el-dialog width="40%" title="区域信息管理" :visible.sync="isShowDialog" append-to-body>
            <el-form :model="formData" label-width="100px">
                <el-form-item label="所属区域：">
                    <div>
                        <p class="hint" style="color: rgb(250, 80, 61)">提示：选择好后，点击旁白就会选中！</p>

                        <el-row type="flex">
                            <el-col :span="9">
                                <el-cascader
                                    :options="areaInfoTree"
                                    :props="{ children: 'children', label: 'name' ,value:'id'}"
                                    @expand-change="handleChange"
                                    @change="change"
                                    :placeholder="cascaderPlaceholder"
                                ></el-cascader>
                            </el-col>
                            <el-col :span="6">
                                <el-popconfirm
                                    title="删除此区域信息？"
                                    @onConfirm="onConfirmDelAll"
                                    @onCancel="onConfirmDel"
                                    confirmButtonText="全部删除"
                                    cancelButtonText="不删除所属区域"
                                >
                                    <el-button type="primary" slot="reference">删除此区域</el-button>
                                </el-popconfirm>
                            </el-col>
                        </el-row>
                    </div>
                </el-form-item>

                <el-form-item label="区域名字：">
                    <el-row type="flex">
                        <el-col :span="13">
                            <el-input v-model="formData.name" placeholder="请填写所属区域名"></el-input>
                        </el-col>
                    </el-row>
                </el-form-item>

                <el-form-item>
                    <el-row type="flex">
                        <el-col :span="4">
                            <el-button @click="isShowDialog=false">取 消</el-button>
                        </el-col>
                        <el-col :span="6">
                            <el-button type="primary" @click="addAreaInfo">添加所属区域</el-button>
                        </el-col>
                        <el-col :span="6">
                            <el-popconfirm title="删除此区域信息？" @onConfirm="onConfirmEdit">
                                <el-button type="primary" slot="reference">修 改</el-button>
                            </el-popconfirm>
                        </el-col>
                    </el-row>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
import { mapActions } from "vuex";

export default {
    name: "AreaInfo",
    data() {
        return {
            isShowDialog: false,
            selectArr: [],
            selectList: [],
            cascaderPlaceholder: "请选择/不选择默认根级",
            formData: {
                parentId: "-1",
                name: "",
                orgId: "1"
            },
            areaInfoTree: [], // tree 数据
            selectedItem: null,
            // tree配置选项
            defaultProps: { children: "children", label: "name" }
        };
    },
    mounted() {
        this.loadTypes();
    },
    watch: {},
    methods: {
        ...mapActions(["fetch"]),
        // 加载所有场地信息列表
        loadTypes() {
            this.fetch({
                api: "/core/organize-structure/list",
                method: "GET",
                data: { orgId: 1 },
                success: res => {
                    this.areaInfoTree = this.findTypesByid(res, -1);
                },
                fail: err => {
                    console.log(err);
                    if (err.errMsg) this.$message.error(err.errMsg);
                    else this.$message.error("服务器发生异常");
                }
            });
        },
        // loadTypes 函数的工具函数
        findTypesByid(resArr, pid) {
            let temArr = [];
            resArr.forEach(item => {
                if (item.parentId == pid) {
                    temArr.push(item);
                    item.children = this.findTypesByid(resArr, item.id);
                }
            });
            if (temArr.length > 0) return temArr;
        },

        // 树形节点 鼠标右键点击事件
        mouseRightCilck(event, data, Node, me) {
            console.log(data);
        },

        // 级联选择器点击事件
        handleChange(value) {
            console.log(value);
            this.formData.parentId = value[value.length - 1];
            console.log("a==>>" + this.formData.parentId);
            // 级联选择时 因组件限制 需拼接 名字字符串在级联选择器上显示
            this.findAreaName(value);
        },
        change(value) {
            console.log("aa");
            console.log(value);
            this.formData.parentId = value[value.length - 1];
            console.log("a==>>" + this.formData.parentId);
        },
        // 级联选择时 因组件限制 需拼接 名字字符串在级联选择器上显示
        findAreaName(tree) {
            let i = 0;
            let tmpStr = "";
            find(this.areaInfoTree);
            function find(subTree) {
                subTree.forEach(item => {
                    if (item.id == tree[i]) {
                        tmpStr += item.name + "/";
                        if (
                            i < tree.length &&
                            item.children &&
                            item.children.length > 0
                        ) {
                            i++;
                            find(item.children);
                        }
                    }
                });
            }
            console.log(tmpStr);
            this.cascaderPlaceholder = tmpStr;
        },

        // 保存区域信息
        addAreaInfo(e) {
            if (!this.formData.name) {
                this.$message.error("请填写所属区域名！");
                return;
            }
            console.log(this.formData);
            this.fetch({
                api: "/core/organize-structure/add",
                method: "POST",
                data: this.formData,
                success: res => {
                    console.log(res);
                    this.$message.success("添加成功！");
                    this.formData.name = "";
                    // 加载所有场地信息列表
                    this.loadTypes();
                },
                fail: err => {
                    console.log(err);
                    if (err.errMsg) this.$message.error(err.errMsg);
                    else this.$message.error("服务器发生异常");
                }
            });
        },
        // 删除区域信息（删除子节点）
        onConfirmDelAll() {
            console.log("删除区域信息（删除子节点）");
            const url = "/core/organize-structure/delete-refer";
            const id = this.formData.parentId;
            if (id) {
                this.doDel(url, id);
            } else {
                this.$message.fail("没有选择对应要删除的区域");
            }
        },
        // 删除区域信息（不删除子节点）
        onConfirmDel() {
            console.log("删除区域信息（不删除子节点）");
            const url = "/core/organize-structure/delete";
            const id = this.formData.parentId;
            if (id) {
                this.doDel(url, id);
            } else {
                this.$message.fail("没有选择对应要删除的区域");
            }
        },
        // 删除区域信息 总函数
        doDel(url, id) {
            console.log("ID===>>>" + id);
            this.fetch({
                api: url,
                method: "POST",
                data: { id },
                success: res => {},
                fail: err => {
                    console.log(err);
                    if (err.errCode == 200) {
                        // 加载所有场地信息列表
                        this.loadTypes();
                        this.$message.success(err.errMsg);
                    } else if (err.errMsg) {
                        this.$message.error(err.errMsg);
                    } else this.$message.error("服务器发生异常");
                }
            });
        },
        // 确认修改
        onConfirmEdit() {
            const id = this.formData.parentId;
            const name = this.formData.name;
            if (!name) {
                this.$message.warning("区域名字不能为空！");
                return;
            }
            this.fetch({
                api: "/core/organize-structure/update",
                method: "POST",
                data: { id, name },
                success: res => {
                    console.log(res);
                    // 加载所有场地信息列表
                    this.loadTypes();
                    this.$message.success("编辑区域信息成功！");
                },
                fail: err => {
                    console.log(err);
                    if (err.errMsg) this.$message.error(err.errMsg);
                    else this.$message.error("服务器发生异常");
                }
            });
        }
    }
};
</script>

<style lang="scss" scoped>
.AreaInfo {
    .top_btn {
        margin-bottom: 20px;
    }
}
</style>

