package com.fs.qw.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.common.utils.DateUtils;
import com.fs.course.mapper.FsCourseWatchLogMapper;
import com.fs.course.mapper.FsUserCourseVideoMapper;
import com.fs.course.vo.FsCourseWatchLogTaskVO;
import com.fs.course.vo.FsQwCourseWatchLogVO;
import com.fs.qw.domain.QwExternalContact;
import com.fs.qw.domain.QwUser;
import com.fs.qw.domain.QwWorkTask;
import com.fs.qw.mapper.QwExternalContactMapper;
import com.fs.qw.mapper.QwWorkTaskMapper;
import com.fs.qw.param.QwWorkTaskListParam;
import com.fs.qw.service.IQwWorkTaskService;
import com.fs.qw.vo.QwWorkTaskAllListVO;
import com.fs.qw.vo.QwWorkTaskListVO;
import com.fs.sop.domain.QwSop;
import com.fs.sop.domain.SopUserLogsInfo;
import com.fs.sop.mapper.QwSopMapper;
import com.fs.sop.mapper.SopUserLogsInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 企微任务看板Service业务层处理
 *
 * @author fs
 * @date 2025-03-18
 */
@Service
public class QwWorkTaskServiceImpl extends ServiceImpl<QwWorkTaskMapper, QwWorkTask> implements IQwWorkTaskService {
    @Autowired
    private QwWorkTaskMapper qwWorkTaskMapper;
    @Autowired
    private FsUserCourseVideoMapper fsUserCourseVideoMapper;

    @Autowired
    private FsCourseWatchLogMapper fsCourseWatchLogMapper;
    @Autowired
    private QwSopMapper qwSopMapper;
    @Autowired
    SopUserLogsInfoMapper sopUserLogsInfoMapper;
    @Autowired
    QwExternalContactMapper qwExternalContactMapper;
    /**
     * 查询企微任务看板
     *
     * @param id 企微任务看板主键
     * @return 企微任务看板
     */
    @Override
    public QwWorkTask selectQwWorkTaskById(Long id)
    {
        return baseMapper.selectQwWorkTaskById(id);
    }

    /**
     * 查询企微任务看板列表
     *
     * @param qwWorkTask 企微任务看板
     * @return 企微任务看板
     */
    @Override
    public List<QwWorkTask> selectQwWorkTaskList(QwWorkTask qwWorkTask)
    {
        return baseMapper.selectQwWorkTaskList(qwWorkTask);
    }

    /**
     * 新增企微任务看板
     *
     * @param qwWorkTask 企微任务看板
     * @return 结果
     */
    @Override
    public int insertQwWorkTask(QwWorkTask qwWorkTask)
    {
        qwWorkTask.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insertQwWorkTask(qwWorkTask);
    }

    /**
     * 修改企微任务看板
     *
     * @param qwWorkTask 企微任务看板
     * @return 结果
     */
    @Override
    public int updateQwWorkTask(QwWorkTask qwWorkTask)
    {
        qwWorkTask.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateQwWorkTask(qwWorkTask);
    }

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

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

    @Override
    public void addQwWorkByFirstCourse() {
            List<FsQwCourseWatchLogVO> fsQwCourseWatchLogVOS = fsCourseWatchLogMapper.selectFsCourseWatchLogByVideoId();
        ArrayList<QwWorkTask> qwWorkTasks = new ArrayList<>();
        for (FsQwCourseWatchLogVO vo : fsQwCourseWatchLogVOS) {
                QwWorkTask qwWorkTask = new QwWorkTask();
                qwWorkTask.setCreateTime(DateUtils.getNowDate());
                qwWorkTask.setExtId(vo.getQwExternalContactId());
                qwWorkTask.setCompanyId(vo.getCompanyId());
                qwWorkTask.setCompanyUserId(vo.getCompanyUserId());
                qwWorkTask.setQwUserId(Long.parseLong(vo.getQwUserId()));
                qwWorkTask.setType(1);
                qwWorkTask.setStatus(0);
                qwWorkTask.setTitle(vo.getLogType()==3?"先导课待看课":"先导课完课");
                qwWorkTask.setScore(vo.getLogType()==3?4:3);
                qwWorkTasks.add(qwWorkTask);
            }
        if (!qwWorkTasks.isEmpty()) {
            qwWorkTaskMapper.insertQwWorkTaskBatch(qwWorkTasks);
        }

    }
    Integer getQwWorkCourseScore(Integer type, Integer day,Integer leve){

            switch (day){
                case 0:
                   return type == 3 ? 12 : 11;
                case 1:
                case 2:
                    return type == 3 ? 9 : 8;
                case 3:
                case 4:
                case 5:
                case 6:
                    return type == 3 ? 3 : 2;
                default:

                    return leve==null?0: leve==1?5:leve==2?3:leve==3?1:0;
            }


    }
    @Autowired
    FsCourseWatchLogMapper courseWatchLogMapper;

