package com.fs.app.controller;

import com.alibaba.fastjson.JSON;
import com.fs.common.core.redis.RedisCache;
import com.fs.course.mapper.FsCourseWatchLogMapper;
import com.fs.course.param.FsCourseWatchLogByFinishTimeParam;
import com.fs.qw.vo.QwSopRuleTimeVO;
import com.fs.sop.domain.SopUserLogs;
import com.fs.sop.domain.SopUserLogsInfo;
import com.fs.sop.mapper.QwSopMapper;
import com.fs.sop.mapper.SopUserLogsInfoMapper;
import com.fs.sop.params.QwSopAutoByTags;
import com.fs.sop.params.SopUserLogsParamByDate;
import com.fs.sop.service.IQwSopLogsService;
import com.fs.sop.service.ISopUserLogsService;
import com.fs.voice.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class TestCourseService {
    @Autowired
    RedisCache redisCache;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Autowired
    private IQwSopLogsService qwSopLogsService;

    @Autowired
    private QwSopMapper qwSopMapper;

    @Autowired
    private FsCourseWatchLogMapper fsCourseWatchLogMapper;

    @Autowired
    private ISopUserLogsService sopUserLogsService;

    @Autowired
    private SopUserLogsInfoMapper sopUserLogsInfoMapper;

    @Async
    public void sysncCousre(List<FsCourseWatchLogByFinishTimeParam> fsCourseWatchLogByFinishTimeParams){

        fsCourseWatchLogByFinishTimeParams.stream().forEach(item->{

            // 将标签字符串解析为 List    //客户总标签
            List<String> tagIdsList = new ArrayList<>();

            if (item.getTagIds() != null && !item.getTagIds().isEmpty()) {
                tagIdsList = JSON.parseArray(item.getTagIds(), String.class);
            }
//            分时段里符合的标签-再用来创建自动SOP
            QwSopAutoByTags qwSopAutoByTags=new QwSopAutoByTags();
            qwSopAutoByTags.setQwUserId(String.valueOf(item.getQwUserId()));
            qwSopAutoByTags.setCorpId(item.getCorpId());
            qwSopAutoByTags.setTagsIdsSelectList(tagIdsList);
            qwSopAutoByTags.setSendType(2);

            if (!tagIdsList.isEmpty()){
                List<QwSopRuleTimeVO> qwSopRuleTimeVOS = qwSopMapper.selectQwSopAutoByTagsByForeachNotAuto(qwSopAutoByTags);

                if (qwSopRuleTimeVOS != null && !qwSopRuleTimeVOS.isEmpty()){

                    Date campPeriodTime = item.getCampPeriodTime();
                    // 将 Date 转换为 LocalDate
                    LocalDate currentDate = campPeriodTime.toInstant()
                            .atZone(ZoneId.systemDefault())
                            .toLocalDate();
                    //SOP规则
                    qwSopRuleTimeTools(qwSopRuleTimeVOS,item.getQwUser(),item.getQwUserId(),item.getCompanyUserId(),item.getCompanyId(),
                            item.getCorpId(),item.getExternalUserId(),item.getExternalContactName(),item.getQwExternalContactId(),
                            item.getUserId(),currentDate,tagIdsList);
                }
            }


        });

    }

    public void qwSopRuleTimeTools(List<QwSopRuleTimeVO> qwSopRuleTimeVOS, String qwUserChar, Long qwUserId,
                                   Long companyUserId, Long companyId, String cropId,
                                   String externalUserID, String externalContactName, Long contactId, Long contactFsUserId,
                                   LocalDate currentDate, List<String> combinedTagsList) {
        // 定义日期和时间格式化器
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // sop任务
        qwSopRuleTimeVOS.forEach(ruleTimeVO -> {

            // 将排除的字符串转成列表
            List<String> excludedTagsList=new ArrayList<>();
            if (ruleTimeVO.getExcludeTags() != null && !ruleTimeVO.getExcludeTags().isEmpty()){
                excludedTagsList= Arrays.asList( ruleTimeVO.getExcludeTags().split(","));
            }

            // 检查 combinedTagsList 是否包含排除列表中的任意一个标签
            boolean containsExcludedTag = combinedTagsList.stream()
                    .anyMatch(excludedTagsList::contains);

            //含任意一个排除标签
            if (containsExcludedTag) {
                return;
            }


            // 用于查询/或新增
            SopUserLogs userLogs = new SopUserLogs();
            userLogs.setSopId(ruleTimeVO.getId());
            userLogs.setSopTempId(ruleTimeVO.getTempId());
            userLogs.setCorpId(ruleTimeVO.getCorpId());
            userLogs.setStatus(1);

            // 用于今天的新增
            SopUserLogsParamByDate userLogsParamByDate = new SopUserLogsParamByDate();
            userLogsParamByDate.setSopId(ruleTimeVO.getId());
            userLogsParamByDate.setSopTempId(ruleTimeVO.getTempId());
            userLogsParamByDate.setCorpId(ruleTimeVO.getCorpId());
            userLogsParamByDate.setStatus(1);


            // 设定用户信息
            userLogs.setQwUserId(qwUserChar);
            userLogs.setUserId(qwUserId + "|" + companyUserId + "|" + companyId);
            userLogsParamByDate.setQwUserId(qwUserChar);
            userLogsParamByDate.setUserId(qwUserId + "|" + companyUserId + "|" + companyId);

            // 创建 SopUserLogsInfo
            SopUserLogsInfo logsInfo = new SopUserLogsInfo();
            logsInfo.setQwUserId(qwUserChar);
            logsInfo.setCorpId(cropId);
            logsInfo.setExternalContactId(externalUserID.trim());
            logsInfo.setExternalId(contactId);
            logsInfo.setFsUserId(contactFsUserId);
            logsInfo.setExternalUserName(externalContactName);
            logsInfo.setSopId(ruleTimeVO.getId());

            // 判断 SOP 任务的开始时间
            qwSopRuleTimeToolsCheck(currentDate,dateFormatter,userLogs,logsInfo,userLogsParamByDate);
        });
    }

    public void qwSopRuleTimeToolsCheck(LocalDate currentDate,DateTimeFormatter dateFormatter,
                                        SopUserLogs userLogs,SopUserLogsInfo logsInfo,SopUserLogsParamByDate userLogsParamByDate) {


        // 今天的日期字符串
        String todayStr = currentDate.format(dateFormatter);
        userLogs.setStartTime(todayStr);

        // 查询今天的营期表
        String unionSopStartId2 = sopUserLogsService.selectSopUserLogsByUnionSopId(userLogs);

        if (!StringUtil.strIsNullOrEmpty(unionSopStartId2)) {

            try {
                // 查询客户是否已存在
            SopUserLogsInfo userLogsInfo = sopUserLogsInfoMapper.selectSopUserLogsInfo(logsInfo);
            if (userLogsInfo == null) {

                logsInfo.setUserLogsId(unionSopStartId2);

                System.out.println("客户加入营期："+logsInfo.getSopId()+":"+logsInfo.getQwUserId()+":"+logsInfo.getExternalContactId()+":"+logsInfo.getExternalUserName()+":"+logsInfo.getCorpId());
                //客户入营期
                sopUserLogsInfoMapper.insertSopUserLogsInfo(logsInfo);
            }else {
                //如果客户不为空-看营期

                System.out.println("营期--:"+userLogsInfo);

                if (!userLogsInfo.getUserLogsId().equals(unionSopStartId2)){

                    userLogsInfo.setUserLogsId(unionSopStartId2);

                    sopUserLogsInfoMapper.updateSopUserLogsInfoToTime(userLogsInfo);

                    System.out.println("客户重回营期："+todayStr+":"+logsInfo.getSopId()+":"+logsInfo.getQwUserId()+":"+logsInfo.getExternalContactId()+":"+logsInfo.getExternalUserName()+":"+logsInfo.getCorpId());

                }


            }


            }catch (Exception e){
                System.out.println("客户入营期失败:logsInfo："+logsInfo+"msg----"+e.getMessage());
            }


        }

    }

}
