package org.jeecg.modules.flowable.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.flowable.task.api.Task;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.flowable.apithird.business.entity.FlowForm;
import org.jeecg.modules.flowable.apithird.business.service.IFlowFormService;
import org.jeecg.modules.flowable.apithird.business.service.ISysDeployFormService;
import org.jeecg.modules.flowable.apithird.business.service.impl.FlowMyBusinessServiceImpl;
import org.jeecg.modules.flowable.apithird.service.IFlowThirdService;

import org.jeecg.modules.flowable.factory.FlowServiceFactory;
import org.jeecg.modules.flowable.service.IFlowTaskFormService;

import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.flowable.task.api.history.HistoricTaskInstance;
import java.util.*;

/**
 **/
@Service
@Slf4j
@Transactional
public class FlowTaskFormServiceImpl extends FlowServiceFactory implements IFlowTaskFormService {
    @Autowired
    private IFlowThirdService iFlowThirdService;
    @Autowired
    FlowMyBusinessServiceImpl flowMyBusinessService;
    @Autowired
    private ISysDeployFormService sysInstanceFormService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IFlowFormService flowFormService;

    /**
     * 获取流程任务表单数据
     * @return 表单数据和流程变量
     */
    @Override
    public Result findFlowFormVal(String taskId) throws Exception {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        // 流程变量
        Map<String, Object> parameters = new HashMap<>();
        HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery().includeProcessVariables().finished().taskId(taskId).singleResult();
        if (Objects.nonNull(historicTaskInstance)) {
            parameters = historicTaskInstance.getProcessVariables();
        } else {
            parameters = taskService.getVariables(taskId);
        }
        return Result.OK(parameters);
    }


    @Override
    public Result flowTaskForm(String taskId) {
        try {
            // 参数校验
            if (StringUtils.isBlank(taskId)) {
                return Result.error("任务ID不能为空");
            }

            // 查询任务信息
            Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
            if (task == null) {
                return Result.error("任务不存在或已完成");
            }

            // 获取流程变量
            Map<String, Object> formValues = getProcessVariables(taskId);

            // 处理表单数据
            Map<String, Object> formData = processFormData(task);

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("taskId", taskId);
            result.put("taskName", task.getName());
            result.put("processInstanceId", task.getProcessInstanceId());
            result.put("curForm", formData);
            if(formValues.get("_value")!=null){
                result.put("formValues", formValues.get("_value"));
            }else{
                result.put("formValues", formValues);
            }


            result.put("formKey", task.getFormKey());
            if(task.getFormKey()!=null) {
                Integer formId = Integer.parseInt(task.getFormKey());
                FlowForm flowForm = flowFormService.getById(formId);
                result.put("flowForm",flowForm);
            }
            return Result.OK(result);

        } catch (Exception e) {
            log.error("获取任务表单数据失败，任务ID: {}", taskId, e);
            return Result.error("获取表单数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取流程变量
     */
    private Map<String, Object> getProcessVariables(String taskId) {
        // 先查询历史任务实例（已完成的任务）
        HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery()
                .includeProcessVariables()
                .finished()
                .taskId(taskId)
                .singleResult();

        if (historicTaskInstance != null) {
            return historicTaskInstance.getProcessVariables();
        } else {
            // 如果是当前任务，获取当前变量
            return taskService.getVariables(taskId);
        }
    }

    /**
     * 处理表单数据
     */
    private Map<String, Object> processFormData(Task task) {
        Map<String, Object> formData = new HashMap<>();

        // 如果有表单KEY，处理表单配置
        if (StringUtils.isNotBlank(task.getFormKey())) {
            processFormConfiguration(task.getFormKey(), formData);
        }

        // 处理特殊字段类型的默认值
        initializeSpecialFields(formData);

        return formData;
    }

    /**
     * 处理表单配置
     */
    private void processFormConfiguration(String formKey, Map<String, Object> formData) {
        try {
            // 根据表单KEY查询表单定义
            Long formId = Long.parseLong(formKey);
            FlowForm sysForm = flowFormService.getById(formId); // 假设有这个方法

            if (sysForm != null && StringUtils.isNotBlank(sysForm.getFormContent())) {
                JSONObject formConfig = JSONObject.parseObject(sysForm.getFormContent());
                JSONArray widgetList = formConfig.getJSONArray("widgetList");

                if (widgetList != null) {
                    // 为表单字段设置默认值
                    for (int i = 0; i < widgetList.size(); i++) {
                        JSONObject field = widgetList.getJSONObject(i);
                        String fieldId = field.getString("id");
                        String fieldType = field.getString("type");

                        // 如果变量中不存在该字段，设置默认值
                        if (!formData.containsKey(fieldId)) {
                            Object defaultValue = getDefaultValueByType(fieldType);
                            formData.put(fieldId, defaultValue);
                        }

                        // 处理子表单等复杂类型
                        processComplexField(field, formData);
                    }

                    // 将表单配置也返回给前端
                    formData.put("formConfig", formConfig);
                }
            }
        } catch (Exception e) {
            log.warn("处理表单配置失败，formKey: {}", formKey, e);
        }
    }

    /**
     * 根据字段类型获取默认值
     */
    private Object getDefaultValueByType(String fieldType) {
        switch (fieldType) {
            case "picture-upload":
            case "file-upload":
                return new ArrayList<>();
            case "number":
            case "rate":
                return 0;
            case "switch":
            case "checkbox":
                return false;
            case "select":
            case "radio":
                return "";
            default:
                return null;
        }
    }

    /**
     * 初始化特殊字段
     */
    private void initializeSpecialFields(Map<String, Object> formData) {
        // 确保图片上传等字段有默认值
        formData.forEach((key, value) -> {
            if (value == null) {
                // 根据key的名称推断类型（这是备选方案，最好从表单配置获取）
                if (key.contains("image") || key.contains("picture") || key.contains("upload")) {
                    formData.put(key, new ArrayList<>());
                }
            }
        });
    }

    /**
     * 处理复杂字段（如子表单）
     */
    private void processComplexField(JSONObject field, Map<String, Object> formData) {
        String fieldType = field.getString("type");

        if ("subform".equals(fieldType)) {
            String fieldId = field.getString("id");
            // 确保子表单字段有默认的空数组值
            if (!formData.containsKey(fieldId)) {
                formData.put(fieldId, new ArrayList<>());
            }
        }
    }

}