package com.lesingle.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lesingle.edu.common.enums.GenericStatus;
import com.lesingle.edu.common.enums.TaskStatus;
import com.lesingle.edu.common.enums.UserRole;
import com.lesingle.edu.common.enums.ErrorCode;
import com.lesingle.edu.common.exception.BusinessException;
import com.lesingle.edu.dto.request.CreateTaskFromTemplateRequest;
import com.lesingle.edu.dto.request.TaskTemplateCreateRequest;
import com.lesingle.edu.entity.Task;
import com.lesingle.edu.entity.TaskTemplate;
import com.lesingle.edu.entity.TaskTarget;
import com.lesingle.edu.mapper.TaskMapper;
import com.lesingle.edu.mapper.TaskTargetMapper;
import com.lesingle.edu.mapper.TaskTemplateMapper;
import com.lesingle.edu.service.TaskTemplateService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.util.List;

/**
 * 任务模板服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TaskTemplateServiceImpl extends ServiceImpl<TaskTemplateMapper, TaskTemplate>
    implements TaskTemplateService {

    private final TaskTemplateMapper taskTemplateMapper;
    private final TaskMapper taskMapper;
    private final TaskTargetMapper taskTargetMapper;

    @Override
    public Page<TaskTemplate> getTemplates(Long tenantId, Integer pageNum, Integer pageSize, String type, String keyword, Boolean publicOnly) {
        log.debug("获取模板列表，租户 ID: {}, 页码：{}, 类型：{}, 关键词：{}", tenantId, pageNum, type, keyword);

        Page<TaskTemplate> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<TaskTemplate> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(TaskTemplate::getTenantId, tenantId);
        if (Boolean.TRUE.equals(publicOnly)) {
            wrapper.eq(TaskTemplate::getIsPublic, 1);
        }
        wrapper.eq(TaskTemplate::getStatus, GenericStatus.ACTIVE.getCode());

        if (StringUtils.hasText(type)) {
            wrapper.and(w -> w.eq(TaskTemplate::getType, type).or().eq(TaskTemplate::getTaskType, type));
        }
        if (StringUtils.hasText(keyword)) {
            wrapper.like(TaskTemplate::getName, keyword);
        }

        wrapper.orderByDesc(TaskTemplate::getCreatedAt);

        return taskTemplateMapper.selectPage(page, wrapper);
    }

    @Override
    public TaskTemplate getDefaultTemplate(Long tenantId, String type) {
        log.debug("获取默认模板，租户 ID: {}, 类型：{}", tenantId, type);

        return taskTemplateMapper.selectOne(
                new LambdaQueryWrapper<TaskTemplate>()
                        .eq(TaskTemplate::getTenantId, tenantId)
                        .eq(TaskTemplate::getTaskType, type)
                        .eq(TaskTemplate::getIsDefault, 1)
                        .eq(TaskTemplate::getStatus, GenericStatus.ACTIVE.getCode())
        );
    }

    @Override
    public TaskTemplate getTemplateById(Long id) {
        TaskTemplate template = taskTemplateMapper.selectById(id);
        if (template == null) {
            throw new BusinessException(ErrorCode.DATA_NOT_FOUND, "模板不存在");
        }
        return template;
    }

    @Override
    @Transactional
    public TaskTemplate createTemplate(Long tenantId, Long userId, TaskTemplateCreateRequest request) {
        log.info("创建任务模板，租户 ID: {}, 用户 ID: {}", tenantId, userId);

        TaskTemplate template = new TaskTemplate();
        template.setTenantId(tenantId);
        template.setName(request.getName());
        template.setDescription(request.getDescription());
        template.setType(request.getType() != null ? request.getType() : request.getTaskType());
        template.setTaskType(request.getTaskType());
        template.setRelatedCourseId(request.getRelatedCourseId());
        template.setDefaultDuration(request.getDefaultDuration() != null ? request.getDefaultDuration() : 7);
        template.setIsDefault(Boolean.TRUE.equals(request.getIsDefault()) ? 1 : 0);
        template.setStatus(GenericStatus.ACTIVE.getCode());
        template.setCreatedBy(userId);
        template.setContent(request.getContent());
        template.setIsPublic(Boolean.TRUE.equals(request.getIsPublic()) ? 1 : 0);

        taskTemplateMapper.insert(template);
        log.info("任务模板创建成功，ID: {}", template.getId());
        return template;
    }

    @Override
    @Transactional
    public TaskTemplate updateTemplate(Long id, TaskTemplateCreateRequest request) {
        log.info("更新任务模板，ID: {}", id);

        TaskTemplate template = getTemplateById(id);

        if (StringUtils.hasText(request.getName())) {
            template.setName(request.getName());
        }
        if (request.getDescription() != null) {
            template.setDescription(request.getDescription());
        }
        if (request.getType() != null) {
            template.setType(request.getType());
        }
        if (request.getTaskType() != null) {
            template.setTaskType(request.getTaskType());
        }
        if (request.getRelatedCourseId() != null) {
            template.setRelatedCourseId(request.getRelatedCourseId());
        }
        if (request.getDefaultDuration() != null) {
            template.setDefaultDuration(request.getDefaultDuration());
        }
        if (request.getIsDefault() != null) {
            template.setIsDefault(request.getIsDefault() ? 1 : 0);
        }
        if (request.getContent() != null) {
            template.setContent(request.getContent());
        }
        if (request.getIsPublic() != null) {
            template.setIsPublic(request.getIsPublic() ? 1 : 0);
        }

        taskTemplateMapper.updateById(template);
        log.info("任务模板更新成功，ID: {}", id);
        return template;
    }

    @Override
    @Transactional
    public void deleteTemplate(Long id) {
        log.info("删除任务模板，ID: {}", id);

        getTemplateById(id);
        taskTemplateMapper.deleteById(id);

        log.info("任务模板删除成功，ID: {}", id);
    }

    @Override
    @Transactional
    public Task createTaskFromTemplate(Long tenantId, Long userId, Long templateId, CreateTaskFromTemplateRequest request) {
        log.info("从模板创建任务，模板 ID: {}, 用户 ID: {}", templateId, userId);

        // 获取模板
        TaskTemplate template = getTemplateById(templateId);

        // 创建任务
        Task task = new Task();
        task.setTenantId(tenantId);
        task.setTitle(request.getTitle());
        task.setDescription(request.getDescription());
        task.setType(template.getTaskType());
        task.setCourseId(template.getRelatedCourseId());

        // 解析日期
        if (StringUtils.hasText(request.getStartDate())) {
            try {
                task.setStartDate(LocalDate.parse(request.getStartDate()));
            } catch (Exception e) {
                log.warn("开始日期解析失败：{}", request.getStartDate());
            }
        }
        if (StringUtils.hasText(request.getEndDate())) {
            try {
                task.setDueDate(LocalDate.parse(request.getEndDate()));
            } catch (Exception e) {
                log.warn("截止日期解析失败：{}", request.getEndDate());
            }
        }

        task.setStatus(TaskStatus.PENDING.getCode());
        task.setCreatorId(userId);
        task.setCreatorRole(UserRole.TEACHER.getCode());

        taskMapper.insert(task);
        log.info("任务创建成功，ID: {}", task.getId());

        // 创建任务目标
        if (request.getTargetIds() != null && !request.getTargetIds().isEmpty()) {
            for (Long targetId : request.getTargetIds()) {
                TaskTarget target = new TaskTarget();
                target.setTaskId(task.getId());
                target.setTargetType(request.getTargetType());
                target.setTargetId(targetId);
                taskTargetMapper.insert(target);
            }
            log.info("任务目标创建完成，任务 ID: {}", task.getId());
        }

        return task;
    }

}
