package com.fs.qw.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.common.constant.HttpStatus;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.DictUtils;
import com.fs.company.cache.ICompanyCacheService;
import com.fs.company.cache.ICompanyUserCacheService;
import com.fs.company.domain.Company;
import com.fs.company.domain.CompanyDept;
import com.fs.company.domain.CompanyUser;
import com.fs.company.mapper.CompanyDeptMapper;
import com.fs.company.mapper.CompanyUserMapper;
import com.fs.course.domain.FsUserCourse;
import com.fs.course.domain.FsUserCourseVideo;
import com.fs.course.param.FsCourseWatchLogListParam;
import com.fs.course.service.cache.IFsUserCourseVideoCacheService;
import com.fs.his.domain.FsUser;
import com.fs.qw.domain.QwWatchLog;
import com.fs.qw.mapper.QwExternalContactMapper;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.qw.mapper.QwWatchLogMapper;
import com.fs.qw.param.QwWatchLogStatisticsListParam;
import com.fs.qw.service.IQwWatchLogService;
import com.fs.qw.vo.QwWatchLogAllStatisticsListVO;
import com.fs.qw.vo.QwWatchLogStatisticsListVO;
import com.fs.store.service.cache.IFsUserCacheService;
import com.fs.store.service.cache.IFsUserCourseCacheService;
import com.hc.openapi.tool.util.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 企微看课Service业务层处理
 *
 * @author fs
 * @date 2025-03-08
 */
@Service
public class QwWatchLogServiceImpl extends ServiceImpl<QwWatchLogMapper, QwWatchLog> implements IQwWatchLogService {
    @Autowired
    private QwUserMapper qwUserMapper;
    @Autowired
    private QwWatchLogMapper qwWatchLogMapper;
    @Autowired
    private QwExternalContactMapper qwExternalContactMapper;
    @Autowired
    private CompanyUserMapper companyUserMapper;

    @Autowired
    private CompanyDeptMapper companyDeptMapper;

    @Autowired
    private IFsUserCourseCacheService fsUserCourseCacheService;

    @Autowired
    private IFsUserCourseVideoCacheService fsUserCourseVideoCacheService;

    @Autowired
    private ICompanyCacheService companyCacheService;

    @Autowired
    private ICompanyUserCacheService companyUserCacheService;
    @Autowired
    private IFsUserCacheService fsUserCacheService;


    /**
     * 查询企微看课
     *
     * @param id 企微看课主键
     * @return 企微看课
     */
    @Override
    public QwWatchLog selectQwWatchLogById(Long id)
    {
        return baseMapper.selectQwWatchLogById(id);
    }

    /**
     * 查询企微看课列表
     *
     * @param qwWatchLog 企微看课
     * @return 企微看课
     */
    @Override
    public List<QwWatchLog> selectQwWatchLogList(QwWatchLog qwWatchLog)
    {
        return baseMapper.selectQwWatchLogList(qwWatchLog);
    }

    /**
     * 新增企微看课
     *
     * @param qwWatchLog 企微看课
     * @return 结果
     */
    @Override
    public int insertQwWatchLog(QwWatchLog qwWatchLog)
    {
        qwWatchLog.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insertQwWatchLog(qwWatchLog);
    }

    /**
     * 修改企微看课
     *
     * @param qwWatchLog 企微看课
     * @return 结果
     */
    @Override
    public int updateQwWatchLog(QwWatchLog qwWatchLog)
    {
        return baseMapper.updateQwWatchLog(qwWatchLog);
    }

    /**
     * 批量删除企微看课
     *
     * @param ids 需要删除的企微看课主键
     * @return 结果
     */
    @Override
    public int deleteQwWatchLogByIds(Long[] ids)
    {
        return baseMapper.deleteQwWatchLogByIds(ids);
    }

    /**
     * 删除企微看课信息
     *
     * @param id 企微看课主键
     * @return 结果
     */
    @Override
    public int deleteQwWatchLogById(Long id)
    {
        return baseMapper.deleteQwWatchLogById(id);
    }


