"use strict";
import { util } from '../../../util/util.js'
import {fullMap} from "../../../fullMap.js";
import {config} from "../../../config.js";
import {khcModal} from "../../alert/khcModal.js";
import {form} from "./form.js";
import {pageInfoMap} from "../../../pageInfoMap.js";
import {khcAlert} from "../../alert/khcAlert.js";
class formButtons {
    constructor(data) {

        this.data = data;
        this.parentObjID = data.parentObjID;
        this.eleID = util.getUUID();
        this.type = 'buttons';
        this.objID = this.eleID + 'div';
        this.isValue = false;
        this.bpmButtonNameArray = [];
    }
    getObjID() {
        return this.objID;
    }
    render() {
        let that=this;
        let formObj=fullMap.getObj(that.parentObjID)
        let showLocation='left';//默认靠左
        let formButtonShowLocation=formObj.formStructureData['formInfo']['form_button_show_location']
        if(!util.isNull(formButtonShowLocation)){
            showLocation=formButtonShowLocation
        }
        let formHeaderButtonHtml = `<div class="demo-inline-spacing mt-1" style="margin-left:20px;text-align: ${showLocation}" id="${that.objID}_header_button">`;
        let buttons = that.data.buttons;
        let buttonStyle='';
        if(formObj.formShowType=='page'){
            buttonStyle+='display: none';
        }
        let buttonShowDistance=that.getFormButtonShowDistance()
        for (let i = 0; i < buttons.length; i++) {
            let button = buttons[i];
            let buttonCss='';
            let colorClassName=config.getConfigJson().defaultColorClassJson[button.button_class];
            if(colorClassName){
                colorClassName=colorClassName['bfColor']
            }else{
                let backgroundColor=util.getColorByName(button.button_class);
                let color=util.dynamicColor(backgroundColor);
                buttonCss+=`background:${backgroundColor};color:${color}`;
            }
            formHeaderButtonHtml += `<button type="button" name="${button.button_name}" 
                    style="margin: 0.375rem 0.375rem 0.375rem ${i!=0?buttonShowDistance:''} !important;${buttonCss}${buttonStyle}" 
                    class="btn btn- ladda-button ${colorClassName}" data-style="slide-down">${button.button_title}</button>`;
        }
        let isEditComponent=util.getSessionStorageItem('isEditComponent');
        if(isEditComponent=='S'||isEditComponent=='P'){
            let html=that.getFormHtml('header');
            formHeaderButtonHtml+=html;
        }
        formHeaderButtonHtml += '</div>';
        let parentButtonObj=document.getElementById(that.data.parentObjID);
        if(parentButtonObj==null){
            return ;
        }
        document.getElementById(that.data.parentObjID).insertAdjacentHTML("beforeEnd", formHeaderButtonHtml);
        for (let i = 0; i < buttons.length; i++) {
            let button = buttons[i];
            if (!util.isNull(button.button_method)) {
                if(!util.isNull(button.row_button_show_func)){
                    let content=formObj.getFormValue()
                    let myselfFuncStr=util.toOldChar(button.row_button_show_func);
                    content.util=util;
                    if (!util.executeDynamicCode(myselfFuncStr,content)){//自定义校验不通过，不渲染按钮
                        continue;
                    }
                }
                let buttonEle = document.getElementById(that.objID+'_header_button').querySelector('button[name="' + button.button_name + '"]');
                Ladda.bind( buttonEle, { timeout: 1500 } );//按钮loading动画效果
                buttonEle.addEventListener(button.button_event,  () =>{
                    let jsonConfig={objID:that.parentObjID,button_method:button.button_method}
                    let buttonParams={buttonUuid:button.uuid}
                    jsonConfig.buttonParams=buttonParams;
                    if(!util.isNull(button.js_path)){//配置扩展js优先执行(优先级1)
                        util.import2023(button.js_path,jsonConfig);
                    }else if (!util.isNull(button['button_click_json_config'])) {//配置 button_click_json_config 则执行(优先级2)
                        jsonConfig['button_method']='formButtonClickFunc'
                        jsonConfig['button_click_json_config']=JSON.parse(button['button_click_json_config'])
                        util.import2023(config.getConfigJson().formActionPath,jsonConfig);
                    }else{//没有配置扩展js，也没配置自定义js(优先级3)
                        util.import2023(config.getConfigJson().formActionPath,jsonConfig);
                    }
                })
            }
        }
        if(isEditComponent=='S'||isEditComponent=='P'){
            that.formAddEventListener('header');
        }
    }
    renderFooterButton() {//渲染表单底部按钮
        let that=this;
        let formObj=fullMap.getObj(that.parentObjID)
        let showLocation='left';//默认靠左
        let formButtonShowLocation=formObj.formStructureData['formInfo']['form_button_show_location']
        if(!util.isNull(formButtonShowLocation)){
            showLocation=formButtonShowLocation
        }
        let formFooterButtonHtml = `
                    <div style="padding: 0.1rem;" class="card-body">
                    <div class="demo-inline-spacing mt-1" style="margin-left:20px;text-align: ${showLocation}"  id="${that.objID}_footer_button">
                    `;
        let buttons = that.data.buttons;
        let buttonStyle='';
        if(formObj.formShowType=='page'){
            buttonStyle+='display: none';
        }
        let buttonShowDistance=that.getFormButtonShowDistance()
        for (let i = 0; i < buttons.length; i++) {
            let button = buttons[i];
            let backgroundColor=util.getColorByName(button.button_class);
            let color=util.dynamicColor(backgroundColor);
            formFooterButtonHtml += `<button type="button" name="${button.button_name}" 
        style="margin: 0.375rem 0.375rem 0.375rem ${i!=0?buttonShowDistance:''} !important;background:${backgroundColor};color:${color};${buttonStyle}" 
        class="btn btn-">${button.button_title}</button>`;
        }
        let isEditComponent=util.getSessionStorageItem('isEditComponent');
        if(isEditComponent=='S'||isEditComponent=='P'){
            let html=that.getFormHtml('footer');
            formFooterButtonHtml+=html;
        }
        formFooterButtonHtml += '</div></div>';
        let parentButtonObj=document.getElementById(that.data.parentObjID);
        if(parentButtonObj==null){
            return ;
        }
        document.getElementById(formObj.parentObjID+'_footer').insertAdjacentHTML("beforeEnd", formFooterButtonHtml);
        document.getElementById(formObj.parentObjID+'_footer').style.display='';
        for (let i = 0; i < buttons.length; i++) {
            let button = buttons[i];
            if (!util.isNull(button.button_method)) {
                if(!util.isNull(button.row_button_show_func)){
                    let content=formObj.getFormValue()
                    let myselfFuncStr=util.toOldChar(button.row_button_show_func);
                    content.util=util;
                    if (!util.executeDynamicCode(myselfFuncStr,content)){//自定义校验不通过，不渲染按钮
                        continue;
                    }
                }
                let buttonEle = document.getElementById(that.objID+'_footer_button').querySelector('button[name="' + button.button_name + '"]');
                buttonEle.addEventListener(button.button_event,  () =>{
                    let jsonConfig={objID:that.parentObjID,button_method:button.button_method}
                    let buttonParams={buttonUuid:button.uuid}
                    jsonConfig.buttonParams=buttonParams;
                    if(!util.isNull(button.js_path)){//配置扩展js优先执行(优先级1)
                        util.import2023(button.js_path,jsonConfig);
                    }else if (!util.isNull(button['button_click_json_config'])) {//配置 button_click_json_config 则执行(优先级2)
                        jsonConfig['button_method']='formButtonClickFunc'
                        jsonConfig['button_click_json_config']=JSON.parse(button['button_click_json_config'])
                        util.import2023(config.getConfigJson().formActionPath,jsonConfig);
                    }else{//没有配置扩展js，也没配置自定义js(优先级3)
                        util.import2023(config.getConfigJson().formActionPath,jsonConfig);
                    }
                })
            }
        }
        if(isEditComponent=='S'||isEditComponent=='P'){
            that.formAddEventListener('footer');
        }
    }
    addBpmButton(buttonName, buttonClass, buttonTitle,buttonEvent,buttonMethod,buttonInfo) {
        let that=this;
        let buttonEle = document.getElementById(that.objID+'_header_button').querySelector('button[name="' + buttonName + '"]');
        if(buttonEle!=null){
            buttonEle.style.display='';
            return ;
        }
        //将工作流按钮名存起来，在新增表单时隐藏按钮用到。
        that.bpmButtonNameArray.push(buttonName);
        let backgroundColor=util.getColorByName(buttonClass);
        let color=util.dynamicColor(backgroundColor);
        let html = `<button type="button" name="${buttonName}" id="${buttonName}"  
        style="margin: 0.375rem 0.375rem 0.375rem 0 !important;background:${backgroundColor};color:${color}" class="btn btn-">${buttonTitle}</button>`
        document.getElementById(that.objID+'_header_button').insertAdjacentHTML("beforeEnd", html);
        buttonEle = document.getElementById(that.objID+'_header_button').querySelector('button[name="' + buttonName + '"]');
        buttonEle.addEventListener(buttonEvent,  () =>{
            let jsonConfig={objID:that.parentObjID,button_method:buttonMethod,buttonInfo:buttonInfo}
            util.import2023(config.getConfigJson().formActionPath, jsonConfig);
        })
    }
    getValue() {
        //空方法
    }
    setValue(value) {
        //空方法
    }
    validateText(){
        //空方法
    }
    init(){

    }
    //获取按钮间隔的距离
    getFormButtonShowDistance(){
        let that=this;
        let formObj=fullMap.getObj(that.parentObjID)
        let maxShowDistance=2;//最大距离2rem
        let buttonShowDistance=formObj.formStructureData['formInfo']['form_button_show_distance']
        let defaultShowDistance=0.25;//默认间隔0
        if(util.isNull(buttonShowDistance))return (maxShowDistance*defaultShowDistance)+'rem'
        if(buttonShowDistance==100)return maxShowDistance+'rem';
        if(buttonShowDistance==75)return (maxShowDistance*0.75)+'rem';
        if(buttonShowDistance==50)return (maxShowDistance*0.5)+'rem'
        if(buttonShowDistance==25)return (maxShowDistance*0.25)+'rem';
    }

