package com.fs.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.PubFun;
import com.fs.company.domain.Company;
import com.fs.company.domain.CompanyUser;
import com.fs.company.mapper.CompanyMapper;
import com.fs.company.mapper.CompanyUserMapper;
import com.fs.course.domain.FsCourseWatchLog;
import com.fs.course.domain.FsUserCompanyBind;
import com.fs.course.domain.FsUserCourse;
import com.fs.course.mapper.FsCourseWatchLogMapper;
import com.fs.course.mapper.FsUserCompanyBindMapper;
import com.fs.course.mapper.FsUserCourseMapper;
import com.fs.course.service.IFsUserCompanyBindService;
import com.fs.course.vo.UserWatchLogListVo;
import com.fs.his.mapper.FsUserMapper;
import com.fs.qw.domain.QwCompany;
import com.fs.qw.domain.QwExternalContact;
import com.fs.qw.mapper.QwCompanyMapper;
import com.fs.qw.mapper.QwExternalContactMapper;
import com.fs.qw.param.UserWatchLogParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 用户客服关联Service业务层处理
 *
 * @author fs
 * @date 2025-07-22
 */
@Slf4j
@Service
@AllArgsConstructor
public class FsUserCompanyBindServiceImpl extends ServiceImpl<FsUserCompanyBindMapper, FsUserCompanyBind> implements IFsUserCompanyBindService {

    private final CompanyUserMapper companyUserMapper;
    private FsUserMapper fsUserMapper;
    private FsCourseWatchLogMapper fsCourseWatchLogMapper;
    private QwExternalContactMapper qwExternalContactMapper;
    private FsUserCourseMapper fsUserCourseMapper;
    private QwCompanyMapper qwCompanyMapper;
    private CompanyMapper companyMapper;

    /**
     * 查询用户客服关联
     *
     * @param id 用户客服关联主键
     * @return 用户客服关联
     */
    @Override
    public FsUserCompanyBind selectFsUserCompanyBindById(Long id) {
        return baseMapper.selectFsUserCompanyBindById(id);
    }

    /**
     * 查询用户客服关联列表
     *
     * @param fsUserCompanyBind 用户客服关联
     * @return 用户客服关联
     */
    @Override
    public List<FsUserCompanyBind> selectFsUserCompanyBindList(FsUserCompanyBind fsUserCompanyBind) {
        return baseMapper.selectFsUserCompanyBindList(fsUserCompanyBind);
    }

    /**
     * 新增用户客服关联
     *
     * @param fsUserCompanyBind 用户客服关联
     * @return 结果
     */
    @Override
    public int insertFsUserCompanyBind(FsUserCompanyBind fsUserCompanyBind) {
        fsUserCompanyBind.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insertFsUserCompanyBind(fsUserCompanyBind);
    }

    /**
     * 修改用户客服关联
     *
     * @param fsUserCompanyBind 用户客服关联
     * @return 结果
     */
    @Override
    public int updateFsUserCompanyBind(FsUserCompanyBind fsUserCompanyBind) {
        fsUserCompanyBind.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateFsUserCompanyBind(fsUserCompanyBind);
    }

    /**
     * 批量删除用户客服关联
     *
     * @param ids 需要删除的用户客服关联主键
     * @return 结果
     */
    @Override
    public int deleteFsUserCompanyBindByIds(Long[] ids) {
        return baseMapper.deleteFsUserCompanyBindByIds(ids);
    }

    /**
     * 删除用户客服关联信息
     *
     * @param id 用户客服关联主键
     * @return 结果
     */
    @Override
    public int deleteFsUserCompanyBindById(Long id) {
        return baseMapper.deleteFsUserCompanyBindById(id);
    }

