package com.ai.da.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.ai.da.common.context.UserContext;
import com.ai.da.mapper.primary.*;
import com.ai.da.mapper.primary.entity.*;
import com.ai.da.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements ProjectService {

    @Override
    public Set<Long> getChildProjectIdSet(Long projectId) {
        QueryWrapper<Project> qw = new QueryWrapper<>();
//        qw.lambda().eq(Project::getParentId, projectId);
        List<Project> projectList = baseMapper.selectList(qw);
        if (CollectionUtil.isNotEmpty(projectList)) {
            return projectList.stream().map(Project::getId).collect(Collectors.toSet());
        }
        return new HashSet<>();
    }

    @Override
    public List<Project> getByProjectNameLike(String projectName) {
        QueryWrapper<Project> qw = new QueryWrapper<>();
        qw.lambda().like(Project::getName, projectName);
        return baseMapper.selectList(qw);
    }

    @Resource
    private BatchTaskSequenceMapper sequenceMapper;

    /**
     * 获取或创建用户的任务序号
     * @return 当前可用的序号
     */
    @Transactional
    public synchronized Integer getOrCreateSequence() {

        Long accountId = UserContext.getUserHolder().getId();
        // 1. 检查是否已有锁定序号
        BatchTaskSequence sequence = sequenceMapper.selectOne(
                Wrappers.<BatchTaskSequence>lambdaQuery()
                        .eq(BatchTaskSequence::getAccountId, accountId));

        if (sequence != null && sequence.getLockedSeq() != null) {
            return sequence.getLockedSeq();
        }

        // 2. 没有锁定序号，创建新记录或获取新序号
        if (sequence == null) {
            sequence = new BatchTaskSequence();
            sequence.setAccountId(accountId);
            sequence.setNextSeq(2); // 第一次返回1，下次从2开始
            sequence.setLockedSeq(1);
            sequenceMapper.insert(sequence);
            return 1;
        } else {
            Integer seq = sequence.getNextSeq();
            sequence.setLockedSeq(seq);
            sequence.setNextSeq(seq + 1);
            sequenceMapper.updateById(sequence);
            return seq;
        }
    }

    /**
     * 清除锁定序号状态（用于确认使用或取消操作）
     * @param accountId 用户ID
     */
    @Transactional
    public void clearLockedSequence(Long accountId) {
        sequenceMapper.update(null,
                Wrappers.<BatchTaskSequence>lambdaUpdate()
                        .set(BatchTaskSequence::getLockedSeq, null)
                        .eq(BatchTaskSequence::getAccountId, accountId));
    }

    public void modifyProjectUpdateTime(Long projectId){
        baseMapper.update(null,
                new UpdateWrapper<Project>()
                        .eq("id", projectId)
                        .set("update_time", LocalDateTime.now())
        );
    }
}