"use strict";
import {util} from "../../util/util.js";
import {config} from "../../config.js";

class menuSettingsConfig{

    static getMenuSettingsConfigJson(){
        if(!util.isNull(this.menuSettingsConfigJson)){
            return this.menuSettingsConfigJson;
        }

        const configJson = config.getConfigJson();
        this.menuSettingsConfigJson = {};
        this.menuSettingsConfigJson.navbarFixed = this.getStoredOrDefault('themeSettingsFixedNavbar', configJson.navbarFixed);
        this.menuSettingsConfigJson.sidenavFixed = this.getStoredOrDefault('themeSettingsFixedSidenav', configJson.sidenavFixed);
        this.menuSettingsConfigJson.navbarTheme = this.getStoredOrDefault('themeSettingsNavbarBg', configJson.navbarTheme);
        this.menuSettingsConfigJson.sidenavTheme = this.getStoredOrDefault('themeSettingsSidenavBg', configJson.sidenavTheme);

        this.menuSettingsConfigJson.settingsTemplate = `<div id="theme-settings">
  <a href="javascript:void(0)" class="theme-settings-open-btn" tabindex="-1" id="theme-settings-open-btn"></a>
  <h5 style="font-size: 20px" class="p-3 m-0 line-height-1 font-weight-bolder bg-light theme-settings-header"> 设置 
  <a href="javascript:void(0)" class="theme-settings-close-btn font-weight-light px-4 py-2 text-dark" tabindex="-1" id="theme-settings-close-btn" style="font-size: 26px;">×</a>
  </h5>
  <div class="theme-settings-inner" style="overflow: auto;">
    <div class="theme-settings-layout">
    <div class="p-3 border-top">
      <button type="button" class="btn btn-sm btn-light btn-block" id="themeSettingsResetBtn">
        恢复默认
      </button>
    </div>
      <hr class="m-0 border-light">
      <h5 class="m-0 px-4 py-3 line-height-1 text-light d-block"> 布局 </h5>
      <label class="m-0 px-4 pb-3 d-flex media align-items-middle theme-settings-layoutPosition">
        <div class="media-body">固定菜单栏</div>
        <div class="switcher switcher-sm d-block m-0">
          <input class="switcher-input" type="checkbox" id="themeSettingsFixedSidenav" checked="checked">
          <span class="switcher-indicator">
            <span class="switcher-yes"></span>
            <span class="switcher-no"></span>
          </span>
        </div>
      </label>
      <label class="m-0 px-4 pb-3 d-flex media align-items-middle theme-settings-layoutNavbarFixed">
        <div class="media-body">固定导航栏</div>
        <div class="switcher switcher-sm d-block m-0">
          <input class="switcher-input" type="checkbox" id="themeSettingsFixedNavbar" checked="checked">
          <span class="switcher-indicator">
            <span class="switcher-yes"></span>
            <span class="switcher-no"></span>
          </span>
        </div>
      </label>
    </div>
    ${menuSettingsConfig.buildThemeBgSection('navbar', '导航栏背景', [
      ['navbar-theme', 'navbar-theme'],
      ['primary', 'primary'],
      ['primary-dark', 'primary-dark navbar-dark'],
      ['primary-darker', 'primary-darker navbar-dark'],
      ['secondary', 'secondary'],
      ['secondary-dark', 'secondary-dark navbar-dark'],
      ['secondary-darker', 'secondary-darker navbar-dark', true],
      ['success', 'success'],
      ['success-dark', 'success-dark navbar-dark'],
      ['success-darker', 'success-darker navbar-dark'],
      ['info', 'info'],
      ['info-dark', 'info-dark navbar-dark'],
      ['info-darker', 'info-darker navbar-dark'],
      ['warning', 'warning'],
      ['warning-dark', 'warning-dark navbar-light'],
      ['warning-darker', 'warning-darker navbar-light'],
      ['danger', 'danger'],
      ['danger-dark', 'danger-dark navbar-dark'],
      ['danger-darker', 'danger-darker navbar-dark'],
      ['dark', 'dark'],
      ['white', 'white'],
      ['light', 'light'],
      ['lighter', 'lighter']
    ])}
    ${menuSettingsConfig.buildThemeBgSection('sidenav', '菜单栏背景', [
      ['sidenav-theme', 'sidenav-theme'],
      ['primary', 'primary'],
      ['primary-dark', 'primary-dark sidenav-dark'],
      ['primary-darker', 'primary-darker sidenav-dark'],
      ['secondary', 'secondary'],
      ['secondary-dark', 'secondary-dark sidenav-dark'],
      ['secondary-darker', 'secondary-darker sidenav-dark', true],
      ['success', 'success'],
      ['success-dark', 'success-dark sidenav-dark'],
      ['success-darker', 'success-darker sidenav-dark'],
      ['info', 'info'],
      ['info-dark', 'info-dark sidenav-dark'],
      ['info-darker', 'info-darker sidenav-dark'],
      ['warning', 'warning'],
      ['warning-dark', 'warning-dark sidenav-light'],
      ['warning-darker', 'warning-darker sidenav-light'],
      ['danger', 'danger'],
      ['danger-dark', 'danger-dark sidenav-dark'],
      ['danger-darker', 'danger-darker sidenav-dark'],
      ['dark', 'dark'],
      ['white', 'white'],
      ['light', 'light'],
      ['lighter', 'lighter']
    ])}
    <div class="theme-settings-status">
      <hr class="m-0 border-light">
      <h5 class="m-0 px-4 py-3 line-height-1 text-light d-block"> 状态主题色 </h5>
      ${menuSettingsConfig.buildMiniColorSection([
          ['themSettingsStatusPrimary', '主要', '#4c84ff'],
          ['themSettingsStatusSecondary', '次要', '#8897AA'],
          ['themSettingsStatusSuccess', '成功', '#02BC77'],
          ['themSettingsStatusWarning', '警告', '#F59A23'],
          ['themSettingsStatusInfo', '信息', '#28c3d7'],
          ['themSettingsStatusDanger', '危险', '#d9534f'],
          ['themSettingsStatusDark', '黑暗', '#2f3237']
      ])}
    </div>
    <div class="theme-settings-table">
      <hr class="m-0 border-light">
      <h5 class="m-0 px-4 py-3 line-height-1 text-light d-block"> 表格设置 </h5>
      ${menuSettingsConfig.buildMiniColorSection([
          ['themSettingsTableTh', '表头颜色', configJson.defaultTableColorJson.tableThBackgroundColor],
          ['tableTDMouseoutEvenBackgroundColor', '偶数移出', configJson.defaultTableColorJson.tableTDMouseoutEvenBackgroundColor],
          ['tableTDMouseoutOddBackgroundColor', '奇数移出', configJson.defaultTableColorJson.tableTDMouseoutOddBackgroundColor],
          ['themSettingsTableTdMouseover', '鼠标移入', configJson.defaultTableColorJson.tableTdMouseoverBackgroundColor]
      ])}
      <label class="m-0 px-4 pb-3 d-flex media align-items-middle theme-settings-layoutPosition">
        <div class="media-body" style="line-height: 25px;">表头对齐</div>
        <div>
          <select id="tableThAlign" class="form-control form-control-sm" style="width: 160px;">
            ${menuSettingsConfig.buildSelectOptions([['center', '居中'], ['left', '居左']], configJson.tableThAlign)}
          </select>
        </div>
      </label>
      <label class="m-0 px-4 pb-3 d-flex media align-items-middle theme-settings-layoutNavbarFixed">
        <div class="media-body">表格竖线分割</div>
        <div class="switcher switcher-sm d-block m-0">
          <input class="switcher-input" type="checkbox" id="tableLrBordered" checked="checked">
          <span class="switcher-indicator">
            <span class="switcher-yes"></span>
            <span class="switcher-no"></span>
          </span>
        </div>
      </label>
    </div>
    <div class="theme-settings-table">
      <hr class="m-0 border-light">
      <h5 class="m-0 px-4 py-3 line-height-1 text-light d-block"> 系统配置 </h5>
      ${menuSettingsConfig.buildMiniColorSection([
          ['systemFullName', '系统全称', configJson.systemFullName],
          ['systemShortName', '系统简称', configJson.systemShortName]
      ])}
      ${menuSettingsConfig.buildMiniColorSection([
            ['themSettingsInputBgColor', '控件背景色', configJson.inputBgColor],
        ])}
      <label class="m-0 px-4 pb-3 d-flex media align-items-middle theme-settings-layoutNavbarFixed">
        <div class="media-body">全局水印</div>
        <div class="switcher switcher-sm d-block m-0">
          <input class="switcher-input" type="checkbox" id="isShowWaterMark" checked="checked">
          <span class="switcher-indicator">
            <span class="switcher-yes"></span>
            <span class="switcher-no"></span>
          </span>
        </div>
      </label>
    </div>
    <br><br><br><br><br><br><br><br><br><br><br><br>
    </div>
  </div>
</div>`;
        return this.menuSettingsConfigJson;
    }