    @Override
    public boolean bindFsUser(Long fsUserId, Long externalUserId, Long watchLogId) {
        try {
            QwExternalContact qwExternalContact = qwExternalContactMapper.selectById(externalUserId);
            FsCourseWatchLog watchLog = fsCourseWatchLogMapper.selectById(watchLogId);
            FsUserCourse course = fsUserCourseMapper.selectFsUserCourseByCourseId(watchLog.getCourseId());
            Company company = companyMapper.selectCompanyById(qwExternalContact.getCompanyId());
            QwCompany qwCompany = qwCompanyMapper.selectQwCompanyByCorpId(qwExternalContact.getCorpId());
            // 员工ID
            Long companyUserId = qwExternalContact.getCompanyUserId();
            // 公司ID
            Long companyId = qwExternalContact.getCompanyId();
            // 企微用户ID
            Long qwUserId = qwExternalContact.getQwUserId();
            // 项目
            Long project = course.getProject() == null ? 0 : course.getProject();
            // 企微主体ID
            Long qwCompanyId = qwCompany.getId();
            // 课程ID
            Long courseId = watchLog.getCourseId();
            // 视频ID
            Long videoId = watchLog.getVideoId();
            // 看课记录ID
            Long logId = watchLog.getLogId();
            // 看课状态
            Integer logType = watchLog.getLogType();
            if (company.getRepeat() == 1 && project != 0) {
                List<FsUserCompanyBind> list = baseMapper.selectList(new QueryWrapper<FsUserCompanyBind>().eq("fs_user_id", fsUserId).eq("project_id", project).last(" GROUP BY qw_user_id"));
                if (!list.isEmpty() && list.stream().noneMatch(e -> e.getQwUserId().equals(qwUserId))) {
                    log.error("当前客户：{}已经有所属项目{}， 企微ID：{}， 当前企微ID：{}", fsUserId, project, PubFun.listToNewList(list, FsUserCompanyBind::getQwUserId), qwUserId);
                    return false;
                }
            }
            if (qwExternalContact.getUserRepeat() == 0) {
                Integer i = baseMapper.selectCount(new QueryWrapper<FsUserCompanyBind>().eq("fs_user_id", fsUserId).ne("company_user_id", companyUserId));
                if (i > 0) {
                    qwExternalContact.setUserRepeat(1);
                    qwExternalContactMapper.updateById(qwExternalContact);
                }
            }
            // 当前登录账号名称
            FsUserCompanyBind one = baseMapper.selectOne(new QueryWrapper<FsUserCompanyBind>()
                    .eq("fs_user_id", fsUserId)
                    .eq("project_id", project)
                    .eq("course_id", courseId)
                    .eq("qw_user_id", qwUserId)
                    .eq("company_user_id", companyUserId)
                    .eq("video_id", videoId));
            if (one == null) {
                FsUserCompanyBind bind = new FsUserCompanyBind();
                bind.setFsUserId(fsUserId);
                bind.setCompanyUserId(companyUserId);
                bind.setCompanyId(companyId);
                bind.setQwUserId(qwUserId);
                bind.setQwExternalContactId(externalUserId);
                bind.setProjectId(project);
                bind.setQwCompanyId(qwCompanyId);
                bind.setCourseId(courseId);
                bind.setVideoId(videoId);
                bind.setWatchLogId(logId);
                bind.setLogType(logType);
                bind.setCreateTime(new Date());
                bind.setUpdateTime(new Date());
                if (bind.getLogType() == 2) {
                    bind.setFinishTime(LocalDateTime.now());
                }
                try {
                    save(bind);
                } catch (Exception e) {
                    log.error("添加重粉失败", e);
                }
            }
            return true;
        }catch (Exception e){
            log.error("绑定关系错误", e);
            return false;
        }
    }

    @Override
    public void finish(Long fsUserId, Long qwUserId, Long companyUserId, FsCourseWatchLog watchLog) {
        FsUserCourse course = fsUserCourseMapper.selectFsUserCourseByCourseId(watchLog.getCourseId());
        FsUserCompanyBind one = baseMapper.selectOne(new QueryWrapper<FsUserCompanyBind>()
                .eq("fs_user_id", fsUserId)
                .eq("project_id", course.getProject())
                .eq("course_id", watchLog.getCourseId())
                .eq("qw_user_id", qwUserId)
                .eq("company_user_id", companyUserId)
                .eq("video_id", watchLog.getVideoId()));
        if(one == null){
            CompanyUser companyUser = companyUserMapper.selectCompanyUserById(companyUserId);
            QwCompany qwCompany = qwCompanyMapper.selectQwCompanyByCorpId(companyUser.getCorpId());
            one = new FsUserCompanyBind();
            one.setFsUserId(fsUserId);
            one.setCompanyUserId(companyUserId);
            one.setCompanyId(companyUser.getCompanyId());
            one.setQwUserId(qwUserId);
            one.setQwExternalContactId(watchLog.getQwExternalContactId());
            one.setProjectId(course.getProject());
            one.setQwCompanyId(qwCompany != null ? qwCompany.getId() : null);
            one.setCourseId(watchLog.getCourseId());
            one.setVideoId(watchLog.getVideoId());
            one.setWatchLogId(watchLog.getLogId());
            one.setLogType(2);
            one.setFinishTime(LocalDateTime.now());
            one.setCreateTime(new Date());
            one.setUpdateTime(new Date());
            try {
                save(one);
            } catch (Exception e) {
                log.error("添加重粉失败", e);
            }
        }else{
            one.setFinishTime(LocalDateTime.now());
            one.setLogType(2);
            updateById(one);
        }
    }

    @Override
    public List<UserWatchLogListVo> getWatchLogList(UserWatchLogParam param) {
        if(param.getExternalUserId() == null &&  param.getFsUserId() == null){
            return Collections.emptyList();
        }
        return baseMapper.getWatchLogList(param);
    }
}