    //获取表单组件管理配置Html
    getFormHtml(type){
        let that=this;
        let html=``
        let formComponent=fullMap.getObj(that.data.parentObjID)
        let formInfo=formComponent.formStructureData['formInfo'];
        if(formInfo['form_code']=='form'){
            return '';
        }
        let objID=formComponent.getObjID();
        let buttonShowDistance=that.getFormButtonShowDistance()
        html+=`<button type="button" class="btn md-btn-flat dropdown-toggle" data-toggle="dropdown" style="margin: 0.375rem 0.375rem 0.375rem ${buttonShowDistance} !important;">
                     表单组件维护
                   </button>
                   <div class="dropdown-menu dropdown-menu-right">
                     <a class="dropdown-item" href="javascript:void(0)" id="${objID+type}_form_edit${formInfo.id}">编辑</a>
                     <a class="dropdown-item" href="javascript:void(0)" id="${objID+type}_form_to_field${formInfo.id}">字段维护</a>
                     <a class="dropdown-item" href="javascript:void(0)" id="${objID+type}_form_to_button${formInfo.id}">按钮维护</a>
                   </div>`;
        return html;
    }

    //给form的配置绑定事件 todo 这块代码以后迁移出单独文件
    formAddEventListener(type){
        let that=this;
        let formComponent=fullMap.getObj(that.data.parentObjID)
        let content=formComponent.formStructureData['formInfo'];
        if(content['form_code']=='form'){
            return '';
        }
        document.getElementById(formComponent.getObjID()+type+'_form_edit'+content.id).addEventListener('click',  ()=>{
            let params = {};
            params.dsCode='ds_form';
            params.formCode='form';
            params.queryCode='query_form';
            let khcModalForForm = new khcModal({ modalAreaID: config.getConfigJson().modalAreaID });
            khcModalForForm.render().then(() => {
                let formComponent = new form({ parentObjID: khcModalForForm.getEleID(), code: params });
                khcModalForForm.formObjID=formComponent.getObjID()
                let khcModalForFormKey='khcModalForForm#'+formComponent.getObjID();
                pageInfoMap.push(khcModalForFormKey,khcModalForForm);
                formComponent.setFormShowType('modals')
                formComponent.render().then(() => {
                    formComponent.renderThenFunc=(content)=>{
                        formComponent.renderValue(content).then(()=>{
                            let eleMap = formComponent.getFormMap();
                            let read=pageInfoMap.getObj('readOnly#'+params.formCode)
                            if(read!=undefined){
                                for (let i = 0; i < read.length; i++) {
                                    eleMap.get(read[i]).setDisabled();
                                }
                            }
                            let canNull=pageInfoMap.getObj('canNull#'+params.formCode)
                            formComponent.setSaveAfter( ()=> {
                                khcModalForForm.hide();
                                setTimeout(function (){
                                    let alertData = {};
                                    alertData.title = '是否重新加载';
                                    alertData.text = '变更配置需要重新加载页面生效';
                                    alertData.preConfirm = () => {
                                        window.location.reload()
                                    }
                                    khcAlert.showConfirm(alertData, () => {})
                                },1500)
                            })
                            if(canNull!=undefined){
                                for (let i = 0; i < canNull.length; i++) {
                                    eleMap.get(canNull[i]).data.can_null='Y';
                                    eleMap.get(canNull[i]).refreshCanNull();
                                }
                            }
                            formComponent.formEdit();//一些高级属性在新增时大部分是不需要设置所以隐藏，在编辑时再展示
                            khcModalForForm.show();
                        })
                    };
                    formComponent.renderThenFunc(content);
                });
            })
        })
        document.getElementById(formComponent.getObjID()+type+'_form_to_field'+content.id).addEventListener('click',  ()=>{
            let queryInfo={"page_parent_uuid":content.uuid};
            let pageCode='page_ds_form_info';
            let url=config.getIndexUrl()+'?pageCode='+pageCode+'&queryInfo='+JSON.stringify(queryInfo)
            window.open(url);
        })
        document.getElementById(formComponent.getObjID()+type+'_form_to_button'+content.id).addEventListener('click',  ()=>{
            let queryInfo={"page_parent_uuid":content.uuid};
            let pageCode='page_ds_button';
            let url=config.getIndexUrl()+'?pageCode='+pageCode+'&queryInfo='+JSON.stringify(queryInfo)+'&type=form'
            window.open(url);
        })
    }

}

export { formButtons }



