package com.fs.qw.qwTask;

import com.fs.course.service.IFinishCourseStatisticsSyncService;
import com.fs.course.service.IFsUserCourseService;
import com.fs.his.service.IFsUserService;
import com.fs.qw.domain.QwIpadServerLog;
import com.fs.qw.domain.QwUser;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.qw.param.QwMandatoryRegistrParam;
import com.fs.qw.service.*;
import com.fs.sop.service.impl.QwSopLogsServiceImpl;
import com.fs.sop.service.impl.QwSopServiceImpl;
import com.fs.sop.service.ISopUserLogsService;
import com.fs.statis.IFsStatisQwWatchService;
import com.fs.statis.service.FsStatisSalerWatchService;
import com.fs.wxwork.dto.WxWorkGetQrCodeDTO;
import com.fs.wxwork.service.WxWorkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Component("qwTask")
public class qwTask {

    @Autowired
    private QwSopServiceImpl qwSopService;

    @Autowired
    private QwSopLogsServiceImpl qwSopLogsService;

    @Autowired
    private IQwGroupMsgService qwGroupMsgService;

    @Autowired
    private ISopUserLogsService sopUserLogsService;
    @Autowired
    private IQwExternalContactService qwExternalContactService;

    @Autowired
    private IFsUserCourseService iFsUserCourseService;

    @Autowired
    private IQwUserService qwUserService;


    @Autowired
    private FsStatisSalerWatchService fsStatisSalerWatchService;

    @Autowired
    private IFsStatisQwWatchService fsStatisQwWatchService;

    @Autowired
    private IQwMaterialService iQwMaterialService;


    @Autowired
    private QwUserMapper qwUserMapper;

    @Autowired
    private IQwIpadServerService ipadServerService;

    @Autowired
    private IQwIpadServerLogService qwIpadServerLogService;

    @Autowired
    private IQwIpadServerUserService qwIpadServerUserService;

    @Autowired
    private IQwExternalContactService externalContactService;

    @Autowired
    private WxWorkService wxWorkService;

    @Autowired
    private IFsUserService fsUserService;


    @Autowired
    private IQwCompanyService iQwCompanyService;


    @Autowired
    private IFinishCourseStatisticsSyncService finishCourseStatisticsSyncService;


    //正在使用
    public void qwExternalContact()
    {
        qwExternalContactService.qwExternalContactSync();
    }
    //正在使用
    public void qwExternalContactAddAndDel()
    {
        qwExternalContactService.qwExternalContactSyncAddAndDel();
    }
    //正在使用
    public void qwExternalContactSyncAddRedis()
    {
        qwExternalContactService.qwExternalContactSyncAddRedis();
    }
    //正在使用
    public void qwExternalContactAddRedis()
    {
        qwExternalContactService.qwExternalContactAddRedis();
    }
    //正在使用
    public void qwExternalContactAddAndDelByRedis()
    {
        qwExternalContactService.qwExternalContactAddAndDelByRedis();
    }
    //正在使用
    public void qwExternalContactAddTag()
    {
        qwExternalContactService.qwExternalContactAddCourseTag();
    }

    /**
    * 定时任务 将 qw_sop任务 符合条件的录入到sop_user_Logs(clickHouse)
    */
    public void qwCheckSopRuleTime()
    {
        qwSopService.checkSopRuleTime();
    }

    /**
    * 定时任务 将 clickHouse的sopUserLogs(营期表)按每小时的巡回 录入clickHouse的qw_sop_logs(消息发送表)
    */
    public void selectSopUserLogsListByTime(){
        sopUserLogsService.selectSopUserLogsListByTime();
    }

    /**
    * 定时 发送 通过调用 企业微信接口 发送的 SOP 群发消息
    */
    public void SendQwApiSopLogTimer(){
        qwSopLogsService.checkQwSopLogs();
    }

    /**
    * 定时获取 通过调用 企业微信接口 发送的 SOP 客户群发消息 的反馈结果
    */
    public void GetQwApiSopLogResultTimer(){
        qwSopLogsService.qwSopLogsResult();
    }