    static getStoredOrDefault(storageKey, defaultValue){
        const value = util.getLocalStorageItem(storageKey);
        if(util.isNull(value) || value == 'undefined'){
            return defaultValue;
        }
        return value;
    }

    static setCheckedByValue(id, value){
        document.getElementById(id).checked = value == 'true';
    }

    static applyCssVarPair(prefix, value){
        const root = document.documentElement;
        const fontColor = util.dynamicColor(value);
        root.style.setProperty(`${prefix}-b-color`, value);
        root.style.setProperty(`${prefix}-f-color`, fontColor);
    }

    static bindMiniColor(selector, prefix, value){
        const isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';
        $(selector).minicolors({
            control: 'hue',
            position: 'bottom ' + (isRtl ? 'right' : 'left'),
            change: function (){
                menuSettingsConfig.applyCssVarPair(prefix, this.value);
            }
        });
        if(!util.isNull(value)){
            menuSettingsConfig.applyCssVarPair(prefix, value);
        }
    }

    static bindThemeRadio(groupName, targetId, storageKey, currentValue){
        const inputs = document.getElementsByName(groupName);
        let selectedValue = currentValue;
        for (let i = 0; i < inputs.length; i++) {
            if (inputs[i].value === selectedValue) {
                inputs[i].closest('label').classList.add('active');
            }
            util.addEventListener(inputs[i], 'click', function (){
                const nextValue = this.value;
                const element = document.getElementById(targetId);
                const removeClasses = ('bg-' + selectedValue).split(' ');
                const classArray = element.getAttribute('class').split(' ').filter(cls => !removeClasses.includes(cls));
                classArray.push(...('bg-' + nextValue).split(' '));
                element.setAttribute('class', classArray.join(' '));
                util.setLocalStorageItem(storageKey, nextValue);
                menuSettingsConfig.menuSettingsConfigJson[storageKey === 'themeSettingsNavbarBg' ? 'navbarTheme' : 'sidenavTheme'] = nextValue;
                selectedValue = nextValue;

                const radios = document.querySelectorAll(`input[type=radio][name=${groupName}]`);
                radios.forEach(input => {
                    const parentLabel = input.closest('label');
                    if(parentLabel){
                        parentLabel.classList.toggle('active', input.value === nextValue);
                    }
                });
            });
        }
    }

