package com.qqchen.deploy.backend.workflow.converter;

import com.qqchen.deploy.backend.framework.converter.BaseConverter;
import com.qqchen.deploy.backend.framework.security.SecurityUtils;
import com.qqchen.deploy.backend.workflow.dto.FormDataCreateFromWorkflowRequest;
import com.qqchen.deploy.backend.workflow.dto.FormDataDTO;
import com.qqchen.deploy.backend.workflow.dto.FormDefinitionDTO;
import com.qqchen.deploy.backend.workflow.entity.FormData;
import com.qqchen.deploy.backend.workflow.enums.FormBusinessTypeEnums;
import com.qqchen.deploy.backend.workflow.enums.FormDataStatusEnums;
import org.mapstruct.AfterMapping;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingTarget;

import java.time.LocalDateTime;

/**
 * 表单数据转换器
 *
 * @author qqchen
 * @date 2025-10-24
 */
@Mapper(config = BaseConverter.class)
public interface FormDataConverter extends BaseConverter<FormData, FormDataDTO> {

    /**
     * 从工作流启动创建表单数据 DTO
     * 从 FormDefinitionDTO 和 FormDataCreateFromWorkflowRequest 映射到 FormDataDTO
     *
     * @param formDefinition 表单定义
     * @param request 工作流表单数据请求
     * @return 表单数据 DTO
     */
    @Mapping(target = "id", ignore = true)
    @Mapping(target = "formDefinitionId", source = "formDefinition.id")
    @Mapping(target = "formKey", source = "formDefinition.key")
    @Mapping(target = "formVersion", source = "formDefinition.formVersion")
    @Mapping(target = "categoryId", source = "formDefinition.categoryId")
    @Mapping(target = "schemaSnapshot", source = "formDefinition.schema")
    @Mapping(target = "data", source = "request.formData")
    @Mapping(target = "businessKey", source = "request.businessKey")
    @Mapping(target = "businessType", constant = "WORKFLOW")
    @Mapping(target = "status", constant = "SUBMITTED")
    @Mapping(target = "submitter", ignore = true)  // 在 @AfterMapping 中设置
    @Mapping(target = "submitTime", ignore = true)  // 在 @AfterMapping 中设置
    @Mapping(target = "createTime", ignore = true)
    @Mapping(target = "updateTime", ignore = true)
    @Mapping(target = "createBy", ignore = true)
    @Mapping(target = "updateBy", ignore = true)
    @Mapping(target = "version", ignore = true)
    @Mapping(target = "deleted", ignore = true)
    FormDataDTO fromWorkflowRequest(
        FormDefinitionDTO formDefinition,
        FormDataCreateFromWorkflowRequest request
    );

    /**
     * 后处理：设置动态值
     */
    @AfterMapping
    default void setDynamicFields(@MappingTarget FormDataDTO formDataDTO) {
        // ✅ 设置当前用户
        formDataDTO.setSubmitter(SecurityUtils.getCurrentUserIdAsString());
        
        // ✅ 设置提交时间
        formDataDTO.setSubmitTime(LocalDateTime.now());
    }
}