    @Override
    public List<QwWatchLogStatisticsListVO> selectQwWatchLogStatisticsListVOExport(FsCourseWatchLogListParam param) {
        List<Long> deptIds = param.getDeptIds();
        List<Long> allDeptIds = getAllDeptIds(deptIds);
        if (allDeptIds == null){
            param.setDeptId(null);
            param.setDeptIds(null);
        } else if (!allDeptIds.isEmpty()){
            param.setDeptIds(allDeptIds);
            param.setDeptId(null);
        } else {
            CompanyDept companyDept = companyDeptMapper.selectCompanyDeptById(param.getDeptId());
            if (ObjectUtils.isNotEmpty(companyDept)&&companyDept.getParentId()==0L){
                param.setDeptId(null);
            }
        }


        if (param.getCompanyUserId()!=null){
            param.setIds(companyUserMapper.selectQwUserIdsByCompany(param.getCompanyUserId()));
        }
        List<QwWatchLogStatisticsListVO> vos = qwWatchLogMapper.selectQwExtCountByDayAndOther(param);
        for (QwWatchLogStatisticsListVO vo : vos) {
            Long id = vo.getId();
            Date createTime = vo.getCreateTime();
            QwWatchLogStatisticsListVO stat = qwWatchLogMapper.selectQwWatchLogByQwUserId(id, createTime);
            vo.setD1Online(stat.getD1Online());
            vo.setD1Over(stat.getD1Over());
            vo.setFirstOnline(stat.getFirstOnline());
            vo.setFirstOver(stat.getFirstOver());
        }
        return vos;
    }
    @Override
    public List<QwWatchLogStatisticsListVO> selectQwWatchLogStatisticsListVOExportExcludeTransfer(FsCourseWatchLogListParam param) {
        List<Long> deptIds = param.getDeptIds();
        if (deptIds !=null && !deptIds.isEmpty()){
            List<CompanyDept> companyDeptList  = companyDeptMapper.selectCompanyDeptByIds(deptIds);
            if (companyDeptList!=null && !companyDeptList.isEmpty()){
                for (CompanyDept c : companyDeptList) {
                    if (c.getParentId() == 0L) {
                        param.setDeptId(null);
                        param.setDeptIds(null);
                        break;
                    }
                }
            }
        } else {
            CompanyDept companyDept = companyDeptMapper.selectCompanyDeptById(param.getDeptId());
            if (ObjectUtils.isNotEmpty(companyDept)&&companyDept.getParentId()==0L){
                param.setDeptId(null);
            }
        }


        if (param.getCompanyUserId()!=null){
            param.setIds(companyUserMapper.selectQwUserIdsByCompany(param.getCompanyUserId()));
        }
//        List<QwWatchLogStatisticsListVO> vos = qwWatchLogMapper.selectQwExtCountByDayAndOther(param);
        List<QwWatchLogStatisticsListVO> vos = qwWatchLogMapper.selectQwExtCountByDayAndOtherExcludeTransfer(param);
        for (QwWatchLogStatisticsListVO vo : vos) {
            Long id = vo.getId();
            Date createTime = vo.getCreateTime();
            QwWatchLogStatisticsListVO stat = qwWatchLogMapper.selectQwWatchLogByQwUserId(id, createTime);
            vo.setD1Online(stat.getD1Online());
            vo.setD1Over(stat.getD1Over());
            vo.setFirstOnline(stat.getFirstOnline());
            vo.setFirstOver(stat.getFirstOver());
        }
        return vos;
    }

