package cn.stylefeng.workflow.instance.core.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.stylefeng.team.form.api.FormModelServiceApi;
import cn.stylefeng.team.form.api.entity.FormItem;
import cn.stylefeng.team.form.api.pojo.FormDesignVo;
import cn.stylefeng.workflow.api.pojo.config.model.FlowGlobalConfig;
import cn.stylefeng.workflow.api.pojo.config.model.ModelForm;

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

public class FormItemUtil {

    public static Map<Long, List<FormItem>> getFlowDefinitionFormItemList(FlowGlobalConfig flowGlobalConfig) {

        List<Long> formDefinitionIdList = flowGlobalConfig.getFormDefinitionList().stream().map(ModelForm::getFormDefinitionId).collect(Collectors.toList());

        FormModelServiceApi formModelServiceApi = SpringUtil.getBean(FormModelServiceApi.class);
        List<FormDesignVo> formDesignVoList = formModelServiceApi.getFromDesignList(formDefinitionIdList);

        Map<Long, List<FormItem>> result = new HashMap<>();
        for (FormDesignVo formDesignVo : formDesignVoList) {
            Long formDefinitionId = formDesignVo.getFormDefinitionId();
            List<FormItem> formItemList = formDesignVo.getFormItemList();
            result.put(formDefinitionId, formItemList);
        }

        return result;
    }

    public static FormItem getFormItemByFieldCode(Map<Long, List<FormItem>> formItemMap, Long formDefinitionId, String fieldCode) {
        if (ObjectUtil.isEmpty(formItemMap)) {
            return null;
        }

        List<FormItem> formItemList = formItemMap.get(formDefinitionId);

        for (FormItem item : formItemList) {
            if (item != null && item.getFieldCode() != null) {
                if (item.getFieldCode().equals(fieldCode)) {
                    return item;
                }
            }
        }

        return null;
    }

}
