package cn.axzo.workflow.form.engine.cmd;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.form.api.FormInfo;
import org.flowable.form.engine.FormEngineConfiguration;
import org.flowable.form.engine.impl.cmd.GetVariablesFromFormSubmissionCmd;
import org.flowable.form.engine.impl.util.CommandContextUtil;
import org.flowable.form.model.FormField;
import org.flowable.form.model.FormFieldTypes;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.Map;

/**
 * 覆盖表单引擎自带的表单提交处理命令
 *
 * @author wangli
 * @since 2025-01-22 15:20
 */
public class CustomGetVariablesFromFormSubmissionCmd extends GetVariablesFromFormSubmissionCmd {

    public CustomGetVariablesFromFormSubmissionCmd(FormInfo formInfo, Map<String, Object> values) {
        super(formInfo, values);
    }

    public CustomGetVariablesFromFormSubmissionCmd(FormInfo formInfo, Map<String, Object> values, String outcome) {
        super(formInfo, values, outcome);
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        return super.execute(commandContext);
    }

    @Override
    protected Object transformFormFieldValueToVariableValue(FormField formField, Object formFieldValue) {
        Object result = formFieldValue;
        if (formField.getType().equals(FormFieldTypes.DATE) && formFieldValue instanceof String) {
            if (StringUtils.isNotEmpty((String) formFieldValue)) {
                try {
//                    result = LocalDate.parse((String) formFieldValue);
                    result = parseToLocalDateTime((String) formFieldValue, fmtConvert(formField.getParam("fmt").toString()));
                } catch (Exception e) {
                    e.printStackTrace();
                    result = null;
                }
            }

        } else if (formField.getType().equals(FormFieldTypes.DATE) && formFieldValue instanceof Date) {
            result = parseToLocalDateTime((String) formFieldValue, fmtConvert(formField.getParam("fmt").toString()));
//            result = new LocalDate(formFieldValue);
        } else if (formField.getType().equals(FormFieldTypes.INTEGER) && formFieldValue instanceof String) {
            String strFieldValue = (String) formFieldValue;
            if (StringUtils.isNotEmpty(strFieldValue) && NumberUtils.isCreatable(strFieldValue)) {
                result = Long.valueOf(strFieldValue);

            } else {
                result = null;
            }

        } else if (formField.getType().equals(FormFieldTypes.DECIMAL) && formFieldValue instanceof String) {
            String strFieldValue = (String) formFieldValue;
            if (StringUtils.isNotEmpty(strFieldValue) && NumberUtils.isCreatable(strFieldValue)) {
                result = Double.valueOf(strFieldValue);

            } else {
                result = null;
            }

        } else if (formField.getType().equals(FormFieldTypes.AMOUNT) && formFieldValue instanceof String) {
            try {
                result = Double.parseDouble((String) formFieldValue);

            } catch (NumberFormatException e) {
                result = null;
            }

        } else if (formField.getType().equals(FormFieldTypes.DROPDOWN) || formField.getType().equals(FormFieldTypes.RADIO_BUTTONS)) {
            if (formFieldValue instanceof Map<?, ?>) {
                result = ((Map<?, ?>) formFieldValue).get("id");
                if (result == null) {
                    // fallback to name for manual config options
                    result = ((Map<?, ?>) formFieldValue).get("name");
                }
            }

        } else if (formField.getType().equals(FormFieldTypes.UPLOAD)) {
            FormEngineConfiguration formEngineConfiguration = CommandContextUtil.getFormEngineConfiguration();
            try {
                result = formEngineConfiguration.getObjectMapper().writeValueAsString(formFieldValue);
            } catch (JsonProcessingException e) {
                result = null;
            }

        } else if (formField.getType().equals(FormFieldTypes.PEOPLE) || formField.getType().equals(FormFieldTypes.FUNCTIONAL_GROUP)) {
            if (formFieldValue instanceof Map<?, ?>) {
                Map<String, Object> value = (Map<String, Object>) formFieldValue;
                result = value.get("id").toString();

            } else {
                // Incorrect or empty map, ignore
                result = null;
            }
        }

        // Default: no processing needs to be done, can be stored as-is
        return result;
    }


    public static LocalDateTime parseToLocalDateTime(String dateStr, String format) {
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format.replace("YYYY", "yyyy").replace("DD", "dd"));
            if (format.contains("HH:mm")) {
                return LocalDateTime.parse(dateStr, formatter);
            } else {
                LocalDate localDate = LocalDate.parse(dateStr, formatter);
                return localDate.atStartOfDay();
            }
        } catch (DateTimeParseException e) {
            System.err.println("解析日期字符串时出错: " + dateStr + " ，使用格式: " + format);
            return null;
        }
    }

    public static String fmtConvert(String fmt) {
        switch (fmt) {
            case "YYYY-MM-DD HH:mm:ss":
                return "yyyy-MM-dd HH:mm:ss";
            case "YYYY-MM-DD HH:mm":
                return "yyyy-MM-dd HH:mm";
            default:
                return "yyyy-MM-dd";
        }
    }
}
