package nckd.jxccl.opmc.pm.plugin.form;

import kd.bos.dataentity.resource.ResManager;
import kd.bos.form.CloseCallBack;
import kd.bos.form.ConfirmCallBackListener;
import kd.bos.form.MessageBoxOptions;
import kd.bos.form.ShowType;
import kd.bos.form.container.Tab;
import kd.bos.form.container.Wizard;
import kd.bos.form.control.Control;
import kd.bos.form.control.Steps;
import kd.bos.form.control.events.TabSelectEvent;
import kd.bos.form.control.events.TabSelectListener;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.ListShowParameter;
import nckd.jxccl.opmc.pm.business.PerfManagerService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.EventObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* 人员考评向导
* @author W.Y.C
* @date 2025/6/13 11:26
* @version 1.0
*/
public class PerfManagerWizardFormPlugin extends AbstractFormPlugin implements TabSelectListener{

    private static final String WIZARD_AP_KEY = "nckd_wizard";
    private static final String TAB_KEY = "nckd_wizard_tabap";

    private static final String[] STEP_TAB_FORM_ID = new String[]{"nckd_tabpageap1","nckd_tabpageap2","nckd_tabpageap3","nckd_tabpageap4"};

    private static final String BTN_NEXT_KEY = "nckd_btnnext";
    private static final String BTN_PREV_KEY = "nckd_btnprev";

    public PerfManagerWizardFormPlugin() {
    }


/*    @Override
    public void initialize() {
        //监听上一步、下一步按钮
        this.addClickListeners(BTN_NEXT_KEY, BTN_PREV_KEY);
    }*/





    @Override
    public void afterBindData(EventObject e) {
        int currentStep = this.getCurrentStep();
        //第一个步骤不显示“上一步”
        if(currentStep == 0){
            this.getView().setVisible(Boolean.FALSE, BTN_PREV_KEY);

            ListShowParameter showParameter = new ListShowParameter();
            showParameter.setBillFormId("nckd_perfmanager");
            showParameter.getOpenStyle().setShowType(ShowType.InContainer);
            showParameter.getOpenStyle().setTargetKey("nckd_tabpageap1");
            showParameter.setCloseCallBack(new CloseCallBack(this, "listCallback")); // 设置回调标识
            /*ListFilterParameter listFilterParameter = new ListFilterParameter();
            QFilter qFilter = new QFilter("field_name", QCP.equals, "filter_value");
            listFilterParameter.setFilter(qFilter);
            showParameter.setListFilterParameter(listFilterParameter);*/
            this.getView().showForm(showParameter);
        }

    }

    // 父页面插件中
    @Override
    public void closedCallBack(ClosedCallBackEvent e) {
        if ("listCallback".equals(e.getActionId())) {
            List<Object> selectedData = (List<Object>)e.getReturnData();
            // 使用selectedData处理业务逻辑
        }
    }

    @Override
    public void click(EventObject evt) {
        //点击上一步、下一步
        switch (((Control)evt.getSource()).getKey()) {
            case BTN_NEXT_KEY:
                this.next();
                break;
            case BTN_PREV_KEY:
                this.previous();
            default:
                // 处理未预期的按钮点击事件
                this.getView().showTipNotification(ResManager.loadKDString(
                        "不支持的操作", "WizardPlugin_unsupported_action", "bos-designer-plugin", new Object[0]));
                break;
        }

    }

    /**
     * 下一步
     * @return: void
     * @author W.Y.C
     * @date: 2025/06/14 20:18
     */
    private void next() {
        int currentStep = this.getCurrentStep();
        if(beforeNext(currentStep)){
            Tab tab = (Tab)this.getView().getControl(TAB_KEY);
            tab.activeTab(STEP_TAB_FORM_ID[currentStep+1]);
        }
        afterNext(currentStep);
       /* for(int i = 0; i < tab.getItems().size(); ++i) {
            if (currentTab.equals(((Control)tab.getItems().get(tab.getItems().size() - 1)).getKey())) {
                this.getView().showConfirm(ResManager.loadKDString("向导已完成，是否退出本页?", "WizardPlugin_0", "bos-designer-plugin", new Object[0]), MessageBoxOptions.YesNo, new ConfirmCallBackListener("exitGuideCallBack"));
                break;
            }
            Control control = (Control)tab.getItems().get(i);
            if (control.getKey().equals(currentTab)) {
                tab.activeTab(((Control)tab.getItems().get(i + 1)).getKey());
                break;
            }
        }*/
    }

