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.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.course.domain.FsCourseWatchLog;
import com.fs.course.mapper.FsCourseWatchLogMapper;
import com.fs.course.vo.FsCourseWatchLogTaskVO;
import com.fs.course.vo.FsQwCourseWatchLogVO;
import com.fs.qw.domain.HyWorkTask;
import com.fs.qw.domain.QwExternalContact;
import com.fs.qw.domain.QwWorkTask;
import com.fs.qw.mapper.HyWorkTaskMapper;
import com.fs.qw.mapper.QwExternalContactMapper;
import com.fs.qw.param.QwWorkTaskListParam;
import com.fs.qw.service.IHyWorkTaskService;
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 com.hc.openapi.tool.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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
@Slf4j
public class HyWorkTaskServiceImpl extends ServiceImpl<HyWorkTaskMapper, HyWorkTask> implements IHyWorkTaskService {
    @Autowired
    private FsCourseWatchLogMapper fsCourseWatchLogMapper;
    @Autowired
    private QwSopMapper qwSopMapper;
    @Autowired
    private SopUserLogsInfoMapper sopUserLogsInfoMapper;
    @Autowired
    private QwExternalContactMapper qwExternalContactMapper;
    @Autowired
    private ICompanyCacheService companyCacheService;
    @Autowired
    private ICompanyUserCacheService companyUserCacheService;
    @Autowired
    private HyWorkTaskMapper hyWorkTaskMapper;

    /**
     * 查询企微任务看板
     *
     * @param id 企微任务看板主键
     * @return 企微任务看板
     */
    @Override
    public HyWorkTask selectHyWorkTaskById(Long id)
    {
        return baseMapper.selectHyWorkTaskById(id);
    }

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

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

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

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

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

    @Override
    public void addHyWorkByFirstCourse() {
            List<FsQwCourseWatchLogVO> fsQwCourseWatchLogVOS = fsCourseWatchLogMapper.selectFsCourseWatchLogByVideoId();
        ArrayList<HyWorkTask> qwWorkTasks = new ArrayList<>();
        for (FsQwCourseWatchLogVO vo : fsQwCourseWatchLogVOS) {
                HyWorkTask qwWorkTask = new HyWorkTask();
                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()) {
            hyWorkTaskMapper.insertQwWorkTaskBatch(qwWorkTasks);
        }

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

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

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


    }