    static buildMiniColorSection(items){
        return items.map(([id, label, value]) => `
      <label class="m-0 px-4 pb-3 d-flex media align-items-middle theme-settings-layoutPosition">
        <div class="media-body" style="line-height: 25px;">${label}</div>
        <div><input type="text" id="${id}" style="width: 160px" class="form-control form-control-sm minicolors-input" value="${value}" size="7"></div>
      </label>`).join('');
    }

    static buildThemeBgSection(type, title, items){
        const fieldsetClass = `theme-settings-${type}Bg-inner`;
        const inputName = `theme-settings-${type}Bg-input`;
        const labels = items.map(([bgClass, value, checked]) => `
        <label class="theme-settings-bg-item bg-${bgClass}">
          <input type="radio" name="${inputName}" value="${value}"${checked ? ' checked="checked"' : ''}>
          <span class="theme-settings-bg-name"></span>
        </label>`).join('');

        return `
    <div class="theme-settings-${type}Bg">
      <hr class="m-0 border-light">
      <h5 class="m-0 px-4 py-3 line-height-1 text-light d-block"> ${title} </h5>
      <fieldset class="m-0 px-4 pb-3 d-block clearfix ${fieldsetClass}">${labels}
      </fieldset>
    </div>`;
    }

    static buildSelectOptions(options, selectedValue){
        return options.map(([value, text]) => `<option value="${value}"${value === selectedValue ? ' selected="selected"' : ''}>${text}</option>`).join('');
    }