    /**
    * 定时群发API接口的 客户/群 群发
    */
    public void sendQwGroupMsgTask(){
        qwGroupMsgService.qwGroupMsgTask();
    }

    /**
    *  定时更新 待发送中已经算过期了的不能发的消息
    */
    public void updateQwSopLogsBySendStatusTask(){
        qwSopLogsService.updateQwSopLogsBySendStatus();
    }

    /**
     * 2天跑一次 将 课程的封面 上传企业微信 并上传到redis
     */
    public void processQwSopCourseMaterialTimer() {

        iFsUserCourseService.processQwSopCourseMaterialTimer();

    }
    /**
    *  同步待同步客户
    */
    public void synchronizeQwExternalContactTask(){
        qwExternalContactService.synchronizeQwExternalContactTask();
    }


    /**
     * 定时解除 已经删除了的销售 绑定的企业微信云主机。或者是没有绑定销售 却绑定了云主机的
     */
    public void unlockQwUserLoginCodeUrlTask(){
        qwUserService.unlockQwUserLoginCodeUrlTask();
    }


    /**
     * 看课统计
     */
    public void watchCourseStatis(String date){
        if("1".equals(date)){
            fsStatisSalerWatchService.writeData(null);
        } else {
            fsStatisSalerWatchService.writeData(date);
        }
    }

    /**
     * 看课统计昨天
     */
    public void watchCourseStatisPrevious(){
        LocalDate localDate = LocalDate.now().minusDays(1);
        fsStatisSalerWatchService.writeData(localDate.toString());
    }
    /**
     * 看课统计-统计当天的-每15分钟统计一次
     */
    public void watchCourseStatisToday(){
        fsStatisSalerWatchService.writeDataToday();
    }

    /**
     * 进线转化统计
     */
    public void qwWatchCourseStatis(String date){
        if("1".equals(date)){
            fsStatisQwWatchService.writeData(null);
        } else {
            fsStatisQwWatchService.writeData(date);
        }
    }

    /**
     * 进线转化统计
     */
    public void qwWatchCourseStatisToday(){
        LocalDate today = LocalDate.now();
        fsStatisQwWatchService.writeData(today.toString());
    }

    /**
    * 每俩天 更新一次 素材库
    */
    public void updateMaterialByTwoDays(){
        iQwMaterialService.updateQwMaterialByQw();
    }

    /**
     * 统计 每天的官方群发统计
     */
    public void countQwApiAopLogToken(){
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 获取当前日期（只包含年月日）
        LocalDate currentDate = LocalDate.now();

        String todayStr = currentDate.format(dateFormatter);
         qwSopLogsService.countQwApiAopLogToken(todayStr);


    }

    /**
     * 定时清除 占着茅坑不拉屎的ipad 账号
     */
    public void selectQwUserByUnbindIpad(){

        //查询所有状态为 绑定了AI主机的
        List<QwUser> list = qwUserMapper.selectQwUserByTest();
        for (QwUser qwUser : list) {
            try {

                Long serverId = qwUser.getServerId();

                if (serverId==null){
                    System.out.println("serverId不存在");
                }else {
                    //没绑定销售 或者 已经离职
                    if (qwUser.getStatus()==0 || qwUser.getIsDel()==2){

                        updateIpadStatus(qwUser,serverId);
                    }

                    //绑定了销售-也绑定了ipad,但是长时间离线的(离线状态，无操作超过2天的，也自动解绑)
                    if(qwUser.getCreateTime()!=null){
                        Date createTime = qwUser.getCreateTime();
                        Integer serverStatus = qwUser.getServerStatus();
                        Integer ipadStatus = qwUser.getIpadStatus();

                        boolean result = isCreateTimeMoreThanDaysWithOptional(createTime, 2);
                        //大于2天 ，绑定了ipad，离线
                        if(result && serverStatus==1 && ipadStatus==0){
                            updateIpadStatus(qwUser,serverId);

                        }
                    }


                }


            } catch (Exception e) {
                System.out.println("解绑ipad报错"+e);

            }
        }
    }