    //
    @Override
    public void addQwWorkByCourse() {
        List<QwSop> qwSops = qwSopMapper.selectQwSopByIsRating();
        LocalDate today = LocalDate.now();
        for (QwSop qwSop : qwSops) {
            List<SopUserLogsInfo> qwSopLogs = sopUserLogsInfoMapper.selectSopUserLogsInfoBySopId(qwSop.getId());
            if (qwSopLogs==null || qwSopLogs.isEmpty()) {
                continue;
            }

            List<FsCourseWatchLogTaskVO> fsCourseWatchLogs = courseWatchLogMapper.selectFsCourseWatchLogByDaySopId3(qwSop.getId());
            if (fsCourseWatchLogs==null || fsCourseWatchLogs.isEmpty()) {
                continue;
            }
            List<QwWorkTask> qwWorkTasks = new ArrayList<>();
            for (SopUserLogsInfo qwSopLog : qwSopLogs) {
                Map<Long, FsCourseWatchLogTaskVO> map = fsCourseWatchLogs.stream()
                        .collect(Collectors.toMap(FsCourseWatchLogTaskVO::getQwExternalContactId, data -> data,(oldValue, newValue) -> newValue ));
                FsCourseWatchLogTaskVO fsCourseWatchLog = map.get(qwSopLog.getExternalId());
                if (fsCourseWatchLog == null) {
                    continue;
                }
                String createTime = qwSopLog.getCreateTime();
                LocalDate createDate = LocalDate.parse(createTime.substring(0, 10), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                // 计算两个日期之间的天数差
                Integer day = Math.toIntExact(ChronoUnit.DAYS.between(createDate, today));
                Integer score = getQwWorkCourseScore(fsCourseWatchLog.getLogType(), day,fsCourseWatchLog.getLevel());
                if (score==0){
                    continue;
                }
                QwWorkTask qwWorkTask = new QwWorkTask();
                qwWorkTask.setCreateTime(DateUtils.getNowDate());
                qwWorkTask.setExtId(fsCourseWatchLog.getQwExternalContactId());
                qwWorkTask.setCompanyId(fsCourseWatchLog.getCompanyId());
                qwWorkTask.setCompanyUserId(fsCourseWatchLog.getCompanyUserId());
                qwWorkTask.setSopId(qwSop.getId());
                qwWorkTask.setQwUserId(fsCourseWatchLog.getQwUserId());
                qwWorkTask.setType(2);
                qwWorkTask.setStatus(0);
                qwWorkTask.setTitle("第"+(day+1)+"天"+"待看课");
                qwWorkTask.setScore(score);
                qwWorkTasks.add(qwWorkTask);
            }
            if (!qwWorkTasks.isEmpty()){
                qwWorkTaskMapper.insertQwWorkTaskBatch(qwWorkTasks);
            }

        }
    }



    @Override
    public void addQwWorkByConversionDay() {
        List<QwSop> qwSops = qwSopMapper.selectQwSopByIsRatingNotNull();
        Map<Integer, Integer> minMap = new HashMap<>();
        minMap.put(1, 10);
        minMap.put(2, 6);
        minMap.put(3, 2);
        Map<Integer, Integer> MaxMap = new HashMap<>();
        MaxMap.put(1, 25);
        MaxMap.put(2, 15);
        MaxMap.put(3, 5);
        for (QwSop qwSop : qwSops) {
            Integer min= qwSop.getMinConversionDay();
            Integer max = qwSop.getMaxConversionDay();
            LocalDate today = LocalDate.now();
            addQwWorkTask(today, min, qwSop, "用户小转",minMap);
            addQwWorkTask(today, max, qwSop, "用户大转",MaxMap);
        }
    }

    @Override
    public List<QwWorkTaskListVO> selectQwWorkTaskListVO(QwWorkTaskListParam qwWorkTask) {
        return qwWorkTaskMapper.selectQwWorkTaskListVO(qwWorkTask);
    }

    @Override
    public void addQwWorkByCourse4() {
        List<QwSop> qwSops = qwSopMapper.selectQwSopByIsRating();
        List<Long> extIds = qwWorkTaskMapper.selectQwWorkTaskByType();
        Set<Long> extIdSet = new HashSet<>(extIds);
        LocalDate today = LocalDate.now();
        for (QwSop qwSop : qwSops) {
            List<SopUserLogsInfo> qwSopLogs = sopUserLogsInfoMapper.selectSopUserLogsInfoBySopId(qwSop.getId());
            if (qwSopLogs==null || qwSopLogs.isEmpty()) {
                continue;
            }
            List<FsCourseWatchLogTaskVO> fsCourseWatchLogs = courseWatchLogMapper.selectFsCourseWatchLogByDaySopId4(qwSop.getId());
            if (fsCourseWatchLogs==null || fsCourseWatchLogs.isEmpty()) {
                continue;
            }
            List<QwWorkTask> qwWorkTasks = new ArrayList<>();
            for (SopUserLogsInfo qwSopLog : qwSopLogs) {
                Map<Long, FsCourseWatchLogTaskVO> map = fsCourseWatchLogs.stream()
                        .collect(Collectors.toMap(FsCourseWatchLogTaskVO::getQwExternalContactId, data -> data,(oldValue, newValue) -> newValue ));
                FsCourseWatchLogTaskVO fsCourseWatchLog = map.get(qwSopLog.getExternalId());
                if (fsCourseWatchLog == null) {
                    continue;
                }
                if (extIdSet.contains(fsCourseWatchLog.getQwExternalContactId())) {
                    continue;
                }
                String createTime = qwSopLog.getCreateTime();
                LocalDate createDate = LocalDate.parse(createTime.substring(0, 10), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                Integer day = Math.toIntExact(ChronoUnit.DAYS.between(createDate, today));
                if (day>6){
                    continue;
                }
                Integer score = getQwWorkCourseScore(fsCourseWatchLog.getLogType(), day,fsCourseWatchLog.getLevel());
                if (score==0){
                    continue;
                }
                QwWorkTask qwWorkTask = new QwWorkTask();
                qwWorkTask.setCreateTime(DateUtils.getNowDate());
                qwWorkTask.setExtId(fsCourseWatchLog.getQwExternalContactId());
                qwWorkTask.setCompanyId(fsCourseWatchLog.getCompanyId());
                qwWorkTask.setCompanyUserId(fsCourseWatchLog.getCompanyUserId());
                qwWorkTask.setSopId(qwSop.getId());
                qwWorkTask.setQwUserId(fsCourseWatchLog.getQwUserId());
                qwWorkTask.setType(2);
                qwWorkTask.setStatus(0);
                qwWorkTask.setTitle("第"+(day+1)+"天"+"看课中断");
                qwWorkTask.setScore(score);
                qwWorkTasks.add(qwWorkTask);
            }
            if (!qwWorkTasks.isEmpty()){
                qwWorkTaskMapper.insertQwWorkTaskBatch(qwWorkTasks);
            }

        }
    }

    @Override
    public void delQwWorkTaskByOver() {
        List<Long> longs = fsCourseWatchLogMapper.selectFsCourseWatchLogByFinish();

        List<QwWorkTask> qwWorkTasks = qwWorkTaskMapper.selectQwWorkTaskByTypeStatus();

        Set<Long> targetIds = new HashSet<>(longs);

        List<Long> overIds = qwWorkTasks.stream()
                .map(QwWorkTask::getId)
                .filter(targetIds::contains)
                .collect(Collectors.toList());
        if (overIds.isEmpty()){
            return;
        }
        qwWorkTaskMapper.updateQwWorkTaskStatus(overIds);

    }

    @Override
    public void addQwWorkByCourseLastTime() {
        List<QwSop> qwSops = qwSopMapper.selectQwSopByIsRating();
        List<Long> extIds = qwWorkTaskMapper.selectQwWorkTaskByType();
        SimpleDateFormat sdf = new SimpleDateFormat("HHmm"); // 24小时制，如 1100
        String timeStr = sdf.format(new Date());
        int lastTime = Integer.parseInt(timeStr);
        Set<Long> extIdSet = new HashSet<>(extIds);
        LocalDate today = LocalDate.now();
        for (QwSop qwSop : qwSops) {
            if (qwSop.getCourseDay()==null){
                continue;
            }
            Integer courseDay=qwSop.getCourseDay()-1;
            List<SopUserLogsInfo> qwSopLogs = sopUserLogsInfoMapper.selectSopUserLogsInfoBySopId(qwSop.getId());
            if (qwSopLogs==null || qwSopLogs.isEmpty()) {
                continue;
            }

            List<FsCourseWatchLogTaskVO> fsCourseWatchLogs = courseWatchLogMapper.selectFsCourseWatchLogByDaySopId3LastTime(qwSop.getId(),lastTime);
            if (fsCourseWatchLogs==null || fsCourseWatchLogs.isEmpty()) {
                continue;
            }
            List<QwWorkTask> qwWorkTasks = new ArrayList<>();
            for (SopUserLogsInfo qwSopLog : qwSopLogs) {
                Map<Long, FsCourseWatchLogTaskVO> map = fsCourseWatchLogs.stream()
                        .collect(Collectors.toMap(FsCourseWatchLogTaskVO::getQwExternalContactId, data -> data,(oldValue, newValue) -> newValue ));
                FsCourseWatchLogTaskVO fsCourseWatchLog = map.get(qwSopLog.getExternalId());

                if (fsCourseWatchLog == null) {
                    continue;
                }
                if (extIdSet.contains(fsCourseWatchLog.getQwExternalContactId())) {
                    continue;
                }
                String createTime = qwSopLog.getCreateTime();
                LocalDate createDate = LocalDate.parse(createTime.substring(0, 10), DateTimeFormatter.ofPattern("yyyy-MM-dd"));

                Integer day = (Math.toIntExact(ChronoUnit.DAYS.between(createDate, today))) + 1 - courseDay;
                if (day<=7){
                    continue;
                }
                Integer score = getQwWorkCourseScore(fsCourseWatchLog.getLogType(), day,fsCourseWatchLog.getLevel());
                if (score==0){
                    continue;
                }
                QwWorkTask qwWorkTask = new QwWorkTask();
                qwWorkTask.setCreateTime(DateUtils.getNowDate());
                qwWorkTask.setExtId(fsCourseWatchLog.getQwExternalContactId());
                qwWorkTask.setCompanyId(fsCourseWatchLog.getCompanyId());
                qwWorkTask.setCompanyUserId(fsCourseWatchLog.getCompanyUserId());
                qwWorkTask.setSopId(qwSop.getId());
                qwWorkTask.setQwUserId(fsCourseWatchLog.getQwUserId());
                qwWorkTask.setType(2);
                qwWorkTask.setStatus(0);
                qwWorkTask.setTitle("第"+day+"天"+"待看课");
                qwWorkTask.setScore(score);
                qwWorkTasks.add(qwWorkTask);

            }
            if (!qwWorkTasks.isEmpty()){

                qwWorkTaskMapper.insertQwWorkTaskBatch(qwWorkTasks);
            }

        }
    }
    @Override
    public void addQwWorkByAiNotifyArtificial(QwUser user, Long extId, String content) {
        QwWorkTask qwWorkTask = new QwWorkTask();
        qwWorkTask.setStatus(0);
        qwWorkTask.setExtId(extId);
        qwWorkTask.setTitle(content);
        qwWorkTask.setType(4);
        qwWorkTask.setScore(50);
        qwWorkTask.setCompanyUserId(user.getCompanyUserId());
        qwWorkTask.setCompanyId(user.getCompanyId());
        qwWorkTask.setQwUserId(user.getId());
        qwWorkTask.setCreateTime(DateUtils.getNowDate());
        qwWorkTaskMapper.insertQwWorkTask(qwWorkTask);
    }

    @Override
    public List<QwWorkTask> selectQwWorkTaskListByMap(Map<String, Object> params) {
        return qwWorkTaskMapper.selectQwWorkTaskListByMap(params);
    }

    @Override
    public List<QwWorkTaskAllListVO> selectQwWorkTaskAllListVO(QwWorkTaskListParam qwWorkTask) {
        return qwWorkTaskMapper.selectQwWorkTaskAllListVO(qwWorkTask);
    }

    private void addQwWorkTask(LocalDate today, Integer day, QwSop qwSop, String title,Map<Integer, Integer> map) {
        if (day>7){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String minDay = today.minusDays(day).format(formatter);
            List<SopUserLogsInfo> qwSopLogs = sopUserLogsInfoMapper.selectDayBySopId(qwSop.getId(), minDay);
            for (SopUserLogsInfo qwSopLog : qwSopLogs) {
                QwExternalContact qwExternalContact = qwExternalContactMapper.selectQwExternalContactById(qwSopLog.getExternalId());
                if (qwExternalContact==null){
                    continue;
                }
                if (qwExternalContact.getLevel()==null||qwExternalContact.getLevel()==4||qwExternalContact.getLevel()==0){
                    continue;
                }
                System.out.println(qwExternalContact.getId()+"ok");


                insertQwWorkTask(qwSopLog.getId(),qwExternalContact,3,title,map.getOrDefault(qwExternalContact.getLevel(), 0));
            }
        }
    }


    private void insertQwWorkTask(String sopId,QwExternalContact qwExternalContact, Integer type, String title, Integer score) {
        QwWorkTask qwWorkTask = new QwWorkTask();
        qwWorkTask.setCreateTime(DateUtils.getNowDate());
        qwWorkTask.setExtId(qwExternalContact.getId());
        qwWorkTask.setCompanyId(qwExternalContact.getCompanyId());
        qwWorkTask.setCompanyUserId(qwExternalContact.getCompanyUserId());
        qwWorkTask.setQwUserId(qwExternalContact.getQwUserId());
        qwWorkTask.setSopId(sopId);
        qwWorkTask.setType(type);
        qwWorkTask.setStatus(0);
        qwWorkTask.setTitle(title);
        qwWorkTask.setScore(score);
        baseMapper.insertQwWorkTask(qwWorkTask);
    }


}