    static initFunc(){
        const that = this;
        that.initThemeMiniColorFunc();
        const isEditComponent = util.getSessionStorageItem('isEditComponent');
        const pageCode = config.getPageCode();
        const configJson = config.getConfigJson();

        if(!(pageCode == 'page_component') && (isEditComponent == 'S' || configJson.defaultMenuSettings == 'true')){
            document.getElementById('theme-settings-open-btn').addEventListener('click',function (){
                document.getElementById('theme-settings').classList.add('theme-settings-open');
            });
            document.getElementById('theme-settings-close-btn').addEventListener('click',function (){
                document.getElementById('theme-settings').classList.remove('theme-settings-open');
            });

            that.bindThemeRadio('theme-settings-navbarBg-input', 'layout-navbar', 'themeSettingsNavbarBg', that.menuSettingsConfigJson.navbarTheme);
            that.bindThemeRadio('theme-settings-sidenavBg-input', 'showMenuLayout', 'themeSettingsSidenavBg', that.menuSettingsConfigJson.sidenavTheme);

            menuSettingsConfig.setCheckedByValue('themeSettingsFixedSidenav', that.menuSettingsConfigJson.sidenavFixed);
            document.getElementById('themeSettingsFixedSidenav').addEventListener('click',function (){
                util.setLocalStorageItem('themeSettingsFixedSidenav', this.checked == true ? 'true' : 'false');
                document.querySelector('html').classList.toggle('layout-fixed', this.checked == true);
            });

            menuSettingsConfig.setCheckedByValue('themeSettingsFixedNavbar', that.menuSettingsConfigJson.navbarFixed);
            document.getElementById('themeSettingsFixedNavbar').addEventListener('click',function (){
                util.setLocalStorageItem('themeSettingsFixedNavbar', this.checked == true ? 'true' : 'false');
                document.querySelector('html').classList.toggle('layout-navbar-fixed', this.checked == true);
            });

            document.getElementById('themeSettingsResetBtn').addEventListener('click',function (){
                util.setLocalStorageItem('themeSettingsFixedNavbar','');
                util.setLocalStorageItem('themeSettingsFixedSidenav','');
                util.setLocalStorageItem('themeSettingsNavbarBg','');
                util.setLocalStorageItem('themeSettingsSidenavBg','');
                window.location.reload();
            });

            const miniColorBindings = [
                ['#themSettingsStatusPrimary', '--primary', configJson.defaultColorJson['蓝色']],
                ['#themSettingsStatusSecondary', '--secondary', configJson.defaultColorJson['灰色']],
                ['#themSettingsStatusSuccess', '--success', configJson.defaultColorJson['绿色']],
                ['#themSettingsStatusWarning', '--warning', configJson.defaultColorJson['黄色']],
                ['#themSettingsStatusInfo', '--info', configJson.defaultColorJson['浅蓝']],
                ['#themSettingsStatusDanger', '--danger', configJson.defaultColorJson['红色']],
                ['#themSettingsStatusDark', '--dark', configJson.defaultColorJson['黑色']],
                ['#themSettingsTableTh', '--table-th', configJson.defaultTableColorJson.tableThBackgroundColor],
                ['#tableTDMouseoutEvenBackgroundColor', '--table-td-mouseout-even', configJson.defaultTableColorJson.tableTDMouseoutEvenBackgroundColor],
                ['#tableTDMouseoutOddBackgroundColor', '--table-td-mouseout-odd', configJson.defaultTableColorJson.tableTDMouseoutOddBackgroundColor],
                ['#themSettingsTableTdMouseover', '--table-td-mouseover', configJson.defaultTableColorJson.tableTdMouseoverBackgroundColor],
                ['#themSettingsInputBgColor', '--input', configJson.inputBgColor]
            ];
            miniColorBindings.forEach(([selector, prefix, value]) => that.bindMiniColor(selector, prefix, value));

            if(configJson.tableLrBordered == 'true'){
                document.getElementById('tableLrBordered').checked = true;
            }else{
                document.getElementById('tableLrBordered').checked = false;
            }
            document.getElementById('tableLrBordered').addEventListener('click',function (){
                const root = document.documentElement;
                root.style.setProperty('--table-lr-bordered', this.checked == true ? '1px solid #f1f1f2' : 'none');
            });

            document.getElementById('tableThAlign').value = configJson.tableThAlign;
            document.getElementById('tableThAlign').addEventListener('change',function (){
                document.documentElement.style.setProperty('--table-th-align', this.value);
            });

            if(configJson.isShowWaterMark == 'true'){
                document.getElementById('isShowWaterMark').checked = true;
            }else{
                document.getElementById('isShowWaterMark').checked = false;
            }
            document.getElementById('isShowWaterMark').addEventListener('click',function (){
                if (this.checked == true) {
                    if(pageCode != 'page_component'){
                        util.waterMark();
                    }
                }else{
                    util.removeWaterMark();
                }
            });
            document.getElementById('systemFullName').addEventListener('input',function (){
                document.querySelector('title').innerText = this.value;
            });
            document.getElementById('systemShortName').addEventListener('input',function (){
                document.getElementById('systemNameA').innerHTML = this.value;
                document.getElementById('systemNameSpan').innerHTML = this.value;
            });
        }
    }

