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.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.CompanyUser;
import com.fs.company.mapper.CompanyUserMapper;
import com.fs.course.domain.FsUserCourse;
import com.fs.course.domain.FsUserCourseVideo;
import com.fs.course.service.cache.IFsUserCourseVideoCacheService;
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.IFsUserCourseCacheService;
import com.github.pagehelper.PageInfo;
import com.hc.openapi.tool.util.StringUtils;
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 QwWatchLogMapper qwWatchLogMapper;

    @Autowired
    private CompanyUserMapper companyUserMapper;

    @Autowired
    private IFsUserCourseCacheService fsUserCourseCacheService;

    @Autowired
    private IFsUserCourseVideoCacheService fsUserCourseVideoCacheService;

    @Autowired
    private ICompanyCacheService companyCacheService;

    @Autowired
    private ICompanyUserCacheService companyUserCacheService;
    /**
     * 查询企微看课
     *
     * @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 TableDataInfo selectQwWatchLogStatisticsListVO(QwWatchLogStatisticsListParam param) {
        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());
        }

        Long total = qwWatchLogMapper.selectQwExtCountByDayAndCount(param);
        rspData.setRows(vos);
        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());

            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.getSTime(),param.getETime(),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.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.getSTime(), param.getETime(), 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 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());
            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());

            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.getSTime(), param.getETime(),
                        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());
                }
            }
            // 销售名称
            CompanyUser companyUser = companyUserCacheService.selectCompanyUserById(item.getCompanyUserId());

            item.setQwUserName(companyUser.getUserName());
            item.setCreateTime(companyUser.getCreateTime());
            list.add(item);
        }

        Long total = qwWatchLogMapper
                .selectQwWatchLogAllStatisticsListVONewCount(userIds, param.getSTime(), param.getETime(),
                        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 Long selectQwWatchLogStatisticsListVONewCount(QwWatchLogStatisticsListParam param) {

        return companyUserMapper.selectQwWatchLogStatisticsListVONewCount(param);
    }

    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;
    }
}
