package com.fs.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fs.common.utils.StringUtils;
import com.fs.course.domain.*;
import com.fs.course.mapper.FsUserCompanyQwMapper;
import com.fs.course.mapper.FsUserCourseMapper;
import com.fs.course.mapper.FsUserCourseVideoMapper;
import com.fs.course.param.FsUserCourseVideoAddKfUParam;
import com.fs.course.service.ICourseRepeatByProjectService;
import com.fs.course.support.CourseProjectEquivalence;
import com.fs.course.service.IFsUserCompanyBindService;
import com.fs.course.service.IFsUserCompanyUserService;
import com.fs.course.service.IUserProjectRepeatMaintainService;
import com.fs.his.domain.FsUser;
import com.fs.his.mapper.FsUserMapper;
import com.fs.qw.domain.QwExternalContact;
import com.fs.qw.mapper.QwExternalContactMapper;
import com.fs.qw.service.IQwExternalContactService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CourseRepeatByProjectServiceImpl implements ICourseRepeatByProjectService {

    @Autowired
    private FsUserCourseMapper fsUserCourseMapper;
    @Autowired
    private FsUserCourseVideoMapper fsUserCourseVideoMapper;
    @Autowired
    private FsUserCompanyQwMapper fsUserCompanyQwMapper;
    @Autowired
    private IFsUserCompanyUserService userCompanyUserService;
    @Autowired
    private IFsUserCompanyBindService fsUserCompanyBindService;
    @Autowired
    private QwExternalContactMapper qwExternalContactMapper;
    @Autowired
    private IQwExternalContactService qwExternalContactService;
    @Autowired
    private FsUserMapper fsUserMapper;
    @Autowired
    private IUserProjectRepeatMaintainService userProjectRepeatMaintainService;

    @Override
    public void checkAndMarkRepeatByProject(FsUserCourseVideoAddKfUParam param, FsUser fsUser) {
        Long projectId = resolveCourseProjectId(param);
        if (projectId == null || projectId == 0L) {
            log.debug("看课重粉判断跳过：课程未关联项目，userId={}", param.getUserId());
            return;
        }
        List<Long> equivalentProjectIds = CourseProjectEquivalence.equivalentProjectIds(projectId);
        Long currentQwUserId = parseQwUserId(param.getQwUserId());
        boolean projectRepeat = userProjectRepeatMaintainService.wouldBeRepeatAfterBind(
                param.getUserId(), projectId, currentQwUserId);
        boolean userAlreadyRepeat = fsUser.getIsRepeat() != null && fsUser.getIsRepeat() == 1;
        log.info("看课重粉判断（按项目）：userId={}, projectId={}, equivalentProjectIds={}, projectRepeat={}, userAlreadyRepeat={}",
                param.getUserId(), projectId, equivalentProjectIds, projectRepeat, userAlreadyRepeat);
        if (projectRepeat || userAlreadyRepeat) {
            markRepeatFansByProject(fsUser, param, equivalentProjectIds);
            return;
        }
        if (param.getQwExternalId() != null) {
            recordUserProjectBind(param, param.getQwExternalId(), "isAddKf");
        }
    }

    private Long resolveCourseProjectId(FsUserCourseVideoAddKfUParam param) {
        if (param.getCourseId() != null) {
            FsUserCourse course = fsUserCourseMapper.selectFsUserCourseByCourseId(param.getCourseId());
            if (course != null && course.getProject() != null && course.getProject() != 0L) {
                return course.getProject();
            }
        }
        if (param.getVideoId() != null) {
            FsUserCourseVideo video = fsUserCourseVideoMapper.selectFsUserCourseVideoByVideoId(param.getVideoId());
            if (video != null && video.getCourseId() != null) {
                FsUserCourse course = fsUserCourseMapper.selectFsUserCourseByCourseId(video.getCourseId());
                if (course != null && course.getProject() != null) {
                    return course.getProject();
                }
            }
        }
        return 0L;
    }

    private Long parseQwUserId(String qwUserId) {
        if (StringUtils.isEmpty(qwUserId)) {
            return null;
        }
        try {
            return Long.parseLong(qwUserId);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    private void markRepeatFansByProject(FsUser fsUser, FsUserCourseVideoAddKfUParam param, List<Long> equivalentProjectIds) {
        syncProjectRepeatTable(param, equivalentProjectIds);

        List<QwExternalContact> toUpdate = new ArrayList<>();
        if (param.getQwExternalId() != null) {
            QwExternalContact current = qwExternalContactMapper.selectById(param.getQwExternalId());
            if (current != null) {
                current.setIsRepeat(1);
                toUpdate.add(current);
            }
        }
        List<FsUserCompanyBind> binds = fsUserCompanyBindService.list(
                new QueryWrapper<FsUserCompanyBind>().eq("fs_user_id", param.getUserId()).in("project_id", equivalentProjectIds));
        if (CollectionUtils.isNotEmpty(binds)) {
            Set<Long> contactIds = binds.stream().map(FsUserCompanyBind::getQwExternalContactId)
                    .filter(Objects::nonNull).collect(Collectors.toSet());
            for (Long contactId : contactIds) {
                if (toUpdate.stream().anyMatch(c -> contactId.equals(c.getId()))) {
                    continue;
                }
                QwExternalContact contact = qwExternalContactMapper.selectById(contactId);
                if (contact != null) {
                    contact.setIsRepeat(1);
                    toUpdate.add(contact);
                }
            }
        }
        if (toUpdate.isEmpty()) {
            List<QwExternalContact> noRepeatList = qwExternalContactMapper.selectList(
                    new QueryWrapper<QwExternalContact>().eq("fs_user_id", param.getUserId()).eq("is_repeat", 0));
            noRepeatList.forEach(e -> e.setIsRepeat(1));
            toUpdate.addAll(noRepeatList);
        }
        if (!toUpdate.isEmpty()) {
            qwExternalContactService.updateBatchById(toUpdate);
        }
        if (fsUser.getIsRepeat() == null || fsUser.getIsRepeat() != 1) {
            fsUser.setIsRepeat(1);
            fsUserMapper.updateFsUser(fsUser);
        }
        for (Long projectId : equivalentProjectIds) {
            FsUserCompanyUser userCompanyUser = userCompanyUserService.selectByUserIdAndProjectId(param.getUserId(), projectId);
            if (userCompanyUser != null && (userCompanyUser.getIsRepeatFans() == null || userCompanyUser.getIsRepeatFans() != 1)) {
                userCompanyUser.setIsRepeatFans(1);
                userCompanyUserService.updateById(userCompanyUser);
            }
        }
    }

    /** 将本次及已有绑定销售同步写入中间表，保证 fs_user_project_repeat 与判重结果一致 */
    private void syncProjectRepeatTable(FsUserCourseVideoAddKfUParam param, List<Long> equivalentProjectIds) {
        Long currentQwUserId = parseQwUserId(param.getQwUserId());
        Long projectId = equivalentProjectIds.isEmpty() ? null : equivalentProjectIds.get(0);
        if (currentQwUserId != null && projectId != null) {
            userProjectRepeatMaintainService.maintain(
                    param.getUserId(), projectId, currentQwUserId, param.getCompanyId());
        }
        List<FsUserCompanyBind> binds = fsUserCompanyBindService.list(
                new QueryWrapper<FsUserCompanyBind>().eq("fs_user_id", param.getUserId()).in("project_id", equivalentProjectIds));
        if (CollectionUtils.isNotEmpty(binds)) {
            for (FsUserCompanyBind bind : binds) {
                if (bind.getQwUserId() != null && bind.getProjectId() != null) {
                    userProjectRepeatMaintainService.maintain(
                            bind.getFsUserId(), bind.getProjectId(), bind.getQwUserId(), bind.getCompanyId());
                }
            }
        }
    }

    private void recordUserProjectBind(FsUserCourseVideoAddKfUParam param, Long qwExternalId, String sceneName) {
        try {
            FsUserCourseVideo video = fsUserCourseVideoMapper.selectFsUserCourseVideoByVideoId(param.getVideoId());
            if (video == null || video.getCourseId() == null) {
                log.warn("【{}-记录绑定关系】视频信息不存在，视频ID: {}", sceneName, param.getVideoId());
                return;
            }

            FsUserCourse course = fsUserCourseMapper.selectFsUserCourseByCourseId(video.getCourseId());
            Long projectId = course != null && course.getProject() != null ? course.getProject() : 0L;

            if (projectId == 0L) {
                log.debug("【{}-记录绑定关系】课程未关联项目，跳过记录，课程ID: {}", sceneName, video.getCourseId());
                return;
            }

            Long qwUserId = param.getQwUserId() != null ? Long.parseLong(param.getQwUserId()) : null;
            fsUserCompanyQwMapper.insertOrUpdate(
                    param.getUserId(),
                    projectId,
                    qwUserId,
                    param.getCompanyUserId(),
                    param.getCompanyId(),
                    qwExternalId,
                    video.getCourseId(),
                    param.getVideoId()
            );

            userProjectRepeatMaintainService.maintain(
                    param.getUserId(), projectId, qwUserId, param.getCompanyId());

            log.info("【{}-记录绑定关系成功】用户ID: {}, 项目ID: {}, 销售ID: {}, 外部联系人id: {}",
                    sceneName, param.getUserId(), projectId, qwUserId, qwExternalId);

        } catch (Exception e) {
            log.error("【{}-记录绑定关系失败】用户ID: {}, 视频ID: {}, 错误: {}",
                    sceneName, param.getUserId(), param.getVideoId(), e.getMessage(), e);
        }
    }
}
