"use strict";

import { util } from '../../../../util/util.js'
import {fullMap} from "../../../../fullMap.js";
import {config} from "../../../../config.js";
import {pageInfoMap} from "../../../../pageInfoMap.js";
class rowButtons {
    constructor(data) {

        this.data = data;
        this.renderListType = data.renderListType;
        this.parentObjID = data.parentObjID;
        this.eleID = util.getUUID();
        this.objID = this.eleID + 'div';
        this.tableID = '';
    }
    getObjID() {
        return this.objID;
    }
    render(tableId) {
        let that=this;
        return new Promise((resolve, reject) => {
            that.tableID = tableId;
            that.renderHtml().then(() => {
                that.addEventListener();
                if(that.tableView.queryInfo.is_show_select_table=='Y'){
                    that.renderSelectHtml().then(() => {
                        that.addSelectEventListener();
                    })
                }
                resolve();
            })
        })
    }
    renderHtml() {
        let that=this;
        return new Promise((resolve, reject) => {
            let tableId = that.tableID
            let html = '';
            that.isSelectShow=false;
            let tableView=fullMap.getObj(that.data.queryComponentObjID).tableView
            that.tableView=tableView;
            if(that.renderListType=='render_card'){
                resolve();
                return ;
            }
            let rowButtonArray = that.data.rowButtonArray;
            if (rowButtonArray.length > 0) {
                let trArray = document.getElementById(tableId).querySelector('tbody').querySelectorAll('tr');
                for (let tr of trArray) {
                    let pkCode = tr.getAttribute('pkcode');
                    if(pkCode!=null){
                        let dataMap=tableView.dataMap;
                        let trData=dataMap.get(pkCode)
                        trData=util.clone(trData)
                        html=``;
                        for (let i = 0; i < rowButtonArray.length; i++) {
                            let button = rowButtonArray[i];
                            if(button['table_button_render_type']!='defaultTableRender'){
                                continue;
                            }
                            if(!util.isNull(button.row_button_show_func)){
                                let myselfFuncStr=util.toOldChar(button.row_button_show_func);
                                if(pageInfoMap.getObj(that.tableView.code['queryCode'])==undefined||
                                    pageInfoMap.getObj(that.tableView.code['queryCode']).page_parent_uuid==undefined){
                                }else{
                                    let pageObj=fullMap.getObj(fullMap.getObj(that.tableView.queryObjID).pageID)
                                    trData.parentContent=pageObj['parentContent'];
                                }
                                trData.util=util;
                                if (!util.executeDynamicCode(myselfFuncStr,trData)){//自定义校验不通过，不渲染按钮
                                    continue;
                                }
                            }
                            let buttonCss='';
                            if(button.button_show_query_type!=undefined&&button.button_show_query_type=='2'){
                                buttonCss='display: none;'
                            }
                            if(button.is_select_show=='Y'){
                                that.isSelectShow=true;
                            }else {
                                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}`;
                                }
                                html += `
                        <button type="button" name="${button.button_name}"  class="btn btn-xs btn- mr-2 ${colorClassName}" style="${buttonCss}" title="${button.button_title}">
                        ${button.button_icon!=''?`<span class="${button.button_icon} d-xl-none"></span>`:''}
                        <span class="d-none d-xl-inline">${button.button_title}</span>
                        </button>`;
                            }
                        }
                        let buttonHtmlTemplate=``;
                        for (let i = 0; i < rowButtonArray.length; i++) {//渲染在更多操作的按钮
                            let button = rowButtonArray[i];
                            if(!util.isNull(button.row_button_show_func)){
                                let myselfFuncStr=util.toOldChar(button.row_button_show_func);
                                if(pageInfoMap.getObj(that.tableView.code['queryCode'])==undefined||
                                    pageInfoMap.getObj(that.tableView.code['queryCode']).page_parent_uuid==undefined){
                                }else{
                                    let pageObj=fullMap.getObj(fullMap.getObj(that.tableView.queryObjID).pageID)
                                    trData.parentContent=pageObj['parentContent'];
                                }
                                trData.util=util;
                                if (!util.executeDynamicCode(myselfFuncStr,trData)){//自定义校验不通过，不渲染按钮
                                    continue;
                                }
                            }
                            let buttonCss='';
                            if(button.button_show_query_type!=undefined&&button.button_show_query_type=='2'){
                                buttonCss='display: none;'
                            }
                            buttonHtmlTemplate+=`${button.is_select_show=='Y'?`<a class="dropdown-item" name="${button.button_name}" style="${buttonCss} cursor:pointer;">${button.button_title}</a>`:''}`;
                        }
                        let td=document.getElementById(pkCode + tableId);
                        let zIndex=td.getAttribute('zIndex')
                        if(that.isSelectShow&&buttonHtmlTemplate!=''){
                            html+=`<button class="btn btn-secondary btn-xs dropdown-toggle" type="button" 
                                    id="${that.objID}_dropdown_button${zIndex}" data-toggle="dropdown" aria-expanded="false">
                            ${that.tableView.queryInfo['row_select_button_label']?that.tableView.queryInfo['row_select_button_label']:config.getConfigJson().rowSelectButtonLabel}</button>
                            <div class="dropdown-menu" style="">${buttonHtmlTemplate}</div>`;
                            td.insertAdjacentHTML("beforeEnd", html);
                            //由于管理列用到sticky粘性定位来做冻结列用到z-index 导致按钮"更多操作"下拉按钮较多时会被挡住，所以调整如下当点击时给当前td*10
                            if(that.isSelectShow){
                                document.getElementById(that.objID+'_dropdown_button'+zIndex).addEventListener('click',function (){
                                    for (let tr of trArray) {
                                        let code = tr.getAttribute('pkcode');
                                        if(code!=null){
                                            let trTd=document.getElementById(code + tableId);
                                            trTd.style.zIndex=trTd.getAttribute('zIndex');
                                        }
                                    }
                                    td.style.zIndex=td.getAttribute('zIndex')*10;
                                })
                            }
                        }else{
                            td.insertAdjacentHTML("beforeEnd", html);
                        }
                    }
                }
            }
            let showTableDivEle=document.getElementById(tableId+'_show_table_div')
            let minHeight=that.tableView.queryInfo['table_min_height'];
            if(util.isNull(minHeight)){
                minHeight=400;
            }
            if(that.isSelectShow){//是否下拉显示按钮
                showTableDivEle.style.minHeight='500px';
            }else{
                showTableDivEle.style.minHeight=minHeight+'px';
            }
            showTableDivEle.style.maxHeight='80vh';
            resolve();
        })




    }
    //渲染select列表按钮
    renderSelectHtml() {
        let that=this;
        return new Promise((resolve, reject) => {
            if(that.tableView.pageComponent.isReadOnly=='Y'){
                resolve();
                return ;
            }
            let tableId = that.tableID
            let html = '';
            that.isSelectShow=false;
            let tableView=fullMap.getObj(that.data.queryComponentObjID).tableView
            that.tableView=tableView;
            let selectTrArray = [];
            if(that.tableView.queryInfo.is_show_select_table=='Y'){
                selectTrArray = document.getElementById(tableId+'_select').querySelector('tbody').querySelectorAll('tr');
            }
            let rowButtonArray = that.data.rowButtonArray;
            let buttonBackgroundColor=config.getConfigJson().themeColor;
            for (let tr of selectTrArray) {
                let pkCode = tr.getAttribute('pkcode');
                if(pkCode!=null){
                    let dataMap=tableView.selectDataMap;
                    let trData=dataMap.get(pkCode)
                    trData=util.clone(trData)
                    html=``;
                    for (let i = 0; i < rowButtonArray.length; i++) {
                        let button = rowButtonArray[i];
                        if(button['table_button_render_type']!='selectTableRender'){
                            continue;
                        }
                        let isRenderButton=true;
                        if(!util.isNull(button.row_button_show_func)){
                            let myselfFuncStr=util.toOldChar(button.row_button_show_func);
                            if(pageInfoMap.getObj(that.tableView.code['queryCode'])==undefined||
                                pageInfoMap.getObj(that.tableView.code['queryCode']).page_parent_uuid==undefined){
                            }else{
                                let pageObj=fullMap.getObj(fullMap.getObj(that.tableView.queryObjID).pageID)
                                trData.parentContent=pageObj['parentContent'];
                            }
                            trData.util=util;
                            if (!util.executeDynamicCode(myselfFuncStr,trData)){//自定义校验不通过，不渲染按钮
                                isRenderButton=false;
                            }
                        }
                        let buttonCss='';
                        if(button.button_show_query_type!=undefined&&button.button_show_query_type=='2'){
                            buttonCss='display: none;'
                        }
                        if(button.is_select_show=='Y'){
                            that.isSelectShow=true;
                        }else {
                            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}`;
                            }

                            html += `
                    <button type="button" name="${button.button_name}"  class="btn btn-xs btn- mr-2 ${colorClassName}" style="${buttonCss}">
                    ${button.button_icon!=''?`<span class="${button.button_icon}"></span>&nbsp;`:''}
                    ${button.button_title}
                    </button>`;
                        }
                    }
                    let buttonHtmlTemplate=``;
                    for (let i = 0; i < rowButtonArray.length; i++) {//渲染在更多操作的按钮
                        let button = rowButtonArray[i];
                        let isRenderButton=true;
                        if(!util.isNull(button.row_button_show_func)){
                            let myselfFuncStr=util.toOldChar(button.row_button_show_func);
                            if(pageInfoMap.getObj(that.tableView.code['queryCode'])==undefined||
                                pageInfoMap.getObj(that.tableView.code['queryCode']).page_parent_uuid==undefined){
                            }else{
                                let pageObj=fullMap.getObj(fullMap.getObj(that.tableView.queryObjID).pageID)
                                trData.parentContent=pageObj['parentContent'];
                            }
                            trData.util=util;
                            if (!util.executeDynamicCode(myselfFuncStr,trData)){//自定义校验不通过，不渲染按钮
                                isRenderButton=false;
                            }
                        }
                        let buttonCss='';
                        if(button.button_show_query_type!=undefined&&button.button_show_query_type=='2'){
                            buttonCss='display: none;'
                        }
                        buttonHtmlTemplate+=`${button.is_select_show=='Y'?`<a class="dropdown-item" name="${button.button_name}" style="${isRenderButton?'cursor:pointer;':''}${buttonCss}">${button.button_title}</a>`:''}`;
                    }
                    let td=document.getElementById(pkCode +'_select'+ tableId);
                    let zIndex=td.getAttribute('zIndex')
                    if(that.isSelectShow&&buttonHtmlTemplate!=''){
                        /*html+=`<button class="btn btn-secondary btn-xs dropdown-toggle" type="button"
                                id="${that.objID}_dropdown_button${zIndex}" data-toggle="dropdown" aria-expanded="false">
                        操作</button>
                        <div class="dropdown-menu" style="">${buttonHtmlTemplate}</div>`;*/
                        html+=`<span class="mr-1 ml-1">|</span><a class="item" style="cursor:pointer;color: ${buttonBackgroundColor}"
                                    id="${that.objID}_dropdown_button${zIndex}" data-toggle="dropdown" aria-expanded="false">更多 <i class="dropdown-toggle"></i></a>
                            <div class="dropdown-menu" style="">${buttonHtmlTemplate}</div>`;
                        td.insertAdjacentHTML("beforeEnd", html);
                        //由于管理列用到sticky粘性定位来做冻结列用到z-index 导致按钮"更多操作"下拉按钮较多时会被挡住，所以调整如下当点击时给当前td*10
                        if(that.isSelectShow){
                            document.getElementById(that.objID+'_dropdown_button'+zIndex).addEventListener('click',function (){
                                for (let tr of trArray) {
                                    let code = tr.getAttribute('pkcode');
                                    if(code!=null){
                                        let trTd=document.getElementById(code + tableId);
                                        trTd.style.zIndex=trTd.getAttribute('zIndex');
                                    }
                                }
                                td.style.zIndex=td.getAttribute('zIndex')*10;
                            })
                        }
                    }else{
                        td.insertAdjacentHTML("beforeEnd", html);
                    }
                }
            }
            resolve();
        })
    }

    addEventListener() {
        let that = this;
        let tableObjID = that.tableID;
        let rowButtonArray = that.data.rowButtonArray;
        if(that.renderListType=='render_card'){
            let childArray = document.getElementById(tableObjID).children;
            let dataMap=that.tableView.dataMap;
            for (let child of childArray) {
                let pkCode = child.getAttribute('pkcode');
                if(pkCode!=null){
                    let trData=dataMap.get(pkCode)
                    trData=util.clone(trData)
                    for (let i = 0; i < rowButtonArray.length; i++) {
                        let button = rowButtonArray[i];
                        if(button['table_button_render_type']!='defaultTableRender'){
                            continue;
                        }
                        if(!util.isNull(button.row_button_show_func)){
                            let myselfFuncStr=util.toOldChar(button.row_button_show_func);
                            if(pageInfoMap.getObj(that.tableView.code['queryCode'])==undefined||
                                pageInfoMap.getObj(that.tableView.code['queryCode']).page_parent_uuid==undefined){
                            }else{
                                let pageObj=fullMap.getObj(fullMap.getObj(that.tableView.queryObjID).pageID)
                                trData.parentContent=pageObj['parentContent'];
                            }
                            trData.util=util;
                            if (!util.executeDynamicCode(myselfFuncStr,trData)){//自定义校验不通过，不渲染按钮
                                continue;
                            }
                        }
                        if (!util.isNull(button.button_method)) {
                            // 查找所有符合条件的按钮或链接
                            let buttonEles = document.getElementById(pkCode + tableObjID).querySelectorAll('button[name="' + button.button_name + '"], a[name="' + button.button_name + '"]');

                            // 如果没有找到符合条件的元素，跳过当前循环
                            if(buttonEles.length === 0) {
                                continue;
                            }

                            // 遍历所有找到的按钮或链接
                            buttonEles.forEach(buttonEle => {
                                buttonEle.style.display = '';
                                buttonEle.addEventListener(button.button_event, () => {
                                    let queryViewComponent = fullMap.getObj(that.data.queryComponentObjID);
                                    queryViewComponent.scrollIntoRowView = function () {
                                        util.toTops({ dom: buttonEle, isFocus: true });
                                    }
                                    let jsonConfig = { objID: that.data.queryComponentObjID, button_method: button.button_method, pkCode: pkCode };
                                    if (!util.isNull(button['button_click_json_action'])) {
                                        jsonConfig['button_click_json_action'] = JSON.parse(button['button_click_json_action']);
                                    }
                                    let tableViewComponent = queryViewComponent.getTableObj();
                                    let content = tableViewComponent.getContentMap().get(jsonConfig.pkCode.toString());
                                    let buttonParams = { buttonUuid: button.uuid, buttonContent: content };
                                    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'] = 'rowButtonClickFunc';
                                        jsonConfig['old_button_method'] = button.button_method;
                                        jsonConfig['button_click_json_config'] = JSON.parse(button['button_click_json_config']);
                                        util.import2023(config.getConfigJson().tableActionPath, jsonConfig);
                                    } else { // 没有配置扩展js，也没配置自定义js(优先级3)
                                        util.import2023(config.getConfigJson().tableActionPath, jsonConfig);
                                    }
                                });
                            });
                        }
                    }
                }
            }
            return ;
        }
        //行按钮
        if(that.tableView.pageComponent.isReadOnly=='Y'){
            return ;
        }
        let trArray = document.getElementById(tableObjID).querySelector('tbody').querySelectorAll('tr');
        let dataMap=that.tableView.dataMap;
        for (let tr of trArray) {
            let pkCode = tr.getAttribute('pkcode');
            if(pkCode!=null){
                let trData=dataMap.get(pkCode)
                trData=util.clone(trData)
                for (let i = 0; i < rowButtonArray.length; i++) {
                    let button = rowButtonArray[i];
                    if(button['table_button_render_type']!='defaultTableRender'){
                        continue;
                    }
                    if(!util.isNull(button.row_button_show_func)){
                        let myselfFuncStr=util.toOldChar(button.row_button_show_func);
                        if(pageInfoMap.getObj(that.tableView.code['queryCode'])==undefined||
                            pageInfoMap.getObj(that.tableView.code['queryCode']).page_parent_uuid==undefined){
                        }else{
                            let pageObj=fullMap.getObj(fullMap.getObj(that.tableView.queryObjID).pageID)
                            trData.parentContent=pageObj['parentContent'];
                        }
                        trData.util=util;
                        if (!util.executeDynamicCode(myselfFuncStr,trData)){//自定义校验不通过，不渲染按钮
                            continue;
                        }
                    }
                    if (!util.isNull(button.button_method)) {
                        let buttonEle = document.getElementById(pkCode + tableObjID).querySelector('button[name="' + button.button_name + '"]');
                        if(buttonEle==null){
                            buttonEle=document.getElementById(pkCode + tableObjID).querySelector('a[name="' + button.button_name + '"]');
                        }
                        buttonEle.addEventListener(button.button_event,  () =>{
                            let queryViewComponent = fullMap.getObj(that.data.queryComponentObjID);
                            queryViewComponent.scrollIntoRowView=function (){
                                util.toTops({dom:buttonEle,isFocus:true})
                            }
                            let jsonConfig={objID:that.data.queryComponentObjID,button_method:button.button_method,pkCode:pkCode}
                            if(!util.isNull(button['button_click_json_action'])){
                                jsonConfig['button_click_json_action']=JSON.parse(button['button_click_json_action'])
                            }
                            let tableViewComponent = queryViewComponent.getTableObj();
                            let content = tableViewComponent.getContentMap().get(jsonConfig.pkCode.toString());
                            let buttonParams={buttonUuid:button.uuid,buttonContent:content}
                            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']='rowButtonClickFunc'
                                jsonConfig['old_button_method']=button.button_method
                                jsonConfig['button_click_json_config']=JSON.parse(button['button_click_json_config'])
                                util.import2023(config.getConfigJson().tableActionPath,jsonConfig);
                            }else{//没有配置扩展js，也没配置自定义js(优先级3)
                                util.import2023(config.getConfigJson().tableActionPath,jsonConfig);
                            }
                        })
                    }
                }
            }

        }


    }
    //为Select表添加事件
    addSelectEventListener() {
        let that = this;
        if(that.tableView.pageComponent.isReadOnly=='Y'){
            return ;
        }
        let tableObjID = that.tableID;
        let rowButtonArray = that.data.rowButtonArray;
        //select表的行按钮
        let trArray = document.getElementById(tableObjID+'_select').querySelector('tbody').querySelectorAll('tr');
        let dataMap=that.tableView.selectDataMap;
        for (let tr of trArray) {
            let pkCode = tr.getAttribute('pkcode');
            if(pkCode!=null){
                let trData=dataMap.get(pkCode)
                trData=util.clone(trData)
                for (let i = 0; i < rowButtonArray.length; i++) {
                    let button = rowButtonArray[i];
                    if(button['table_button_render_type']!='selectTableRender'){
                        continue;
                    }
                    if(!util.isNull(button.row_button_show_func)){
                        let myselfFuncStr=util.toOldChar(button.row_button_show_func);
                        if(pageInfoMap.getObj(that.tableView.code['queryCode'])==undefined||
                            pageInfoMap.getObj(that.tableView.code['queryCode']).page_parent_uuid==undefined){
                        }else{
                            let pageObj=fullMap.getObj(fullMap.getObj(that.tableView.queryObjID).pageID)
                            trData.parentContent=pageObj['parentContent'];
                        }
                        trData.util=util;
                        if (!util.executeDynamicCode(myselfFuncStr,trData)){//自定义校验不通过，不渲染按钮
                            continue;
                        }
                    }
                    if (!util.isNull(button.button_method)) {
                        let buttonEle = document.getElementById(pkCode +'_select'+ tableObjID).querySelector('button[name="' + button.button_name + '"]');
                        if(buttonEle==null){
                            buttonEle=document.getElementById(pkCode +'_select'+ tableObjID).querySelector('a[name="' + button.button_name + '"]');
                        }
                        buttonEle.addEventListener(button.button_event,  () =>{
                            let queryViewComponent = fullMap.getObj(that.data.queryComponentObjID);
                            queryViewComponent.scrollIntoRowView=function (){
                                util.toTops({dom:buttonEle,isFocus:true})
                            }
                            let jsonConfig={objID:that.data.queryComponentObjID,button_method:button.button_method,pkCode:pkCode}
                            let tableViewComponent = queryViewComponent.getTableObj();
                            let content = tableViewComponent.getContentMap().get(jsonConfig.pkCode.toString());
                            let buttonParams={buttonUuid:button.uuid,buttonContent:content}
                            jsonConfig.buttonParams=buttonParams;
                            if (util.isNull(button.js_path)) {
                                util.import2023(config.getConfigJson().tableActionPath,jsonConfig);
                            } else {
                                util.import2023(button.js_path,jsonConfig);
                            }
                        })
                    }
                }
            }

        }


    }

}
export { rowButtons }