    /**
     * 上一步
     * @return: void
     * @author W.Y.C
     * @date: 2025/06/14 20:18
     */
    private void previous() {
        Tab tab = (Tab)this.getView().getControl(TAB_KEY);
        String currentTab = tab.getCurrentTab();

        for(int i = 0; i < tab.getItems().size(); ++i) {
            if (currentTab.equals(((Control)tab.getItems().get(0)).getKey())) {
                this.getView().showTipNotification(ResManager.loadKDString("当前页面为第一页。", "WizardPlugin_1", "bos-designer-plugin", new Object[0]));// 73
                return;
            }

            Control control = (Control)tab.getItems().get(i);
            if (control.getKey().equals(currentTab)) {
                tab.activeTab(((Control)tab.getItems().get(i - 1)).getKey());
                break;
            }
        }
    }

    /**
     * 点击下一步之前触发（可用于数据校验）
     * @param currentStep 当前步骤
     * @return: Boolean
     * @author W.Y.C
     * @date: 2025/06/14 20:23
     */
    private Boolean beforeNext(int currentStep){
        if(currentStep == 0){

        }else if(currentStep == 1){

        }else if(currentStep == 2){

        }else if(currentStep == 3){

        }else if(currentStep == 4){
            this.getView().showConfirm(ResManager.loadKDString("向导已完成，是否退出本页?", "WizardPlugin_0", "bos-designer-plugin", new Object[0]), MessageBoxOptions.YesNo, new ConfirmCallBackListener("exitGuideCallBack"));
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    private boolean afterNext(int currentStep){
        if(currentStep == 0) {
            //录入考评页面选择的数据
            String rowKeys = this.getView().getPageCache().get("rowKeys");
            if(StringUtils.isNotBlank(rowKeys) && rowKeys.contains(",")){
                List<Long> rowKeyList = Arrays.stream(rowKeys.split(","))
                        .map(String::trim) // 去除每个元素周围的空格
                        .map(Long::valueOf) // 转换为 Long 类型
                        .collect(Collectors.toList());
                kd.bos.form.control.ProgressBar bar = (kd.bos.form.control.ProgressBar)this.getControl("nckd_progressbarap");
                bar.start();
                PerfManagerService.generateEvaluationResult(rowKeyList);
            }
            System.out.println();
        }
        return Boolean.TRUE;
    }





    @Override
    public void registerListener(EventObject e) {
        Tab tab = (Tab)this.getControl(TAB_KEY);
        tab.addTabSelectListener(this);

        //监听上一步、下一步按钮
        this.addClickListeners(BTN_NEXT_KEY, BTN_PREV_KEY);
    }

    @Override
    public void tabSelected(TabSelectEvent tabSelectEvent) {

        Tab tab = (Tab)this.getView().getControl(TAB_KEY);
        String currentTab = tab.getCurrentTab();
        int currentStep = getCurrentStep();
        setStepStatus(currentStep, Steps.PROCESS);
        if(currentStep != 0){
            //除了第一个步骤都显示“上一步”
            this.getView().setVisible(Boolean.TRUE, BTN_PREV_KEY);
        }else{
            //第一个步骤不显示“上一步”
            this.getView().setVisible(Boolean.FALSE, BTN_PREV_KEY);
        }
        //最后一个步骤按钮显示“完成”，否则显示下一步
        if(currentStep == 4){
            Map<String, Object> textMap = new HashMap<>();
            Map<String, Object> textValue = new HashMap<>();
            textValue.put("zh_CN", "完成");
            textMap.put("text", textValue);
            this.getView().updateControlMetadata(BTN_NEXT_KEY, textMap);
        }else{
            Map<String, Object> textMap = new HashMap<>();
            Map<String, Object> textValue = new HashMap<>();
            textValue.put("zh_CN", "下一步");
            textMap.put("text", textValue);
            this.getView().updateControlMetadata(BTN_NEXT_KEY, textMap);
        }
    }


    /**
     * 设置步骤状态
     * @param step 步骤索引（从0开始）
     * @param stepStatus 步骤状态 {@link Steps}
     * @return: void
     * @author W.Y.C
     * @date: 2025/06/14 20:12
     */
    private void setStepStatus(int step,String stepStatus) {
        Wizard wizard = this.getControl(WIZARD_AP_KEY);
        Map<String, Object> currentStepMap = new HashMap<>();
        currentStepMap.put("currentStep", step);
        currentStepMap.put("currentStatus", stepStatus);
        wizard.setWizardCurrentStep(currentStepMap);
    }


    /**
     * 获取当前步骤索引（从0开始）
     * @return: int
     * @author W.Y.C
     * @date: 2025/06/14 20:15
     */
    private int getCurrentStep() {
        Tab tab = (Tab)this.getControl(TAB_KEY);
        String currentTab = tab.getCurrentTab();
        return ArrayUtils.indexOf(STEP_TAB_FORM_ID, currentTab);
    }
}