package com.fs.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fs.course.domain.FsUserProjectQw;
import com.fs.course.domain.FsUserProjectRepeat;
import com.fs.course.mapper.FsUserProjectQwMapper;
import com.fs.course.mapper.FsUserProjectRepeatMapper;
import com.fs.course.service.IUserProjectRepeatMaintainService;
import com.fs.course.support.CourseProjectEquivalence;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class UserProjectRepeatMaintainServiceImpl implements IUserProjectRepeatMaintainService {

    @Autowired
    private FsUserProjectQwMapper fsUserProjectQwMapper;

    @Autowired
    private FsUserProjectRepeatMapper fsUserProjectRepeatMapper;

    @Override
    public void maintain(Long fsUserId, Long projectId, Long qwUserId, Long companyId) {
        if (fsUserId == null || projectId == null || projectId == 0L || qwUserId == null) {
            return;
        }
        try {
            fsUserProjectQwMapper.insertOrIgnore(fsUserId, projectId, qwUserId, companyId);

            List<Long> equivalentProjectIds = CourseProjectEquivalence.equivalentProjectIds(projectId);
            Long canonicalProjectId = CourseProjectEquivalence.canonicalProjectId(projectId);
            int qwUserCount = fsUserProjectQwMapper.countDistinctQwUser(fsUserId, equivalentProjectIds);
            int isRepeat = qwUserCount >= 2 ? 1 : 0;

            fsUserProjectRepeatMapper.upsert(fsUserId, canonicalProjectId, companyId, qwUserCount, isRepeat);
        } catch (Exception e) {
            log.error("维护项目重粉中间表失败 fsUserId={}, projectId={}, qwUserId={}",
                    fsUserId, projectId, qwUserId, e);
        }
    }

    @Override
    public boolean isRepeatByProject(Long fsUserId, Long projectId) {
        if (fsUserId == null || projectId == null || projectId == 0L) {
            return false;
        }
        Long canonicalProjectId = CourseProjectEquivalence.canonicalProjectId(projectId);
        FsUserProjectRepeat record = fsUserProjectRepeatMapper.selectOne(
                new QueryWrapper<FsUserProjectRepeat>()
                        .eq("fs_user_id", fsUserId)
                        .eq("project_id", canonicalProjectId)
                        .last("LIMIT 1"));
        return record != null && record.getIsRepeat() != null && record.getIsRepeat() == 1;
    }

    @Override
    public boolean isRepeatInAnyProject(Long fsUserId) {
        if (fsUserId == null) {
            return false;
        }
        Integer count = fsUserProjectRepeatMapper.selectCount(
                new QueryWrapper<FsUserProjectRepeat>()
                        .eq("fs_user_id", fsUserId)
                        .eq("is_repeat", 1));
        return count != null && count > 0;
    }

    @Override
    public boolean wouldBeRepeatAfterBind(Long fsUserId, Long projectId, Long qwUserId) {
        if (fsUserId == null || projectId == null || projectId == 0L) {
            return false;
        }
        if (isRepeatByProject(fsUserId, projectId)) {
            return true;
        }
        if (qwUserId == null) {
            return false;
        }
        List<Long> equivalentProjectIds = CourseProjectEquivalence.equivalentProjectIds(projectId);
        int distinctCount = fsUserProjectQwMapper.countDistinctQwUser(fsUserId, equivalentProjectIds);
        if (distinctCount >= 2) {
            return true;
        }
        if (distinctCount == 0) {
            return false;
        }
        return fsUserProjectQwMapper.existsQwUserInProjects(fsUserId, qwUserId, equivalentProjectIds) == 0;
    }

    @Override
    public void migrateQwUserOnTransfer(Long fsUserId, Long oldQwUserId, Long newQwUserId, Long companyId) {
        if (fsUserId == null || oldQwUserId == null || newQwUserId == null || oldQwUserId.equals(newQwUserId)) {
            return;
        }
        try {
            List<FsUserProjectQw> oldRows = fsUserProjectQwMapper.selectList(
                    new QueryWrapper<FsUserProjectQw>()
                            .eq("fs_user_id", fsUserId)
                            .eq("qw_user_id", oldQwUserId));
            if (oldRows.isEmpty()) {
                return;
            }

            Set<Long> projectsToRefresh = new HashSet<>();
            for (FsUserProjectQw row : oldRows) {
                projectsToRefresh.add(row.getProjectId());
                FsUserProjectQw existingNew = fsUserProjectQwMapper.selectOne(
                        new QueryWrapper<FsUserProjectQw>()
                                .eq("fs_user_id", fsUserId)
                                .eq("project_id", row.getProjectId())
                                .eq("qw_user_id", newQwUserId)
                                .last("LIMIT 1"));
                if (existingNew != null) {
                    fsUserProjectQwMapper.deleteById(row.getId());
                } else {
                    FsUserProjectQw update = new FsUserProjectQw();
                    update.setId(row.getId());
                    update.setQwUserId(newQwUserId);
                    update.setUpdateTime(new Date());
                    if (companyId != null) {
                        update.setCompanyId(companyId);
                    }
                    fsUserProjectQwMapper.updateById(update);
                }
            }

            for (Long projectId : projectsToRefresh) {
                maintain(fsUserId, projectId, newQwUserId, companyId);
            }
            log.info("转接迁移重粉中间表成功 fsUserId={}, oldQwUserId={}, newQwUserId={}, projects={}",
                    fsUserId, oldQwUserId, newQwUserId, projectsToRefresh);
        } catch (Exception e) {
            log.error("转接迁移重粉中间表失败 fsUserId={}, oldQwUserId={}, newQwUserId={}",
                    fsUserId, oldQwUserId, newQwUserId, e);
        }
    }
}
