package com.seer.teach.mp.app.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.utils.PageConverterUtils;
import com.seer.teach.mp.app.controller.req.ActivityFormSubmitReq;
import com.seer.teach.mp.app.controller.req.AppActivityFormExecutionQueryReq;
import com.seer.teach.mp.app.controller.resp.AppActivityFormExecutionResp;
import com.seer.teach.mp.app.controller.resp.AppActivityFormResp;
import com.seer.teach.mp.app.controller.resp.AppActivityFormFieldResp;
import com.seer.teach.mp.app.convert.AppActivityFormConvert;
import com.seer.teach.mp.app.service.IAppActivityFormService;
import com.seer.teach.mp.entity.*;
import com.seer.teach.mp.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * APP端活动表单服务实现类
 * </p>
 *
 * @author Lingma
 * @since 2026-01-10
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AppActivityFormServiceImpl implements IAppActivityFormService {

    private final IMpActivityFormService activityFormTemplateService;
    private final IMpActivityFormFieldService activityFormFieldService;
    private final IMpActivityFormExecutionService activityFormExecutionService;
    private final IMpActivityFormVariableService activityFormVariableService;
    private final IMpActivityService mpActivityService;
    private final IMpActivityFormRelationService activityFormTemplateRelationService;

    @Override
    public AppActivityFormResp getFormByActivity(Integer activityId) {
        // 首先检查活动是否存在
        MpActivityEntity activity = mpActivityService.getById(activityId);
        if (activity == null) {
            log.warn("活动不存在，ID：{}", activityId);
            return null;
        }
        
        // 从关联表中获取与活动关联的表单ID
        Integer formId = activityFormTemplateRelationService.getPrimaryFormIdByActivityId(activityId);
        
        if (formId != null) {
            MpActivityFormEntity template = activityFormTemplateService.getById(formId);
            if (template != null) {
                AppActivityFormResp resp = AppActivityFormConvert.INSTANCE.convertToAppTemplateResp(template);
                
                // 获取该表单的所有字段
                List<MpActivityFormFieldEntity> fields = activityFormFieldService.list(
                    new LambdaQueryWrapper<MpActivityFormFieldEntity>()
                        .eq(MpActivityFormFieldEntity::getFormId, formId)
                );
                
                List<AppActivityFormFieldResp> fieldResps = fields.stream()
                    .map(AppActivityFormConvert.INSTANCE::convertToAppFieldResp)
                    .collect(Collectors.toList());
                    
                resp.setFields(fieldResps);
                return resp;
            }
        }
        Optional<MpActivityFormRelationEntity> relation = activityFormTemplateRelationService.getLatestVersionByActivityId(activityId);
        
        if (relation.isPresent()) {
            formId = relation.get().getFormId();
            MpActivityFormEntity template = activityFormTemplateService.getById(formId);
            if (template != null) {
                AppActivityFormResp resp = AppActivityFormConvert.INSTANCE.convertToAppTemplateResp(template);
                
                // 获取该表单的所有字段
                List<MpActivityFormFieldEntity> fields = activityFormFieldService.list(
                    new LambdaQueryWrapper<MpActivityFormFieldEntity>()
                        .eq(MpActivityFormFieldEntity::getFormId, formId)
                );
                List<AppActivityFormFieldResp> fieldResps = fields.stream()
                    .map(AppActivityFormConvert.INSTANCE::convertToAppFieldResp)
                    .collect(Collectors.toList());
                    
                resp.setFields(fieldResps);
                return resp;
            }
        }
        log.warn("未找到活动 {} 关联的表单表单", activityId);
        return null;
    }

    @Override
    public List<AppActivityFormFieldResp> getFieldListByTemplate(Integer templateId) {
        List<MpActivityFormFieldEntity> fields = activityFormFieldService.list(
            new LambdaQueryWrapper<MpActivityFormFieldEntity>()
                .eq(MpActivityFormFieldEntity::getFormId, templateId)
                .orderByAsc(MpActivityFormFieldEntity::getSortOrder)
                .orderByDesc(MpActivityFormFieldEntity::getId)
        );
        
        return fields.stream()
            .map(AppActivityFormConvert.INSTANCE::convertToAppFieldResp)
            .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public String submitForm(ActivityFormSubmitReq req, Integer userId) {
        // 生成执行编号
        String executionNo = "AFE-" + System.currentTimeMillis() + "-" + IdUtil.getSnowflakeNextId();
        
        // 创建表单执行实例
        MpActivityFormExecutionEntity execution = new MpActivityFormExecutionEntity();
        execution.setExecutionNo(executionNo);
        execution.setActivityId(req.getActivityId());
        execution.setAgentId(req.getAgentId());
        execution.setFormId(req.getFormId());
        execution.setSubmitterId(userId); // 设置提交人ID为当前登录用户ID
        execution.setSubmitTime(LocalDateTime.now());
        execution.setStatus("submitted"); // 设置状态为已提交
        
        // 保存表单执行实例
        activityFormExecutionService.save(execution);
        
        // 处理表单数据，将其存储到变量表中
        if (req.getFormData() != null && !req.getFormData().isEmpty()) {
            for (Map.Entry<String, Object> entry : req.getFormData().entrySet()) {
                MpActivityFormVariableEntity variable = new MpActivityFormVariableEntity();
                variable.setExecutionId(execution.getId());
                variable.setVariableName(entry.getKey()); // 使用字段代码作为变量名
                variable.setVariableCode(entry.getKey()); // 使用字段代码作为变量代码
                variable.setVariableValue(String.valueOf(entry.getValue())); // 将值转换为字符串存储
                variable.setDataType(getDataType(entry.getValue())); // 根据值确定数据类型
                
                activityFormVariableService.save(variable);
            }
        }
        
        log.info("表单提交成功，执行编号：{}", executionNo);
        return executionNo;
    }
    
    /**
     * 根据执行ID获取完整表单数据
     */
    public AppActivityFormExecutionResp getExecutionWithFormData(Integer executionId) {
        MpActivityFormExecutionEntity execution = activityFormExecutionService.getById(executionId);
        if (execution == null) {
            return null;
        }
        
        AppActivityFormExecutionResp resp = AppActivityFormConvert.INSTANCE.convertToAppExecutionResp(execution);
        
        // 获取表单变量数据
        List<MpActivityFormVariableEntity> variables = activityFormVariableService.list(
            new LambdaQueryWrapper<MpActivityFormVariableEntity>()
                .eq(MpActivityFormVariableEntity::getExecutionId, executionId)
        );
        
        // 转换为Map形式的表单数据
        Map<String, Object> formData = new HashMap<>();
        for (MpActivityFormVariableEntity variable : variables) {
            // 根据数据类型转换值
            Object value = convertValueByType(variable.getVariableValue(), variable.getDataType());
            formData.put(variable.getVariableCode(), value);
        }
        
        resp.setFormData(formData);
        return resp;
    }

    /**
     * 根据数据类型转换值
     */
    private Object convertValueByType(String value, String dataType) {
        if (value == null) {
            return null;
        }
        
        switch (dataType) {
            case "boolean":
                return Boolean.parseBoolean(value);
            case "number":
                try {
                    // 尝试解析为整数或浮点数
                    if (value.contains(".")) {
                        return Double.parseDouble(value);
                    } else {
                        return Long.parseLong(value);
                    }
                } catch (NumberFormatException e) {
                    return value; // 如果无法解析为数字，则返回原始字符串
                }
            case "string":
            default:
                return value;
        }
    }
    
    /**
     * 根据值判断数据类型
     */
    private String getDataType(Object value) {
        if (value instanceof Boolean) {
            return "boolean";
        } else if (value instanceof Number) {
            return "number";
        } else if (value instanceof String) {
            return "string";
        } else {
            return "string";
        }
    }
    
    @Override
    public PageListBean<AppActivityFormExecutionResp> getExecutionList(AppActivityFormExecutionQueryReq query, Integer userId) {
        Page<MpActivityFormExecutionEntity> page = new Page<>(query.getPageNo(), query.getPageSize());
        
        LambdaQueryWrapper<MpActivityFormExecutionEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MpActivityFormExecutionEntity::getSubmitterId, userId)
               .eq(query.getActivityId() != null, MpActivityFormExecutionEntity::getActivityId, query.getActivityId())
               .eq(query.getAgentId() != null, MpActivityFormExecutionEntity::getAgentId, query.getAgentId())
               .orderByDesc(MpActivityFormExecutionEntity::getId);

        Page<MpActivityFormExecutionEntity> pageResult = activityFormExecutionService.page(page, wrapper);
        List<AppActivityFormExecutionResp> records = pageResult.getRecords().stream()
                .map(AppActivityFormConvert.INSTANCE::convertToAppExecutionResp)
                .collect(Collectors.toList());

        return PageConverterUtils.convertPageListBean(pageResult, records);
    }
}