<template>
    <div>
        <h1 style="text-align: center">菜单管理</h1>
        <el-divider><i class="el-icon-menu"></i></el-divider>
        <!--模糊查询-->
        <h5>菜单名称 、访问地址</h5>
        <el-input
                placeholder="关键字查询"
                v-model="input"
                maxlength="30"
                show-word-limit
                style="width: 15%"
                clearable>
        </el-input>
        &nbsp
        <el-button type="info"  icon="el-icon-search" size="small" @click="kwSearch" round>搜索</el-button>
<!--增加菜单-->
        <el-button type="primary" @click="addMenuBtn" round size="small"><i class="el-icon-circle-plus-outline"></i> 新增</el-button>
<!--菜单管理-->
        &nbsp
        <br><br>
        <el-table
                ref="multipleTable"
                stripe border fit highlight-current-row
                @selection-change="handleSelectionChange"
                :data="list"
                height="961"
                style="width: 100%">
            <el-table-column type="index"    label="序号"    width="240" align="center"></el-table-column>
            <el-table-column prop="label"    label="菜单名称" width="240" align="center"></el-table-column>
            <el-table-column prop="address"  label="访问地址" width="240" align="center"></el-table-column>
            <el-table-column prop="icon"     label="图标"     width="240" align="center"></el-table-column>
            <el-table-column prop="fid"      label="父节点"   width="280" align="center"></el-table-column>
            <!--编辑、删除-->
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button
                            size="small"
                            type="info"
                            @click="handleEdit(scope.$index, scope.row)">
                        <i class="el-icon-edit"></i>编辑</el-button>
                    <el-button
                            size="small"
                            type="danger"
                            @click="handleDelete(scope.$index, scope.row)">
                        <i class="el-icon-delete"></i>_删除</el-button>
                </template>
            </el-table-column>
        </el-table>
<!--菜单表-编辑弹窗层-->
        <el-dialog
                :show-close="false"
                :close-on-press-escape="false"
                title="更新菜单"
                :visible.sync="dialogVisible"
                width="75%">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
<!--菜单名称-->
                <el-form-item label="菜单名称" prop="label">
                    <el-input v-model.lazy="form.label" style="width: 15%"></el-input>
                </el-form-item>
<!--访问地址-->
                <el-form-item label="访问地址" prop="address">
<!--                    <el-input v-model.lazy="form.address" style="width: 15%" :disabled="true"></el-input>-->
                    <el-input v-model.lazy="form.address" style="width: 15%"></el-input>
                </el-form-item>
<!--图标-->
                <el-form-item label="图标" prop="icon">
                    <el-input type="text" v-model.lazy="form.icon" style="width: 20%"></el-input>
                </el-form-item>
<!--节点选择-->
                <el-form-item label="节点选择" prop="fid">
                    <el-select v-model="form.fid" placeholder="请选择">
                        <el-option
                                v-for="item in rewriteArr"
                                :label="item.label"
                                :value="item._id">
                        </el-option>
                    </el-select>
                </el-form-item>
<!--立即创建/取消-->
                <el-form-item>
                    <el-button type="primary" @click="updateFoodClick" round>更新信息</el-button>
                    <el-button type="primary" @click="cancelUpdateFoodClickBtn" round>取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

<!--菜单信息-新增弹窗层-->
        <el-dialog
                title="新增菜单"
                :visible.sync="dialogVisibleAdd"
                width="50%">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
<!--菜单名称-->
                <el-form-item label="菜单名称" prop="label">
                    <el-input v-model="form.label" style="width: 25%"></el-input>
                </el-form-item>
<!--访问地址-->
                <el-form-item label="访问地址" >
                    <el-input v-model="form.randomAddress" style="width: 25%" :disabled="false"></el-input>
                </el-form-item>
<!--图标-->
                <el-form-item label="图标">
                    <el-input type="text" v-model="form.icon" style="width: 40%"></el-input>
                </el-form-item>