    public void updateIpadStatus(QwUser qwUser,Long serverId){
        QwUser u = new QwUser();
        u.setId(qwUser.getId());
        u.setServerId(null);
        u.setServerStatus(0);
        qwUserMapper.updateQwUser(u);
        ipadServerService.addServer(serverId);
        QwIpadServerLog qwIpadServerLog = new QwIpadServerLog();
        qwIpadServerLog.setType(2);
        qwIpadServerLog.setTilie("解绑");
        qwIpadServerLog.setServerId(serverId);
        qwIpadServerLog.setQwUserId(qwUser.getId());
        qwIpadServerLog.setCompanyUserId(qwUser.getCompanyUserId());
        qwIpadServerLog.setCompanyId(qwUser.getCompanyId());
        qwIpadServerLog.setCreateTime(new Date());
        qwIpadServerLogService.insertQwIpadServerLog(qwIpadServerLog);
        qwIpadServerUserService.deleteQwIpadServerUserByQwUserId(qwUser.getId());
        WxWorkGetQrCodeDTO wxWorkGetQrCodeDTO = new WxWorkGetQrCodeDTO();
        wxWorkGetQrCodeDTO.setUuid(qwUser.getUid());
        wxWorkService.LoginOut(wxWorkGetQrCodeDTO,qwUser.getServerId());
        updateIpadStatus(qwUser.getId(),0);
    }

    public static boolean isCreateTimeMoreThanDaysWithOptional(Date createTime, int days) {
        return Optional.ofNullable(createTime)
                .map(time -> {
                    LocalDateTime createDateTime = time.toInstant()
                            .atZone(ZoneId.systemDefault())
                            .toLocalDateTime();
                    LocalDateTime now = LocalDateTime.now();
                    Duration duration = Duration.between(createDateTime, now);
                    return duration.toDays() > days;
                })
                .orElse(false); // 为null时返回false，可根据需求调整
    }

    void updateIpadStatus(Long id ,Integer status){
        QwUser u = new QwUser();
        u.setId(id);
        u.setIpadStatus(status);
        qwUserMapper.updateQwUser(u);
    }

    /**
     * 自动解除误封禁的用户
     * 定时任务：将 fs_user 表中 status=0 且 manage_status=1 且 remark 为 null 的用户
     * 自动恢复为 status=1，并设置 remark="自动解除封禁"
     */
    public void autoUnbanMistakenlyDisabledUsers() {
        fsUserService.autoUnbanMistakenlyDisabledUsers();
    }


    /**
     * 强制注册-2025-11-12 之后的 更新
     */
    public void QwExternalContactMandatoryRegistration(){
        try {
//            List<String> longs = qwExternalContactService.selectQwExternalContactMandatoryRegistration();
            List<String> longs = iQwCompanyService.selectQwCompanyListFormCorpId();
            longs.forEach(item->{
                List<QwMandatoryRegistrParam> registrParamList = qwExternalContactService.selectQwExternalContactMandatoryRegistrationByIds(String.valueOf(item));

                batchUpdateQwExternalContactMandatoryRegistration(registrParamList);

            });
        }catch (Exception e){

        }

    }


    private void batchUpdateQwExternalContactMandatoryRegistration(List<QwMandatoryRegistrParam> registrParamList) {
        // 定义批量插入的大小
        int batchSize = 300;

        // 循环处理外部用户 ID，每次处理批量大小的子集
        for (int i = 0; i < registrParamList.size(); i += batchSize) {

            int endIndex = Math.min(i + batchSize, registrParamList.size());
            List<QwMandatoryRegistrParam> batchList = registrParamList.subList(i, endIndex);  // 获取当前批次的子集

            qwExternalContactService.batchUpdateQwExternalContactMandatoryRegistration(batchList);

        }
    }

    /**
     * 特殊处理(木易完课统计数据)
     */
    public  void  syncMultiDimensionStatistics(){
        finishCourseStatisticsSyncService.syncMultiDimensionStatistics();
    }
}