    static initThemeMiniColorFunc(){
        const configJson = config.getConfigJson();
        const root = document.documentElement;

        const statusColors = [
            ['--primary', configJson.defaultColorJson['蓝色']],
            ['--secondary', configJson.defaultColorJson['灰色']],
            ['--success', configJson.defaultColorJson['绿色']],
            ['--warning', configJson.defaultColorJson['黄色']],
            ['--info', configJson.defaultColorJson['浅蓝']],
            ['--danger', configJson.defaultColorJson['红色']],
            ['--dark', configJson.defaultColorJson['黑色']]
        ];
        statusColors.forEach(([prefix, value]) => {
            const fontColor = util.dynamicColor(value);
            root.style.setProperty(`${prefix}-b-color`, value);
            root.style.setProperty(`${prefix}-f-color`, fontColor);
        });

        const tableColors = [
            ['--table-th', configJson.defaultTableColorJson.tableThBackgroundColor],
            ['--table-td-mouseover', configJson.defaultTableColorJson.tableTdMouseoverBackgroundColor],
            ['--table-td-mouseout-even', configJson.defaultTableColorJson.tableTDMouseoutEvenBackgroundColor],
            ['--table-td-mouseout-odd', configJson.defaultTableColorJson.tableTDMouseoutOddBackgroundColor],
            ['--input', configJson.inputBgColor]
        ];
        tableColors.forEach(([prefix, value]) => {
            const fontColor = util.dynamicColor(value);
            root.style.setProperty(`${prefix}-b-color`, value);
            root.style.setProperty(`${prefix}-f-color`, fontColor);
        });

        root.style.setProperty('--table-lr-bordered', configJson.tableLrBordered == 'true' ? '1px solid #f1f1f2' : 'none');
        root.style.setProperty('--table-th-align', configJson.tableThAlign);
    }

}
export {menuSettingsConfig};