    @Override
    public void addHyWorkByCourse() {
        List<QwSop> qwSops = qwSopMapper.selectQwSopByIsRating();
        LocalDate today = LocalDate.now();
        List<Long> extIds = hyWorkTaskMapper.selectHyWorkTaskByType();
        Set<Long> extIdSet = new HashSet<>(extIds);
        // 获取出执行sop的记录数
        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;
            }
            // 每次sop的观看记录
            List<FsCourseWatchLogTaskVO> fsCourseWatchLogs = fsCourseWatchLogMapper.selectFsCourseWatchLogByDaySopId3(qwSop.getId());
            if (fsCourseWatchLogs==null || fsCourseWatchLogs.isEmpty()) {
                continue;
            }
            List<HyWorkTask> 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;
                Integer score = getHyWorkCourseScore(fsCourseWatchLog.getLogType(), day,fsCourseWatchLog.getLevel());
                if (score==0){
                    continue;
                }
                HyWorkTask qwWorkTask = new HyWorkTask();
                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()){
                hyWorkTaskMapper.insertQwWorkTaskBatch(qwWorkTasks);
            }

        }
    }



    @Override
    public void addHyWorkByConversionDay() {
        List<QwSop> qwSops = qwSopMapper.selectQwSopByIsRatingNotNull();
        Map<Integer, Integer> minMap = new HashMap<>();
        // level->分值映射
        minMap.put(1, 10);
        minMap.put(2, 6);
        minMap.put(3, 2);
        Map<Integer, Integer> MaxMap = new HashMap<>();
        // level->分值映射
        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();
            addHyWorkTask(today, min, qwSop, "用户小转",minMap);
            addHyWorkTask(today, max, qwSop, "用户大转",MaxMap);
        }
    }

    @Override
    public List<QwWorkTaskListVO> selectHyWorkTaskListVONew(QwWorkTaskListParam qwWorkTask) {
        List<QwWorkTaskListVO> list = hyWorkTaskMapper.selectHyWorkTaskListVONew(qwWorkTask);
        for (QwWorkTaskListVO item : list) {
            if(ObjectUtils.isNotNull(item.getCompanyId())){
                Company company = companyCacheService.selectCompanyById(item.getCompanyId());
                if(ObjectUtils.isNotNull(company)){
                    item.setCompanyName(String.format("%s_%d",company.getCompanyName(),company.getCompanyId()));
                }
            }
            if(ObjectUtils.isNotNull(item.getCompanyUserId())){
                CompanyUser companyUser = companyUserCacheService.selectCompanyUserById(item.getCompanyUserId());
                if(ObjectUtils.isNotNull(companyUser)){
                    item.setCompanyUserName(String.format("%s_%d", companyUser.getUserName(), companyUser.getUserId()));
                }
            }
            if(ObjectUtils.isNotNull(item.getType())){
                String kbBusinessType = DictUtils.getDictLabel("sys_qw_work_task_type", String.valueOf(item.getType()));
                if(StringUtils.isNotBlank(kbBusinessType)){
                    item.setTypeText(kbBusinessType);
                }
            }
            if(ObjectUtils.isNotNull(item.getStatus())){
                String kbProcessingStatus = DictUtils.getDictLabel("sys_qw_work_task_status", String.valueOf(item.getStatus()));
                if(StringUtils.isNotBlank(kbProcessingStatus)){
                    item.setStatusText(kbProcessingStatus);
                }
            }
        }
        return list;
    }

    @Override
    public Long selectHyWorkTaskListVONewCount(QwWorkTaskListParam qwWorkTask) {
        return hyWorkTaskMapper.selectHyWorkTaskListVONewCount(qwWorkTask);
    }

    @Override
    public void addHyWorkByCourse4() {
        // 获取sop模板
        List<QwSop> qwSops = qwSopMapper.selectQwSopByIsRating();
        // 课程
        List<Long> extIds = hyWorkTaskMapper.selectHyWorkTaskByType();
        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.selectFsUserIdSopUserLogsInfoBySopId(qwSop.getId());
            if (qwSopLogs==null || qwSopLogs.isEmpty()) {
                continue;
            }
            List<FsCourseWatchLogTaskVO> fsCourseWatchLogs = fsCourseWatchLogMapper.selectFsCourseWatchLogByDaySopIdFsUser4(qwSop.getId());
            if (fsCourseWatchLogs==null || fsCourseWatchLogs.isEmpty()) {
                continue;
            }
            List<HyWorkTask> qwWorkTasks = new ArrayList<>();
            for (SopUserLogsInfo qwSopLog : qwSopLogs) {
                Map<Long, FsCourseWatchLogTaskVO> map = fsCourseWatchLogs.stream()
                        .collect(Collectors.toMap(FsCourseWatchLogTaskVO::getUserId, data -> data,(oldValue, newValue) -> newValue ));
                FsCourseWatchLogTaskVO fsCourseWatchLog = map.get(qwSopLog.getFsUserId());
                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 = getHyWorkCourseScore(fsCourseWatchLog.getLogType(), day,fsCourseWatchLog.getLevel());
                if (score==0){
                    continue;
                }
                HyWorkTask qwWorkTask = new HyWorkTask();
                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()){
                hyWorkTaskMapper.insertQwWorkTaskBatch(qwWorkTasks);
            }

        }
    }

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

        List<QwWorkTask> qwWorkTasks = hyWorkTaskMapper.selectHyWorkTaskByTypeStatus();

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

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

    }

    @Override
    public void addHyWorkByCourseLastTime() {
        List<QwSop> qwSops = qwSopMapper.selectQwSopByIsRating();
        List<Long> extIds = hyWorkTaskMapper.selectHyWorkTaskByType();
        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 = fsCourseWatchLogMapper.selectFsCourseWatchLogByDaySopId3LastTime(qwSop.getId(),lastTime);
            if (fsCourseWatchLogs==null || fsCourseWatchLogs.isEmpty()) {
                continue;
            }
            List<HyWorkTask> 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 = getHyWorkCourseScore(fsCourseWatchLog.getLogType(), day,fsCourseWatchLog.getLevel());
                if (score==0){
                    continue;
                }
                HyWorkTask qwWorkTask = new HyWorkTask();
                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()){

                hyWorkTaskMapper.insertQwWorkTaskBatch(qwWorkTasks);
            }

        }
    }

    /**
     * 查询企微任务看板
     * @param params 参数
     * @return list
     */
    @Override
    public List<HyWorkTask> selectHyWorkTaskListByMap(Map<String, Object> params) {
        return hyWorkTaskMapper.selectHyWorkTaskListByMap(params);
    }

    // 定义批处理大小常量
    private static final int BATCH_SIZE = 1000;

    @Override
    public void hyWorkTask() {

        // 获取看课中断和待看的先导课
        List<FsCourseWatchLog> fsCourseWatchLogs = hyWorkTaskMapper.hyWorkTaskGetInterruptedAndFirst();
        if(CollectionUtils.isEmpty(fsCourseWatchLogs)){
            log.info("[获取看课中断和待看的先导课] 没有找到数据，已经跳过！");
            return;
        }
        List<HyWorkTask> batchList = new ArrayList<>(BATCH_SIZE);
        int totalProcessed = 0;
        int batchCount = 0;
        for (FsCourseWatchLog fsCourseWatchLog : fsCourseWatchLogs) {
            HyWorkTask hyWorkTask = new HyWorkTask();
            hyWorkTask.setCreateTime(DateUtils.getNowDate());
            hyWorkTask.setExtId(fsCourseWatchLog.getQwExternalContactId());
            hyWorkTask.setCompanyId(fsCourseWatchLog.getCompanyId());
            hyWorkTask.setCompanyUserId(fsCourseWatchLog.getCompanyUserId());
            hyWorkTask.setUserId(fsCourseWatchLog.getUserId());
            if(fsCourseWatchLog.getPeriodId() != null) {
                hyWorkTask.setUserLogsId(String.valueOf(fsCourseWatchLog.getPeriodId()));
            }
            hyWorkTask.setStatus(0);
            hyWorkTask.setUserId(fsCourseWatchLog.getUserId());

            // 看课中断
            if(fsCourseWatchLog.getLogType()==4){
                hyWorkTask.setType(2);
                Date createTime = fsCourseWatchLog.getCreateTime();
                long day = DateUtils.getDaysDifferenceFromNow(createTime);
                hyWorkTask.setTitle("第"+day+"天"+"看课中断");
            } else {
                hyWorkTask.setType(1);
                hyWorkTask.setTitle(fsCourseWatchLog.getLogType()==3?"先导课待看课":"先导课完课");
            }
            hyWorkTask.setScore(fsCourseWatchLog.getLogType()==3?4:3);

            batchList.add(hyWorkTask);
            totalProcessed++;

            if (batchList.size() >= BATCH_SIZE) {
                batchCount++;
                log.info("处理到第 {} 条数据，开始插入第 {} 批 ({} 条)...", totalProcessed, batchCount, batchList.size());
                try {
                    hyWorkTaskMapper.insertQwWorkTaskBatch(batchList);
                    log.info("第 {} 批插入成功.", batchCount);
                } catch (Exception e) {
                    log.error("第 {} 批插入时发生错误: {}", batchCount, e.getMessage(), e);
                }
                batchList.clear();
            }
        }
        if (!batchList.isEmpty()) {
            batchCount++;
            log.info("处理完成，开始插入最后一批 ({} 条)...", batchList.size());
            try {
                hyWorkTaskMapper.insertQwWorkTaskBatch(batchList);
                log.info("最后一批插入成功.");
            } catch (Exception e) {
                log.error("最后一批插入时发生错误: {}", e.getMessage(), e);
            }
            batchList.clear();
        }
        log.info("hyWorkTask 任务执行完毕，共处理 {} 条数据，分 {} 批插入.", totalProcessed, batchCount > 0 ? batchCount : (totalProcessed > 0 ? 1 : 0));

    }

    /**
     * 根据SOP执行日志和特定条件，为符合要求的外部联系人添加企业微信工作任务。
     * <p>
     * 此方法仅在传入的 `day` 参数大于7时执行。
     * 它会查询指定 `QwSop` 在过去 `day` 天内的用户执行日志 (`SopUserLogsInfo`)。
     * 遍历日志，获取关联的外部联系人 (`QwExternalContact`)。
     * 对联系人进行筛选：必须存在，且其级别 (`level`) 不能为 null、0 或 4。
     * 对于通过筛选的联系人，调用内部的 `insertQwWorkTask` 方法来创建任务。
     * </p>
     *
     * @param today   当前日期，用于计算查询日志的起始日期。
     * @param day     回溯的天数。只有当 `day` 大于 7 时，才会执行添加任务的逻辑。
     * @param qwSop   企业微信SOP（标准操作流程）对象，包含需要查询日志的SOP ID。
     * @param title   要创建的企业微信工作任务的标题。
     * @param map     一个映射表，键可能是外部联系人的级别 (`level`)，值可能是传递给 `insertQwWorkTask` 的参数（例如优先级或特定配置）。
     *                如果联系人级别在map中不存在，则使用默认值0。
     * @author xdd
     * @version 1.0
     * @since yyyy-MM-dd // 建议替换为实际的编写或修改日期
     */
    private void addHyWorkTask(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");


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


    private void insertHyWorkTask(String sopId,QwExternalContact qwExternalContact, Integer type, String title, Integer score) {
        HyWorkTask qwWorkTask = new HyWorkTask();
        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.insertHyWorkTask(qwWorkTask);
    }


}