    @Override
    public TableDataInfo selectQwWatchLogStatisticsListVO(QwWatchLogStatisticsListParam param) {
        List<Long> deptIds = param.getDeptIds();
        List<Long> allDeptIds = getAllDeptIds(deptIds);
        if (allDeptIds == null){
            param.setDeptId(null);
            param.setDeptIds(null);
        } else if (!allDeptIds.isEmpty()){
            param.setDeptIds(allDeptIds);
            param.setDeptId(null);
        } else {
            CompanyDept companyDept = companyDeptMapper.selectCompanyDeptById(param.getDeptId());
            if (ObjectUtils.isNotEmpty(companyDept)&&companyDept.getParentId()==0L){
                param.setDeptId(null);
            }
        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(new ArrayList<>());
        rspData.setTotal(0L);

        Date sTime = param.getSTime();
        Date eTime = param.getETime();
        List<Date> datesBetween = getDatesBetween(sTime, eTime);
        if (datesBetween.size() > 7) {
            return rspData;
        }
        if (param.getCompanyUserId()!=null){
            param.setIds(companyUserMapper.selectQwUserIdsByCompany(param.getCompanyUserId()));
        }
        List<QwWatchLogStatisticsListVO> vos = qwWatchLogMapper.selectQwExtCountByDayAnd(param);
        for (QwWatchLogStatisticsListVO vo : vos) {
            Long id = vo.getId();
            Date createTime = vo.getCreateTime();
            QwWatchLogStatisticsListVO stat = qwWatchLogMapper.selectQwWatchLogByQwUserId(id, createTime);
            vo.setD1Online(stat.getD1Online());
            vo.setD1Over(stat.getD1Over());
            vo.setFirstOnline(stat.getFirstOnline());
            vo.setFirstOver(stat.getFirstOver());
        }
        if (StringUtils.isNotBlank(param.getIds())) {
            String replace = param.getIds().replace("(", "").replace(")", "");
            param.setIdsList(Arrays.asList(replace.split(",")));
        }
        Long total = qwWatchLogMapper.selectQwExtCountByDayAndCount(param);
        rspData.setRows(vos);
        rspData.setTotal(total);
        return rspData;
    }

    /**
     * 根据部门id查询所有子部门
     * @param deptIds
     * @return
     */
    private @Nullable List<Long> getAllDeptIds( List<Long> deptIds) {
        List<Long> allDeptIds = new ArrayList<>();
        if (deptIds == null || deptIds.isEmpty()){
            return allDeptIds;
        } else {
            allDeptIds.addAll(deptIds);
        }
        while (true){
            if (deptIds.isEmpty()){
                break;
            }
            List<CompanyDept> companyDeptList  = companyDeptMapper.selectCompanyDeptByIds(deptIds);
            if (companyDeptList.isEmpty()){
               break;
            }
            deptIds = new ArrayList<>();
            for (CompanyDept c : companyDeptList) {
                List<Long> ids = companyDeptMapper.selectCompanyDeptByParentId(c.getDeptId());
                allDeptIds.addAll(ids);
                deptIds.addAll(ids);
                if (c.getParentId() == 0L) {
                    return null;
                }
            }
        }
        return allDeptIds;
    }

    /**
     * 查询进线统计，排除掉转接的数据
     * @param param
     * @return
     */
    @Override
    public TableDataInfo selectQwWatchLogStatisticsListVOExcludeTransfer(QwWatchLogStatisticsListParam param){
//        CompanyDept companyDept = companyDeptMapper.selectCompanyDeptById(param.getDeptId());
//        if (ObjectUtils.isNotEmpty(companyDept)&&companyDept.getParentId()==0L){
//            param.setDeptId(null);
//        }else {
//            //通过部门id去找到所有子部门id
//            List<Long> currentDeptIdDownTreeIds = companyDeptMapper.getCurrentDeptIdDownTreeIds(param.getDeptId());
//            param.setFilterDeptIds(currentDeptIdDownTreeIds);
//            param.setDeptId(null);
//        }
        List<Long> deptIds = param.getDeptIds();
        if (deptIds !=null && !deptIds.isEmpty()){
            List<CompanyDept> companyDeptList  = companyDeptMapper.selectCompanyDeptByIds(deptIds);
            if (companyDeptList!=null && !companyDeptList.isEmpty()){
                for (CompanyDept c : companyDeptList) {
                    if (c.getParentId() == 0L) {
                        param.setDeptId(null);
                        param.setDeptIds(null);
                        break;
                    }
                }
            }
        } else {
            CompanyDept companyDept = companyDeptMapper.selectCompanyDeptById(param.getDeptId());
            if (ObjectUtils.isNotEmpty(companyDept)&&companyDept.getParentId()==0L){
                param.setDeptId(null);
            }
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(new ArrayList<>());
        rspData.setTotal(0L);

        Date sTime = param.getSTime();
        Date eTime = param.getETime();
        List<Date> datesBetween = getDatesBetween(sTime, eTime);
        if (datesBetween.size() > 7) {
            return rspData;
        }
        if (param.getCompanyUserId()!=null){
            param.setIds(companyUserMapper.selectQwUserIdsByCompany(param.getCompanyUserId()));
        }
        List<QwWatchLogStatisticsListVO> vos = qwWatchLogMapper.selectQwExtCountByDayAndExcludeTransfer(param);
        for (QwWatchLogStatisticsListVO vo : vos) {
            Long id = vo.getId();
            Date createTime = vo.getCreateTime();
            QwWatchLogStatisticsListVO stat = qwWatchLogMapper.selectQwWatchLogByQwUserId(id, createTime);
            vo.setD1Online(stat.getD1Online());
            vo.setD1Over(stat.getD1Over());
            vo.setFirstOnline(stat.getFirstOnline());
            vo.setFirstOver(stat.getFirstOver());
        }
        if (StringUtils.isNotBlank(param.getIds())) {
            String replace = param.getIds().replace("(", "").replace(")", "");
            param.setIdsList(Arrays.asList(replace.split(",")));
        }
        Long total = qwWatchLogMapper.selectQwExtCountByDayAndCount(param);
        rspData.setRows(vos);
        rspData.setTotal(total);
        return rspData;
    }
    @Override
    public List<QwWatchLogAllStatisticsListVO> selectQwWatchLogAllStatisticsListVO(QwWatchLogStatisticsListParam param) {
        Date sTime = param.getSTime();
        Date eTime = param.getETime();
        List<Date> datesBetween = getDatesBetween(sTime, eTime);
        if (datesBetween.size() > 7) {
            return new ArrayList<>();
        }
        if (param.getCompanyUserId()!=null){
            param.setIds(companyUserMapper.selectQwUserIdsByCompany(param.getCompanyUserId()));
        }
        ArrayList<QwWatchLogAllStatisticsListVO> list = new ArrayList<>();
        List<QwWatchLogAllStatisticsListVO> vos = qwWatchLogMapper.selectQwExtCountByDayAndLine(param);
        for (QwWatchLogAllStatisticsListVO vo : vos) {
            Long id = vo.getId();
            Date createTime = vo.getCreateTime();
            QwWatchLogAllStatisticsListVO stat = qwWatchLogMapper.selectQwWatchLogAllStatisticsListVO(id, createTime);
            stat.setCreateTime(vo.getCreateTime());
            stat.setQwUserName(vo.getQwUserName());
            stat.setLine(vo.getLine());
            stat.setRegNum(vo.getRegNum());
            list.add(stat);
        }

        return list;
    }

    @Override
    public TableDataInfo selectQwWatchLogAllStatisticsListVONew(QwWatchLogStatisticsListParam param) {
        // 获取当前公司下的所有销售
        List<Long> userIds;
        if(param.getCompanyUserId()  == null){
            List<CompanyUser> companyUsers = companyUserMapper.selectCompanyUserByCompanyId(param.getCompanyId());
            if(CollectionUtils.isEmpty(companyUsers)){
                throw new CustomException("该公司下面没有任何销售！");
            }
            userIds = companyUsers.stream()
                    .map(CompanyUser::getUserId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
        } else {
            userIds = new ArrayList<>();
            userIds.add(param.getCompanyUserId());
        }

        List<QwWatchLogAllStatisticsListVO> list = new ArrayList<>();

        List<QwWatchLogAllStatisticsListVO> vos = qwWatchLogMapper
                .selectQwWatchLogAllStatisticsListVONew(userIds, param.getStartDate(), param.getEndDate(),
                        param.getProject(),param.getCourseId(),param.getVideoId()
                );
        for (QwWatchLogAllStatisticsListVO item : vos) {
            if(ObjectUtils.isNotNull(item.getProject())){
                String sysCourseProject = DictUtils.getDictLabel("sys_course_project", String.valueOf(item.getProject()));
                if(StringUtils.isNotBlank(sysCourseProject)){
                    item.setProjectName(sysCourseProject);
                }
            }
            // 课程名
            if(ObjectUtils.isNotNull(item.getCourseId())) {
                FsUserCourse course = fsUserCourseCacheService.selectFsUserCourseByCourseId(item.getCourseId());
                if(ObjectUtils.isNotNull(course)){
                    item.setCourseName(course.getCourseName());
                }
            }
            // 小节名
            if(ObjectUtils.isNotNull(item.getVideoId())) {
                FsUserCourseVideo fsUserCourseVideo = fsUserCourseVideoCacheService.selectFsUserCourseVideoByVideoId(item.getVideoId());
                if(ObjectUtils.isNotNull(fsUserCourseVideo)){
                    item.setVideoName(fsUserCourseVideo.getTitle());
                }
            }
            // 销售名称
            if(ObjectUtils.isNotNull(item.getCompanyUserId())){
                CompanyUser companyUser = companyUserCacheService.selectCompanyUserById(item.getCompanyUserId());
                if(companyUser != null) {
                    item.setQwUserName(companyUser.getUserName());
                }
            }
            // 会员名称
            if(ObjectUtils.isNotNull(item.getFsUserId())) {
                FsUser fsUser = fsUserCacheService.selectFsUserById(item.getFsUserId());
                if(fsUser != null) {
                    item.setFsUserName(String.format("%d_%s",fsUser.getUserId(),fsUser.getUsername()));
                }
            }

            list.add(item);
        }

        Long total = qwWatchLogMapper
                .selectQwWatchLogAllStatisticsListVONewCount(userIds, param.getStartDate(), param.getEndDate(),
                        param.getProject(),param.getCourseId(),param.getVideoId()
                );

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(total);

        return rspData;
    }

    @Override
    public TableDataInfo selectQwWatchLogStatisticsListVONew(QwWatchLogStatisticsListParam param) {
        List<Long> userIds = null;
        // 获取当前公司下的所有销售
        if(param.getCompanyUserId()  == null){
            List<CompanyUser> companyUsers = companyUserMapper.selectCompanyUserByCompanyId(param.getCompanyId());
            if(CollectionUtils.isEmpty(companyUsers)){
                throw new CustomException("该公司下面没有任何销售！");
            }
            userIds = companyUsers.stream()
                    .map(CompanyUser::getUserId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
        } else {
            userIds = new ArrayList<>();
            userIds.add(param.getCompanyUserId());
        }


        List<QwWatchLogStatisticsListVO> list = new ArrayList<>();

        // 统计销售下面的所有记录
        List<QwWatchLogStatisticsListVO> vos = qwWatchLogMapper
                .selectQwWatchLogByCompanyUserId(userIds
                        , param.getStartDate(),param.getEndDate(),param.getProject(),param.getCourseId(),param.getVideoId(),param.getPageNum(),param.getPageSize());

        for (QwWatchLogStatisticsListVO item : vos) {
            Company company = companyCacheService.selectCompanyById(item.getCompanyId());
            if(ObjectUtils.isNotNull(company)){
                item.setCompanyUserName(company.getCompanyName());
                item.setCreateTime(company.getCreateTime());
            }
            if(ObjectUtils.isNotNull(item.getCompanyUserId())) {
                CompanyUser companyUser = companyUserCacheService.selectCompanyUserById(item.getCompanyUserId());
                if(companyUser != null) {
                    item.setCompanyUserName(String.format("%d_%s",companyUser.getUserId(),companyUser.getUserName()));
                }
            }

            if(ObjectUtils.isNotNull(item.getProject())){
                String sysCourseProject = DictUtils.getDictLabel("sys_course_project", String.valueOf(item.getProject()));
                if(StringUtils.isNotBlank(sysCourseProject)){
                    item.setProjectName(sysCourseProject);
                }
            }
            // 课程名
            if(ObjectUtils.isNotNull(item.getCourseId())) {
                FsUserCourse course = fsUserCourseCacheService.selectFsUserCourseByCourseId(item.getCourseId());
                if(ObjectUtils.isNotNull(course)){
                    item.setCourseName(course.getCourseName());
                }
            }
            // 小节名
            if(ObjectUtils.isNotNull(item.getVideoId())) {
                FsUserCourseVideo fsUserCourseVideo = fsUserCourseVideoCacheService.selectFsUserCourseVideoByVideoId(item.getVideoId());
                if(ObjectUtils.isNotNull(fsUserCourseVideo)){
                    item.setVideoName(fsUserCourseVideo.getTitle());
                }
            }
            list.add(item);
        }

        // 获取总记录数
        Long total = qwWatchLogMapper
                .selectQwWatchLogByCompanyUserIdCount(userIds
                        , param.getStartDate(), param.getEndDate(), param.getProject(), param.getCourseId(), param.getVideoId());



        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(total);

        return rspData;
    }

    public List<Date> getDatesBetween(Date sTime, Date eTime) {
        List<Date> dates = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(sTime);

        while (!calendar.getTime().after(eTime)) { // 遍历直到结束时间
            dates.add(calendar.getTime()); // 添加当前日期
            calendar.add(Calendar.DAY_OF_MONTH, 1); // 增加一天
        }

        return dates;
    }
}
