"use strict";
import { util } from '../../util/util.js'
import {verify} from '../../util/verify.js'
import {khcToastr} from "../alert/khcToastr.js";
import {config} from "../../config.js";
import {fullMap} from "../../fullMap.js";
import {httpUtil} from "../../util/httpUtil.js";

class menu {
    constructor(data) {
        this.data=data.menuList
        this.showMenuStyleConfig1=config.getConfigJson().showMenuStyleConfig1;
        this.showMenuStyleConfig2=config.getConfigJson().showMenuStyleConfig2;
        this.showMenuStyleConfig3=config.getConfigJson().showMenuStyleConfig3;
        this.codeArray=[];
    }
    render() {
        let that=this;
        return new Promise((resolve, reject) => {
            this.showMenuIconLevel=that.data[0].menu_level;
            let menuHtml=that.getMenuHtml(that.data);
            document.getElementById('showMenu').innerHTML='';
            document.getElementById('showMenu').insertAdjacentHTML("beforeEnd", menuHtml);
            new PerfectScrollbar(document.getElementById('showMenu'));
            document.getElementById('showMenu').querySelectorAll('a[name="childMenu"]').forEach(item => {
                item.addEventListener('click', event => {
                    if(item.parentNode.className.includes('disabled')){//当前禁用状态，不操作
                        return ;
                    }
                    //打开和折叠
                    if(item.parentNode.className=='sidenav-item'){
                        if(item.parentElement.parentElement.className=='sidenav-inner py-1 ps'){//判断是否打开一级菜单如果是则隐藏收起其他一级菜单
                            let firstLevelArray=document.getElementById('showMenu').children;
                            for (let i = 0; i < firstLevelArray.length; i++) {
                                firstLevelArray[i].className='sidenav-item';
                            }
                        }
                        item.parentNode.className+=' open';
                    }else{
                        item.parentNode.className='sidenav-item';
                    }
                });
            });
            //给系统名称左侧的图标添加事件点击隐藏左侧菜单，再次点击则展示
            document.getElementById('menuIcon').addEventListener('click',()=> {
                let htmlClassName=document.querySelector('html').className;
                if(htmlClassName==this.showMenuStyleConfig3){//
                    document.querySelector('html').className='default-style layout-offcanvas layout-collapsed';//小屏幕点击左侧icon时隐藏
                    setTimeout(()=>{
                        document.querySelector('html').className=this.showMenuStyleConfig2;//0.5秒后将左侧菜单设置为小icon菜单（注：只有分辨率大时生效）
                    },500)
                }else if(htmlClassName==this.showMenuStyleConfig2){
                    document.querySelector('html').className=this.showMenuStyleConfig1;
                }else if(htmlClassName==this.showMenuStyleConfig1){
                    document.querySelector('html').className=this.showMenuStyleConfig2;
                }
            })
            that.initActiveMenu(that.data)
            that.setDisabled(3000);//禁用菜单，并在三秒后解除禁用
            resolve();
        });
    }
    getMenuHtml(menuList){
        let htmlTemplate=``;
        for (let i = 0; i < menuList.length; i++) {
            if(menuList[i].menu_child.length>0){
                let iconHtml=``;
                if(this.showMenuIconLevel==menuList[i].menu_level&&menuList[i].menu_icon.length>0){
                    iconHtml += `<i class="sidenav-icon ${menuList[i].menu_icon}"></i>`;
                }
                htmlTemplate+=`
                <li class="sidenav-item">
                <a href="javascript:void(0)"  name="childMenu" class="sidenav-link sidenav-toggle">
                ${iconHtml}
                <div>${menuList[i].menu_name}</div>
                <div class="pl-1 ml-auto" id="${menuList[i].uuid}"></div>
                </a>
                <ul class="sidenav-menu">
                ${this.getMenuHtml(menuList[i].menu_child)}
                </ul>`
            }else{
                this.codeArray.push(menuList[i].menu_page);
                let iconHtml=``;
                if(this.showMenuIconLevel==menuList[i].menu_level&&menuList[i].menu_icon.length>0){
                    iconHtml += `<i class="sidenav-icon ${menuList[i].menu_icon}"></i>`;
                }
                htmlTemplate+=`
                <li class="sidenav-item" id="${menuList[i].menu_page}">
                <a id="${menuList[i].menu_page}" href="javascript:void(0)" class="sidenav-link">
                ${iconHtml}
                <div>${menuList[i].menu_name}</div>
                <div class="pl-1 ml-auto" id="${menuList[i].uuid}"></div>
                </a>`
            }
            htmlTemplate += `</li>`;
        }
        return htmlTemplate;
    }
    //初始化绑定选中左侧菜单事件
    initActiveMenu(menuList){
        let that=this;
        for (let i = 0; i < menuList.length; i++) {
            if(menuList[i].is_show_num=='Y'){//查询菜单num数量提示
                if(menuList[i].show_num_data_type=='1'){//todo 这里后续有时间调整一下，代码冗余了
                    let mJson=JSON.parse(menuList[i].m_json)
                    let backgroundColor=util.getColorByName(menuList[i].show_num_color);
                    let title='';
                    if(!util.isNull(menuList[i].show_num_template)){
                        title=menuList[i].show_num_template.replace('${data}',mJson.data);
                    }else{
                        title=mJson.data
                    }
                    let html=`<div class="badge badge-primary" style="background-color: ${backgroundColor};" title="${title}">${mJson.data}</div>`;
                    document.getElementById(menuList[i].uuid).innerHTML=html;
                }
                if(menuList[i].show_num_data_type=='2'||menuList[i].show_num_data_type=='3'){
                    let params = { version: '1.0.0', dsCode: 'ds_system_menu',queryCode:'query_menu', methodName: 'getMenuShowNum'}
                    params.uuid=menuList[i].uuid;
                    let obj={url:config.getConfigJson().myActionUrl,params:params}
                    httpUtil.post(obj, (response)=>{
                        let menuInfo=response.data.data.menuInfo;
                        //${menuList[i].menu_page=='page_project'?`<div class="badge badge-primary" style="background-color: #d9534f;" title="59">59</div>`:''}
                        if(!util.isNull(menuInfo.data)&&menuInfo.data!=0){
                            let backgroundColor=util.getColorByName(menuInfo.show_num_color);
                            let title='';
                            if(!util.isNull(menuInfo.show_num_template)){
                                title=menuInfo.show_num_template.replace('${data}',menuInfo.data);
                            }else{
                                title=menuInfo.data
                            }
                            let html=`<div class="badge badge-primary" style="background-color: ${backgroundColor};" title="${title}">${menuInfo.data}</div>`;
                            document.getElementById(menuInfo.uuid).innerHTML=html;
                        }
                    })
                }
            }
            if(menuList[i].menu_child.length>0){
                this.initActiveMenu(menuList[i].menu_child);
            }else if(!util.isNull(menuList[i].menu_page)){//绑定单击事件
                let menuEleObj= document.getElementById(menuList[i].menu_page);
                menuEleObj.addEventListener('click',()=>{
                    if(menuEleObj.className.includes('disabled')){
                        khcToastr.showErrorMessage({msg:'操作频繁'})
                        return ;
                    }
                    let home=fullMap.getObj('home');
                    if(home.pageCode==menuList[i].menu_page){
                        window.location.href=config.getIndexUrl()+'?pageCode='+menuList[i].menu_page+'&queryInfo=%7B%7D';
                    }else{
                        util.setSessionStorageItem('pageCode',`?pageCode=${menuList[i].menu_page}&queryInfo=%7B%7D`);
                        window.location.href=config.getIndexUrl()+'#'+menuList[i].menu_page;
                    }
                    that.setActiveMenuByCode(menuList[i].menu_page)
                    //url直接访问的将当前菜单设置为选中 未做
                    //console.log(that.codeArray.includes('page_todo'))
                })
            }
        }
    }
    //根据code选中菜单，并自动展开父级菜单
    setActiveMenuByCode(code){
        let that=this;
        let eleObj=document.getElementById(code)
        if(eleObj==null||eleObj.className.includes('disabled')){
            return ;
        }
        that.removeActiveMenu();
        //将当前菜单设置为选中
        eleObj.className='sidenav-item active';
        let parentLi = eleObj.parentElement.parentElement;
        if (parentLi && parentLi.classList.contains('sidenav-item')) {
            parentLi.classList.add('open');
        }
    }
    //清空选中
    removeActiveMenu(){
        let that=this;
        for (let j = 0; j < that.codeArray.length; j++) {
            let eleObj=document.getElementById(that.codeArray[j])
            if(eleObj!=null){
                for (let k = 0; k < eleObj.classList.length; k++) {
                    if(eleObj.classList[k]=='active'){
                        eleObj.classList.remove('active');
                    }
                }
            }
        }
    }
    //立即禁用，removeTimeout是什么时间后关闭禁用
    setDisabled(removeTimeout){
        let that=this;
        /*let menuLi=document.getElementById('showMenu').querySelectorAll('li')
        for (let i = 0; i < menuLi.length; i++) {
            let liEle=menuLi[i];
            liEle.classList.add('disabled');
        }*/
        if(!util.isNull(removeTimeout)){
            setTimeout(()=>{
                that.removeDisabled();
            },removeTimeout)
        }
    }

    /**
     * @param timeout 延迟时间
     */
    removeDisabled(timeout){
        if(util.isNull(timeout)){
            timeout=0
        }
        setTimeout(()=>{
            let menuLi=document.getElementById('showMenu').querySelectorAll('li')
            for (let i = 0; i < menuLi.length; i++) {
                let liEle=menuLi[i];
                liEle.classList.remove('disabled');
            }
        },timeout)
    }
}
export { menu }