<!--父节点测试-->
                <el-form-item label="节点选择" prop="fid">
                    <el-select v-model="form.fid" placeholder="请选择">
                        <el-option
                                v-for="item in rewriteArr"
                                :label="item.label"
                                :value="item._id">
                        </el-option>
                    </el-select>
                </el-form-item>
<!--立即创建/取消-->
                <el-form-item>
                    <el-button type="primary" @click="createMenuInfo" round>新增</el-button>
                    <el-button type="warning" @click="cancelBtnClick" round>取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
<!--底部说明-->
        <footer>
            <p>{{CopyRight}}</p>
        </footer>
    </div>
</template>

<script>
    const axios=require('axios');
    import Cookies from 'js-cookie';
    export  default {
        data(){
            return {
                updateDialogStatus:false,
                rewriteArr:[],
                menuList:[],
                menuFatherChildren:['父节点','子节点'],
                dialogVisible: false,
                dialogVisibleAdd: false,
                list:[],
                input: '',
                CopyRight:'2020  Menu  Vue  Demo ! ',
                form: {
                    randomAddress:'',
                    _id:'',
                    label:'',
                    icon:'',
                    fid:'',
                    address:'',
                },
                rules:{
                    label:[
                        {required:true,message:'请填菜单名称',trigger:'blur'}
                    ],
                    address:[
                        {required:true,message:'请填写访问地址',trigger:'blur'}
                    ],
                    fid:[
                        {required:true,message:'请选择节点',trigger:'blur'}
                    ],
                }
            }
        },
        created() {
            const arr=[];

            this.getInfo();
            axios.post('https://mz.tshe.cn/restauantCH/menu/find')
                .then((res)=>{
                    this.menuList=this.putTree(res.data.data);
                    this.menuList.push({label:'父节点',_id:0})

                    //更改模式
                    for (let i=0;i<this.menuList.length;i++){
                        if(this.menuList[i].label!='父节点'){
                            arr.push({label:'子节点-'+this.menuList[i].label,_id:this.menuList[i]._id})
                        }
                        else{
                            arr.push({label:this.menuList[i].label,_id:String(this.menuList[i]._id)})
                        }
                    }
                    this.rewriteArr=arr;
                })
        },
        methods:{
            //获取信息
            getInfo(){
                axios.post('https://mz.tshe.cn/restauantCH/menu/find')
                    .then((res)=>{
                        this.list=res.data.data;
                    })
            },
            //val 为选中数据的集合
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            //单个删除
            handleDelete(index, row) {
                if (confirm('确定要删除吗') == true) {
                    axios.post('https://mz.tshe.cn/restauantCH/menu/remove', {_id: row._id})
                        .then((res) => {
                            this.$message.success('删除成功!')
                            let that = this;
                            setTimeout(function () {
                                that.getInfo();
                            }, 300);
                        })
                }
            },
            //编辑-弹窗信息
            handleEdit(index, row) {
                this.dialogVisible = true;
                // this.form = row;  //把这一行的值赋值给form
                this.form = {
                    randomAddress:row.randomAddress,
                    _id:row._id,
                    label:row.label,
                    icon:row.icon,
                    fid:row.fid,
                    address:row.address
                };

            },
            //编辑-修改事件
            updateFoodClick() {
                axios.post('https://mz.tshe.cn/restauantCH/menu/updateOne',
                    {
                    _id: this.form._id,
                    label: this.form.label,
                    address: this.form.address,
                    icon: this.form.icon,
                    fid:this.form.fid
                })
                    .then((res) => {
                        if(res.data.code==0){
                            this.$message.success(res.data.msg);

                            this.dialogVisible = false;
                            this.form.label='';
                            this.form.icon='';
                            this.form.address='';
                            this.form.fid='';

                            let that = this;
                            setTimeout(function () {
                                that.getInfo();
                            }, 300);
                        }
                        else if(res.data.code==-1){
                            this.$message.error(res.data.msg);
                        }
                        else if(res.data.code==-2){
                            this.$message.error(res.data.msg);
                        }
                        else if(res.data.code==-3){
                            this.$message.error(res.data.msg);
                        }
                        else if(res.data.code==-4){
                            this.$message.error(res.data.msg);
                        }
                        else if(res.data.code==-5){
                            this.$message.error(res.data.msg);
                        }
                        else if(res.data.code==-6){
                            this.$message.error(res.data.msg);
                        }
                    })
                    .catch((err)=>{
                        console.log(err,'err')
                    })
            },
            cancelUpdateFoodClickBtn(){
                this.dialogVisible=false;
                this.getInfo();
            },
            addMenuBtn(){
                this.form.label='',
                this.form.icon='',
                this.form.address='',
                this.form.fid='',
                this.dialogVisibleAdd =true;
            },
            //弹窗-增加菜单按钮
            createMenuInfo(){
                const randomAddress=parseInt((Math.random()*9+1)*100000);
                const data=new Date().getTime()
                const randomDataStr=`#${String(data)+String(randomAddress)}`;
                this.form.randomAddress=randomDataStr;
                console.log(this.form.randomAddress,'this.form.randomAddress')

                axios.post('https://mz.tshe.cn/restauantCH/menu/addOne',{
                    label:this.form.label,
                    address:this.form.randomAddress,
                    icon:this.form.icon,
                    fid:this.form.fid,
                })
                    .then((res)=>{
                        console.log(res,'res.data');
                        if(res.data.code==0){
                            this.$message.success(res.data.msg);
                            this.dialogVisibleAdd = false;
                            this.form.label='';
                            this.form.icon='';
                            this.form.address='';
                            this.form.fid='';
                            let that = this;
                            setTimeout(function () {
                                that.getInfo();
                            }, 300);
                        }
                        else if(res.data.code==-1){
                            this.$message.error(res.data.msg);
                        }
                        else if(res.data.code==-2){
                            this.$message.error(res.data.msg);
                        }
                        else if(res.data.code==-3){
                            this.$message.error(res.data.msg);
                        }
                        else if(res.data.code==-4){
                            this.$message.error(res.data.msg);
                        }
                        else if(res.data.code==-5){
                            this.$message.error(res.data.msg);
                        }
                        else if(res.data.code==-6){
                            this.$message.error(res.data.msg);
                        }
                        else if(res.data.code==-7){
                            this.$message.error(res.data.msg);
                        }
                    })
            },
            //弹窗-取消按钮
            cancelBtnClick(){
                this.form.label='',
                this.form.icon='',
                this.form.address='',
                this.form.fid='',
                this.dialogVisibleAdd=false;
            },
            //关键字搜索
            kwSearch(){
                axios.post('https://mz.tshe.cn/restauantCH/menu/kwSearch',{
                    kw:this.input
                })
                    .then((res)=>{
                        if(res.data.code==-2){
                            this.$message.error(res.data.msg);
                        }
                        else if(res.data.code==-1){
                            this.$message.error(res.data.msg);
                        }
                        else if(res.data.code==0){
                            this.$message.success(res.data.msg);
                            this.list=res.data.data;
                        }
                    })
            },
            putTree(arr,child='_id',father='fid',mostKey='0',childKey='children'){

                let map = {};
                // map是映射的意思，将一个数组映射成一个新数组。
                // h[key]返回映射h中的自变量key映射到的value的值

                let resultArr = [];
                arr.forEach((item) => {
                    item[childKey] = [];  //让所有的item中，每条数据增加一条children:{type:[]} 字段；children的作用是，放孩子路由
                    map[item[child]] = item;
                });
                // console.log(map,'map')

                arr.forEach((item) => {
                    if (item[father]){ //如果二级路由的Key存在
                        if (item[father] == mostKey) {   //如果 二级路由的Key==0 (说明此条item是一级路由)
                            resultArr.push(item);     //就添加到resultArr数组里;
                        }
                        else {//如果二级路由的Key != 0； 说明此条item是二级路由
                            map[item[father]][childKey].push(item);//为什么可以push，因为item里的children字段，是一个[数组]格式
                        }
                    }
                });
                return resultArr;
            },
        }
    }
</script>
