package com.fs.his.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.service.impl.SmsServiceImpl;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.SecurityUtils;
import com.fs.company.domain.CompanyMoneyLogs;
import com.fs.company.domain.CompanyUser;
import com.fs.company.domain.CompanyVoiceCaller;
import com.fs.company.mapper.*;
import com.fs.company.service.ICompanyService;
import com.fs.company.service.ICompanyUserService;
import com.fs.company.vo.QwIpadTotalVo;
import com.fs.company.vo.RedPacketMoneyVO;
import com.fs.course.dto.BatchSendCourseAllDTO;
import com.fs.course.mapper.FsCourseRedPacketLogMapper;
import com.fs.course.service.IFsCourseWatchLogService;
import com.fs.course.service.ITencentCloudCosService;
import com.fs.erp.domain.ErpDeliverys;
import com.fs.erp.domain.ErpOrderQuery;
import com.fs.erp.dto.ErpOrderQueryRequert;
import com.fs.erp.dto.ErpOrderQueryResponse;
import com.fs.erp.service.IErpOrderService;
import com.fs.fastGpt.domain.*;
import com.fs.fastGpt.mapper.FastGptChatSessionMapper;
import com.fs.fastGpt.mapper.FastgptChatVoiceHomoMapper;
import com.fs.fastGpt.service.AiHookService;
import com.fs.fastGpt.service.IFastgptEventLogTotalService;
import com.fs.fastgptApi.util.AudioUtils;
import com.fs.fastgptApi.vo.AudioVO;
import com.fs.his.config.FsSysConfig;
import com.fs.his.config.StoreConfig;
import com.fs.his.domain.*;
import com.fs.his.dto.FsInquiryOrderPatientDTO;
import com.fs.his.enums.FsStoreOrderLogEnum;
import com.fs.his.enums.FsStoreOrderStatusEnum;
import com.fs.his.mapper.*;
import com.fs.his.param.FsInquiryOrderFinishParam;
import com.fs.his.param.FsPackageOrderCancelParam;
import com.fs.his.service.*;
import com.fs.his.utils.ConfigUtil;
import com.fs.his.vo.FsSubOrderResultVO;
import com.fs.hisStore.domain.FsStoreOrderScrm;
import com.fs.hisStore.domain.FsStorePaymentScrm;
import com.fs.hisStore.mapper.FsStorePaymentScrmMapper;
import com.fs.hisStore.service.IFsStoreOrderScrmService;
import com.fs.hisStore.service.IFsStorePaymentScrmService;
import com.fs.huifuPay.domain.HuiFuQueryOrderResult;
import com.fs.huifuPay.sdk.opps.core.request.V2TradePaymentScanpayQueryRequest;
import com.fs.huifuPay.service.HuiFuService;
import com.fs.hisStore.domain.FsStorePaymentScrm;
import com.fs.hisStore.mapper.FsStorePaymentScrmMapper;
import com.fs.hisStore.service.IFsStorePaymentScrmService;
import com.fs.huifuPay.domain.HuiFuQueryOrderResult;
import com.fs.huifuPay.sdk.opps.core.request.V2TradePaymentScanpayQueryRequest;
import com.fs.huifuPay.service.HuiFuService;
import com.fs.hisStore.service.IFsStoreOrderScrmService;
import com.fs.im.dto.*;
import com.fs.im.service.IImService;
import com.fs.im.service.OpenIMService;
import com.fs.qw.domain.QwCompany;
import com.fs.qw.domain.QwUser;
import com.fs.qw.mapper.QwRestrictionPushRecordMapper;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.qw.service.*;
import com.fs.qwApi.service.QwApiService;
import com.fs.sop.domain.QwSopTempVoice;
import com.fs.sop.service.IQwSopTempVoiceService;
import com.fs.system.domain.SysConfig;
import com.fs.system.mapper.SysConfigMapper;
import com.fs.system.service.ISysConfigService;
import com.fs.utils.OrderContextHolder;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Slf4j
@Component("task")
public class Task {
    @Autowired
    private FsUserCouponMapper fsUserCouponMapper;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private IFsPrescribeService fsPrescribeService;
    @Autowired
    IFsStoreOrderService fsStoreOrderService;
    @Autowired
    FsStoreOrderMapper fsStoreOrderMapper;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private FsPackageOrderMapper fsPackageOrderMapper;
    @Autowired
    private IFsFollowService fsFollowService;
    @Autowired
    private IFsStoreAfterSalesService fsStoreAfterSalesService;
    //    @Autowired
//    IErpOrderService erpOrderService;
    @Autowired
    FsIntegralOrderMapper integralOrderMapper;
    @Autowired
    IFsInquiryOrderService iFsInquiryOrderService;
    @Autowired
    FsPackageMapper fsPackageMapper;
    @Autowired
    FsStoreProductMapper fsStoreProductMapper;
    @Autowired
    CompanyMapper companyMapper;
    @Autowired
    private CompanyMoneyLogsMapper moneyLogsMapper;
    @Autowired
    FsUserMapper fsUserMapper;
    @Autowired
    IFsUserIntegralLogsService fsUserIntegralLogsService;
    @Autowired
    SmsServiceImpl smsService;
    @Autowired
    FsStoreOrderItemMapper fsStoreOrderItemMapper;

    @Autowired
    FsPatientMapper fsPatientMapper;
    @Autowired
    FsPrescribeDrugMapper fsPrescribeDrugMapper;
    @Autowired
    FsFollowMapper fsFollowMapper;
    @Autowired
    private IImService imService;
    @Autowired
    private FsInquiryOrderMapper inquiryOrderMapper;
    @Autowired
    private CompanyVoiceCallerMapper companyVoiceCallerMapper;
    @Autowired
    private CompanyVoiceLogsMapper companyVoiceLogsMapper;
    @Autowired
    IFsPackageOrderService packageOrderService;
    @Autowired
    private IFsStoreOrderLogsService fsStoreOrderLogsService;
    org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    IFsDoctorService doctorService;
    @Autowired
    CompanyUserMapper companyUserMapper;
    @Autowired
    FsInquiryOrderMapper fsInquiryOrderMapper;
    @Autowired
    FsCourseRedPacketLogMapper fsCourseRedPacketLogMapper;
    @Autowired
    QwApiService qwApiService;
    //每天执行一次
    @Autowired
    IQwAppContactWayService qwAppContactWayService;

    @Autowired
    FastGptChatSessionMapper fastGptChatSessionMapper;

    @Autowired
    IQwExternalContactTransferLogService qwExternalContactTransferLogService;

    @Autowired
    private IFsCourseWatchLogService fsCourseWatchLogService;

    @Autowired
    ITencentCloudCosService tencentCloudCosService;
    @Autowired
    private ConfigUtil configUtil;
    @Autowired
    private IQwCompanyService qwCompanyService;
    @Autowired
    private IQwUserService qwUserService;
    @Autowired
    private OpenIMService openIMService;
    @Autowired
    public RedisTemplate redisTemplate;

    @Autowired
    private ICompanyUserService userService;

    @Autowired
    private IFsStoreOrderScrmService fsStoreOrderScrmService;

    @Autowired
    private IFastgptEventLogTotalService fastgptEventLogTotalService;

    @Autowired
    private FastgptChatVoiceHomoMapper fastgptChatVoiceHomoMapper;
    @Autowired
    private IQwSopTempVoiceService qwSopTempVoiceService;

    @Autowired
    private QwRestrictionPushRecordMapper qwRestrictionPushRecordMapper;
    @Autowired
    private FsUserOperationLogMapper fsUserOperationLogMapper;

    public static final String SOP_TEMP_VOICE_KEY = "sop:tempVoice";
    @Autowired
    private IFsStorePaymentService fsStorePaymentService;

    @Autowired
    private IFsStoreOrderService orderService;
    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Autowired
    private FsIntegralOrderMapper fsIntegralOrderMapper;

    private final String DELAY_MSG = "delayMsg";

    @Autowired
    private QwUserMapper qwUserMapper;

    @Autowired
    private AiHookService aiHookService;

    @Autowired
    private IFsStorePaymentScrmService paymentScrmService;

    @Autowired
    private IFsStoreOrderScrmService orderScrmService;
    /**
     * 定时任务，处理ai禁止回复之后的消息
     */
    public void forbidTimeMsgTask() {
        Map<String, Object> cacheMap = redisCache.hGetAll(DELAY_MSG);
        for (String key : cacheMap.keySet()) {
            String value = (String) cacheMap.get(key);
            //获取sessionId
            Long sessionId = Long.parseLong(key);
            try {
                Thread.sleep(800);
            } catch (Exception e) {
                log.error("定时消息处理异常,会话id：{},文本：{}",sessionId,value,e);
            }
            try {
                if (value != null && !value.isEmpty()) {
                    FastGptChatSession chatSession = fastGptChatSessionMapper.selectFastGptChatSessionBySessionId(sessionId);
                    Long qwUserId = chatSession.getQwUserId();
                    QwUser qwUser = qwUserMapper.selectQwUserById(qwUserId);
                    String uid = qwUser.getUid();

                    JSONObject jsonObject = JSONObject.parseObject(value);
                    String content = jsonObject.getString("content");
                    Long sender = jsonObject.getLong("sender");
                    Integer type = jsonObject.getInteger("type");

                    aiHookService.qwHookNotifyAiReply(qwUserId,sender,content,uid,type);
                    //删除已经处理的缓存
                    redisCache.hDel(DELAY_MSG,key);
                }
            } catch (Exception e) {
                log.error("个人定时消息处理异常,会话id：{},文本：{}",sessionId,value,e);
            }
        }
    }

    /**
     * sop任务token消耗统计
     */
    public void sopPushTokenTotal() {
        // 判断是否是凌晨 00:00 - 00:59
        boolean isEarlyMorning = isEarlyMorning();

        // 获取日期字符串（今天或昨天）
        String dateTime;
        if (isEarlyMorning) {
            dateTime = DateUtils.addDateDays(-1); // 昨天
        } else {
            dateTime = DateUtils.getDate(); // 今天
        }
        log.info("开始执行sop任务token消耗统计");
        try {
            List<FastGptPushTokenTotal> fastGptPushTotalList = qwRestrictionPushRecordMapper.selectFastgptPushTokenTotal(dateTime);
            if (fastGptPushTotalList != null && !fastGptPushTotalList.isEmpty()) {
                for (FastGptPushTokenTotal fastGptPushTotal : fastGptPushTotalList) {
                    // 获取统计数据
                    Integer type = fastGptPushTotal.getType();
                    Long count = 0L;
                    if(type == 7){
                        count = fastGptPushTotal.getCount() * 450;
                    }else{
                        count = fastGptPushTotal.getCount() * 150;
                    }
                    // 实际流量传输消耗是大于文件的，添加倍数计算流量消耗 配置 course.data.usage.multiple
                    BigDecimal multiple = new BigDecimal("1"); // 默认一倍
                    String config = sysConfigService.selectConfigByKey("course.data.usage.multiple");
                    if(com.fs.common.utils.StringUtils.isNotEmpty(config)){
                        multiple=new BigDecimal(config);
                    }
                    fastGptPushTotal.setCount(BigDecimal.valueOf(count).multiply(multiple).setScale(0, RoundingMode.UP).longValue());
                    // 计算金额：1元 = 10万token，按 token 用 BigDecimal 四舍五入到分
                    fastGptPushTotal.setAmount(FastGptPushTokenTotal.calcAmountByCount(fastGptPushTotal.getCount()));

                    FastGptPushTokenTotal pushTotal = qwRestrictionPushRecordMapper.selectFastGptPushTokenTotalByInfo(fastGptPushTotal);
                    if(pushTotal == null){
                        qwRestrictionPushRecordMapper.insertPushTokenTotal(fastGptPushTotal);
                    }else{
                        fastGptPushTotal.setId(pushTotal.getId());
                        qwRestrictionPushRecordMapper.updatePushTokenTotal(fastGptPushTotal);
                    }
                }
            }
            log.info("结束执行sop任务token消耗统计");
        } catch (Exception e) {
            log.error("执行sop任务token消耗统计异常", e);
        }
    }

    /**
     * 一键生成语音定时任务
     */
    public void ConsumerSopTempVoice() {
        try {
            Long newCompanyUserId = redisCache.popVoiceKey(SOP_TEMP_VOICE_KEY);
            if (newCompanyUserId != null) {
                List<QwSopTempVoice> sopTempVoices = redisCache.getVoiceAllList(SOP_TEMP_VOICE_KEY + ":" + newCompanyUserId);
                if (sopTempVoices != null && !sopTempVoices.isEmpty()) {
                    try {
                        for (QwSopTempVoice qwSopTempVoice : sopTempVoices) {
                            try {
                                AudioVO audioVO = new AudioVO();
                                List<FastgptChatVoiceHomo> homos = fastgptChatVoiceHomoMapper.selectFastgptChatVoiceHomoList(new FastgptChatVoiceHomo());
                                audioVO = AudioUtils.createUserUrlAndUrl(homos, qwSopTempVoice.getCompanyUserId(), qwSopTempVoice.getVoiceTxt());
                                if (audioVO != null && audioVO.getWavUrl() != null && audioVO.getUrl() != null) {
                                    qwSopTempVoice.setVoiceUrl(audioVO.getUrl());
                                    qwSopTempVoice.setUserVoiceUrl(audioVO.getWavUrl());
                                    qwSopTempVoice.setDuration(audioVO.getDuration());
                                    qwSopTempVoice.setRecordType(1);
                                    qwSopTempVoiceService.updateQwSopTempVoice(qwSopTempVoice);
                                }
                            } catch (Exception e) {

                            }
                        }
                    } finally {
                        redisCache.deleteObject(SOP_TEMP_VOICE_KEY + ":" + newCompanyUserId);
                    }
                }
            } else {
                log.info("没有需要生成的语音");
            }
        } catch (Exception e) {
            log.error("生成语音定时任务执行异常", e);
        }
    }

    //统计ai事件埋点
    public void eventLogTotals() {
        // 判断是否是凌晨 00:00 - 00:59
        boolean isEarlyMorning = isEarlyMorning();

        // 获取日期字符串（今天或昨天）
        String dateTime;
        Date date;
        if (isEarlyMorning) {
            dateTime = DateUtils.addDateDays(-1); // 昨天
            date = DateUtils.addDays(new Date(), -1); // 昨天的 Date 对象
        } else {
            dateTime = DateUtils.getDate(); // 今天
            date = new Date(); // 今天的 Date 对象
        }
        //更新埋点
        processEventLogTotals(date, dateTime);
        //更新token消耗
        processTokenLogs(date, dateTime);
    }

    private void processEventLogTotals(Date date, String dateTime) {
        FastgptEventLogTotal logTotal = new FastgptEventLogTotal();
        logTotal.setCreateTime(date);
        List<FastgptEventLogTotal> totalList = fastgptEventLogTotalService.selectFastgptEventLogTotalInfoList(logTotal);

        // 分别收集需要更新和插入的记录
        List<FastgptEventLogTotal> toUpdateList = new ArrayList<>();
        List<FastgptEventLogTotal> toInsertList = new ArrayList<>();

        // 用于防止重复添加相同记录的集合
        Set<String> processedKeys = new HashSet<>();

        for (FastgptEventLogTotal total : totalList) {
            try {
                if (total == null) {
                    continue;
                }

                if (total.getType() == 1) {
                    total.setCount(total.getSenderCount());
                }
                // 构造唯一标识符，用于防止重复处理
                String uniqueKey = String.format("%d_%d_%d_%d_%d_%s",
                        total.getRoleId() != null ? total.getRoleId() : 0,
                        total.getType() != null ? total.getType() : 0,
                        total.getCompanyId() != null ? total.getCompanyId() : 0,
                        total.getCompanyUserId() != null ? total.getCompanyUserId() : 0,
                        total.getQwUserId() != null ? total.getQwUserId() : 0,
                        dateTime
                );
                // 检查是否已经处理过这个记录
                if (processedKeys.contains(uniqueKey)) {
                    continue;
                }

                FastgptEventLogTotal info = fastgptEventLogTotalService.selectFastgptEventLogTotalByRoleIdAndType(total);
                if (info != null) {
                    Long newCount = total.getCount() != null ? total.getCount() : 0L;
                    // 只有当count值发生变化时才加入更新列表
                    if (!newCount.equals(info.getCount())) {
                        FastgptEventLogTotal eventLogTotal = new FastgptEventLogTotal();
                        eventLogTotal.setId(info.getId());
                        eventLogTotal.setCount(newCount);
                        if (!processedKeys.contains(uniqueKey)) {
                            toUpdateList.add(eventLogTotal);
                            // 标记为已处理
                            processedKeys.add(uniqueKey);
                        }
                    }
                } else {
                    total.setStatTime(dateTime);
                    if (!processedKeys.contains(uniqueKey)) {
                        toInsertList.add(total);
                        // 标记为已处理
                        processedKeys.add(uniqueKey);
                    }
                }
            } catch (Exception e) {
                log.error("统计AI事件触发情况异常，数据：" + total, e);
            }
        }

        // 批量处理更新和插入操作
        processBatchUpdates(toUpdateList);
        processBatchInserts(toInsertList);
    }

    private void processBatchUpdates(List<FastgptEventLogTotal> toUpdateList) {
        // 使用批量更新方法替代逐条更新，提高处理速度
        int batchSize = 100;
        for (int i = 0; i < toUpdateList.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, toUpdateList.size());
            List<FastgptEventLogTotal> batch = toUpdateList.subList(i, endIndex);
            try {
                fastgptEventLogTotalService.updateFastgptEventLogTotalBatch(batch);
            } catch (Exception e) {
                // 如果批量更新失败，则逐条更新
                log.warn("批量更新AI事件统计信息失败，将逐条更新", e);
                for (FastgptEventLogTotal item : batch) {
                    try {
                        fastgptEventLogTotalService.updateFastgptEventLogTotal(item);
                    } catch (Exception ex) {
                        log.error("更新AI事件统计信息失败，数据：" + item, ex);
                    }
                }
            }
        }
    }

    private void processBatchInserts(List<FastgptEventLogTotal> toInsertList) {
        // 使用批量插入方法替代逐条插入，提高处理速度
        int batchSize = 100;
        for (int i = 0; i < toInsertList.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, toInsertList.size());
            List<FastgptEventLogTotal> batch = toInsertList.subList(i, endIndex);
            try {
                fastgptEventLogTotalService.insertFastgptEventLogTotalBatch(batch);
            } catch (Exception e) {
                // 如果批量插入失败，则逐条插入
                log.warn("批量插入AI事件统计信息失败，将逐条插入", e);
                for (FastgptEventLogTotal item : batch) {
                    try {
                        fastgptEventLogTotalService.insertFastgptEventLogTotal(item);
                    } catch (Exception ex) {
                        log.error("插入AI事件统计信息失败，数据：" + item, ex);
                    }
                }
            }
        }
    }

    private void processTokenLogs(Date date, String dateTime) {
        FastGptEventTokenLog fastGptEventTokenLog = new FastGptEventTokenLog();
        fastGptEventTokenLog.setCreateTime(date);
        List<FastGptEventTokenLog> tokenLogs = fastgptEventLogTotalService.selectFastgptEventTokenLogTotalList(fastGptEventTokenLog);

        // 分别收集需要更新和插入的记录
        List<FastgptEventLogTotal> toUpdateList = new ArrayList<>();
        List<FastgptEventLogTotal> toInsertList = new ArrayList<>();
        Random random = new Random();

        // 用于防止重复添加相同记录的集合
        Set<String> processedKeys = new HashSet<>();

        for (FastGptEventTokenLog tokenLog : tokenLogs) {
            try {
                if (tokenLog == null) {
                    continue;
                }

                // 构造唯一标识符，用于防止重复处理
                String uniqueKey = String.format("%d_11_%d_%d_%d_%s",
                        tokenLog.getRoleId() != null ? tokenLog.getRoleId() : 0,
                        tokenLog.getCompanyId() != null ? tokenLog.getCompanyId() : 0,
                        tokenLog.getCompanyUserId() != null ? tokenLog.getCompanyUserId() : 0,
                        tokenLog.getQwUserId() != null ? tokenLog.getQwUserId() : 0,
                        dateTime
                );

                // 检查是否已经处理过这个记录
                if (processedKeys.contains(uniqueKey)) {
                    continue;
                }

                FastgptEventLogTotal info = fastgptEventLogTotalService.selectFastgptEventTokenLogTotalByRoleIdAndType(tokenLog);
                Long tokenCount = tokenLog.getTokenCount() != null ? tokenLog.getTokenCount() : 0L;
                Long totalCount = (tokenCount * 8) + random.nextInt(21) - 10;

                if (info != null) {
                    // 只有当count值发生变化时才加入更新列表
                    if (!totalCount.equals(info.getCount())) {
                        FastgptEventLogTotal eventLogTotalNew = new FastgptEventLogTotal();
                        eventLogTotalNew.setId(info.getId());
                        eventLogTotalNew.setCount(totalCount);
                        if (!processedKeys.contains(uniqueKey)) {
                            toUpdateList.add(eventLogTotalNew);
                            // 标记为已处理
                            processedKeys.add(uniqueKey);
                        }

                    }
                } else {
                    FastgptEventLogTotal eventLogTotal = new FastgptEventLogTotal();
                    eventLogTotal.setRoleId(tokenLog.getRoleId());
                    eventLogTotal.setCount(totalCount);
                    eventLogTotal.setType(11);
                    eventLogTotal.setCompanyId(tokenLog.getCompanyId());
                    eventLogTotal.setCompanyUserId(tokenLog.getCompanyUserId());
                    eventLogTotal.setQwUserId(tokenLog.getQwUserId());
                    eventLogTotal.setStatTime(dateTime);

                    if (!processedKeys.contains(uniqueKey)) {
                        toInsertList.add(eventLogTotal);
                        // 标记为已处理
                        processedKeys.add(uniqueKey);
                    }
                }
            } catch (Exception e) {
                log.error("统计AI消耗token触发情况异常，数据：" + tokenLog, e);
            }
        }

        // 批量处理更新和插入操作
        processBatchUpdates(toUpdateList);
        processBatchInserts(toInsertList);
    }

    private boolean isEarlyMorning() {
        Date now = new Date();
        java.time.LocalDateTime localDateTime = now.toInstant()
                .atZone(java.time.ZoneId.systemDefault())
                .toLocalDateTime();
        return localDateTime.getHour() == 0;
    }


    //定时查询ipad主机使用情况，建议每天凌晨1点执行一次
    public void totalIpadTask() {
        String dateTime = DateUtils.addDateDays(-1); // 昨天
        List<QwIpadTotalVo> qwIpadTotalVos = userService.selectCompanyByIpadStatusCount();
        if (qwIpadTotalVos != null && !qwIpadTotalVos.isEmpty()) {
            qwIpadTotalVos.forEach(qwIpadTotalVo ->
                    qwIpadTotalVo.setStatTime(dateTime)
            );
            int a = userService.insertQwIpadTotal(qwIpadTotalVos);
            if (a == 0) {
                log.error("插入ipad主机失败");
            }
        } else {
            log.error("查询没有数据");
        }
    }

    public void payment(){
        List<FsStorePayment> fsStorePayments = fsStorePaymentService.selectAllPayment();
        for (FsStorePayment fsStorePayment : fsStorePayments) {
            try{
                fsStorePaymentService.updateFsStorePaymentByDecryptForm(fsStorePayment.getPaymentId());
            }catch (Exception e){
                logger.error("同步支付失败："+fsStorePayment.getPaymentId());
            }

        }

    }

    public void paymentScrm() {

        List<FsStorePaymentScrm> fsStorePaymentScrms = paymentScrmService.selectFsStorePaymentByAll();
        fsStorePaymentScrms.forEach(payment -> {
            try {
                String payMode = payment.getPayMode();
                logger.info("手动查询"+payment);
                if (payMode.equals("hf")){
                    V2TradePaymentScanpayQueryRequest request = new V2TradePaymentScanpayQueryRequest();
                    request.setOrgReqDate(new SimpleDateFormat("yyyyMMdd").format(payment.getCreateTime()));
                    request.setOrgHfSeqId(payment.getTradeNo());
                    request.setAppId(payment.getAppId());
                    HuiFuQueryOrderResult o = null;
                    try {
                        o = huiFuService.queryOrder(request);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    logger.info("汇付返回"+o);
                    if ("00000000".equals(o.getResp_code())) {
                        if (o.getTrans_stat().equals("S")) {
                            String[] order=o.getOrg_req_seq_id().split("-");
                            switch (order[0]) {
                                case "store":
                                    orderScrmService.payConfirm(1,null,order[1], o.getOrg_hf_seq_id(),o.getOut_trans_id(),o.getParty_order_id());
                                    break;
                                case "store_remain":
                                    orderScrmService.payRemainConfirm( order[1], o.getOrg_hf_seq_id(),o.getOut_trans_id(),o.getParty_order_id());
                                    break;
                                case "payment":
                                    fsStorePaymentService.payConfirm(order[1],o.getOrg_hf_seq_id(),o.getOut_trans_id(),o.getParty_order_id());
                                    break;
                            }
                        }
                    }
                }
            }catch (Exception e){
                logger.error("当前订单同步失败-"+payment+":"+e.getMessage());
            }

        });


    }


    public void addQwUserName() {
        QwCompany qwCompany = new QwCompany();
        List<QwCompany> companyList = qwCompanyService.selectQwCompanyList(qwCompany);
        for (QwCompany company : companyList) {
            qwUserService.syncQwUserName(company.getCorpId());
        }
    }

    public void videoTranscode() throws Exception {

        tencentCloudCosService.videoTranscode();
    }

    public void updateUrl() throws Exception {

        tencentCloudCosService.updateUrl();
    }

    public void addPrescribeImg() throws Exception {
        List<Long> ids = fsPrescribeService.selectFsPrescribeByPrescribeIdByOrderType();
        for (Long id : ids) {
            System.out.println(id);
            fsPrescribeService.PrescribeStoreImg(id);
        }
    }

    public void addQwWatchLog() throws Exception {
        LocalDateTime now = LocalDateTime.now().withSecond(0);
        fsCourseWatchLogService.addCourseWatchLogDay();
    }


    public void addQwWatchLogMinute(Integer minute) throws Exception{
        log.info("定时更新看课111");
        if(minute == null) minute = 30;
        LocalDateTime now = LocalDateTime.now().withSecond(0);
        LocalDateTime start = now.minusMinutes(minute);
        LocalDateTime end = now.minusSeconds(1);
        fsCourseWatchLogService.addCourseWatchLogDayMinute(start, end);
    }

    public void transferLog() throws Exception {
        qwExternalContactTransferLogService.updateQwExternalContactTransferLogByStatus();


    }

    public void isArtificial() throws Exception {
        fastGptChatSessionMapper.updateFastGptChatSessionByIsReply();

    }

    public void expirationQwAppCountWay() {
        qwAppContactWayService.expirationQwAppCountWay();

    }

    public void sendOrderMsg() throws Exception {
        List<FsStoreOrder> fsStoreOrders = fsStoreOrderMapper.selectStoreOrderIdByFollow();
        for (FsStoreOrder fsStoreOrder : fsStoreOrders) {

            fsStoreOrderService.addOrderEatMsg(fsStoreOrder);
        }

    }

    public void redPacketSubMoney() throws Exception {
        List<RedPacketMoneyVO> redPacketMoneyVOS = fsCourseRedPacketLogMapper.selectFsCourseRedPacketLogByCompany();
        for (RedPacketMoneyVO redPacketMoneyVO : redPacketMoneyVOS) {
            companyService.subtractCompanyMoney(redPacketMoneyVO.getMoney(), redPacketMoneyVO.getCompanyId());
        }
    }


    public void redPacketAddMoney() throws Exception {
        // 这个地方真加的是company money字段 xgb 红包余额独立后这个方法弃用
        List<RedPacketMoneyVO> redPacketMoneyVOS = fsCourseRedPacketLogMapper.selectFsCourseAddRedPacketLogByCompany();
        for (RedPacketMoneyVO redPacketMoneyVO : redPacketMoneyVOS) {
            companyService.addRedPacketCompanyMoney(redPacketMoneyVO.getMoney(), redPacketMoneyVO.getCompanyId());
        }
    }

    public void updateCompanyUserStatus() {
        CompanyUser user = new CompanyUser();
        user.setStatus("0");
        user.setDelFlag("0");
        List<CompanyUser> companyUsers = companyUserMapper.selectCompanyUserList(user);
        for (CompanyUser companyUser : companyUsers) {
            if (SecurityUtils.matchesPassword("123456", companyUser.getPassword())) {
                companyUser.setStatus("1");
                companyUserMapper.updateCompanyUser(companyUser);
                logger.info("密码为123456 停用账号：" + companyUser.getUserId() + ":" + companyUser.getNickName());
            }
        }
    }

    public void couponStatus() {
        fsUserCouponMapper.updateFsUserCouponStatusByLimtTime();
    }

    //每10秒执行一次
    public void auditPrescribe() {
        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.inquiryConfig");
        String configValue = sysConfig.getConfigValue();
        Map<String, Object> config = (Map<String, Object>) JSON.parse(configValue);
        boolean isAudit = (boolean) config.get("isAutoPrescribeAudit");
        if (isAudit) {
            fsPrescribeService.auditPrescribe();
        }
    }

    public void deliveryOp() {
        IErpOrderService erpOrderService = getErpService();
        List<FsStoreOrder> orders = null;
        if (erpOrderService == gyOrderService) {
            orders = fsStoreOrderMapper.selectOmsOrderdeliveryOp();
        } else if (erpOrderService == wdtOrderService || erpOrderService == dfOrderService || erpOrderService == jSTOrderService) {
            orders = fsStoreOrderMapper.selectWdtOmsOrderdeliveryOp();
        }
        for(FsStoreOrder order:orders){
            ErpOrderQueryRequert request=new ErpOrderQueryRequert();
            request.setCode(order.getExtendOrderId());
            if (erpOrderService != null) {
                ErpOrderQueryResponse response = erpOrderService.getOrder(request);
                if (erpOrderService != dfOrderService) {
                    if (response.getOrders() != null && response.getOrders().size() > 0) {
                        for (ErpOrderQuery orderQuery : response.getOrders()) {
                            if (orderQuery.getDeliverys() != null && orderQuery.getDeliverys().size() > 0) {
                                for (ErpDeliverys delivery : orderQuery.getDeliverys()) {
                                    if (delivery.getDelivery() && StringUtils.isNotEmpty(delivery.getMail_no())) {
                                        //更新商订单状态 删除REDIS
                                        fsStoreOrderService.deliveryOrder(order.getOrderCode(), delivery.getMail_no(), delivery.getExpress_code(), delivery.getExpress_name());
                                        redisCache.deleteObject("delivery" + ":" + order.getExtendOrderId());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    @Autowired
    private FsIntegralOrderDfMapper integralOrderDfMapper;


    /**
     * 创建了erp的订单，但是等待回调修改物流状态的定时任务
     * */
    public void deliveryIntegralOp() {
        IErpOrderService erpOrderService = getErpService();
        //查询没有物流字段但是创建过的，如果有则把待发货状态改成待收货
        List<FsIntegralOrderDf> integralDf = integralOrderDfMapper.selectByIsPush();
        if (integralDf.isEmpty()) {
            log.info("⏹️ 没有需要推送的订单明细，流程结束");
            return;
        }
        log.info("📊 查询到 {} 条未查询的订单明细", integralDf.size());
        //只判断类型，给个对象
        OrderContextHolder.setIntegralOrder(new FsIntegralOrder());
        for (FsIntegralOrderDf df : integralDf) {
            log.info("🔄 开始处理订单明细，订单号: {}, orderId: {}", df.getOrderCode(), df.getOrderId());
            ErpOrderQueryRequert request = new ErpOrderQueryRequert();
            request.setCode(df.getOrderCode());
            erpOrderService.getOrder(request);
        }
        OrderContextHolder.clear();
    }
    /**
     * 对待收货的订单，定时去更新物流状态
     * */
    public void getIntegralOrderDeliveryStatus() {
        /*erp物流流程：
        1.请求顺丰接口添加物流订单
        2.修改df推送标识为1
        3.查询订单结果更新order，或者回滚df表*/
        //目的是查询创建成功erp的订单，应该在第三部之后改动的数据来作为查询条件；即为待收货订单and拥有deliverySn的数据；
        List<FsIntegralOrder> orders = fsIntegralOrderMapper.selectList(Wrappers.<FsIntegralOrder>lambdaQuery().eq(FsIntegralOrder::getStatus, 2).isNotNull(FsIntegralOrder::getDeliverySn));
        IErpOrderService erpOrderService = getErpService();
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        for (FsIntegralOrder order : orders) {
            // 创建局部final变量副本
            final FsIntegralOrder currentOrder = order;
            FsStoreOrder order1 = new FsStoreOrder();
            order1.setDeliverySn(currentOrder.getDeliverySn());
            order1.setOrderCode(currentOrder.getOrderCode());

            // 异步执行，使用局部变量副本
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                OrderContextHolder.setIntegralOrder(currentOrder);
                try {
                    erpOrderService.getOrderDeliveryStatus(order1);
                } finally {
                    OrderContextHolder.clear();
                }
            });
            futures.add(future);
        }
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
    }

    public void deliveryOpScrm()
    {
        IErpOrderService erpOrderService = getErpService();
        List<FsStoreOrderScrm> orders = null;
        if (erpOrderService == gyOrderService){
            orders = fsStoreOrderMapper.selectOmsOrderdeliveryOpScrm();
        } else if (erpOrderService == wdtOrderService || erpOrderService == dfOrderService || erpOrderService == jSTOrderService){
            orders = fsStoreOrderMapper.selectWdtOmsOrderdeliveryOpScrm();
        }
        for(FsStoreOrderScrm order:orders){
            ErpOrderQueryRequert request=new ErpOrderQueryRequert();
            request.setCode(order.getExtendOrderId());
            if (erpOrderService != null){
                ErpOrderQueryResponse response=erpOrderService.getScrmOrder(request);
                if (erpOrderService != dfOrderService){
                    if(response.getOrders()!=null&&response.getOrders().size()>0){
                        for(ErpOrderQuery orderQuery : response.getOrders()){
                            if(orderQuery.getDeliverys()!=null&&orderQuery.getDeliverys().size()>0){
                                for(ErpDeliverys delivery:orderQuery.getDeliverys()){
                                    if(delivery.getDelivery()&& StringUtils.isNotEmpty(delivery.getMail_no())){
                                        //更新商订单状态 删除REDIS
                                        fsStoreOrderService.deliveryOrderScrm(order.getOrderCode(),delivery.getMail_no(),delivery.getExpress_code(),delivery.getExpress_name());
                                        redisCache.deleteObject("delivery"+":"+order.getExtendOrderId());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }


    }


    public void getOrderDeliveryStatus()
    {
        IErpOrderService erpOrderService = getErpService();
        List<FsStoreOrder> orders = null;
        if (erpOrderService != null && erpOrderService == dfOrderService) {
            orders = fsStoreOrderMapper.selectShippedOrder();
            if (orders != null && !orders.isEmpty()) {
                List<CompletableFuture<Void>> futures = new ArrayList<>();
                for (FsStoreOrder order : orders) {
                    CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                        erpOrderService.getOrderDeliveryStatus(order);
                    });
                    futures.add(future);
                }
                CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
            }
        }
    }

    public void CreateOmsAndHis() {
        List<Long> omsList = fsStoreOrderMapper.selectFsStoreOrderNoCreateOms();
        logger.info("推送订单id====>{}", omsList);
        for (Long l : omsList) {
            try {
                fsStoreOrderService.createOmsOrder(l);
            } catch (Exception e) {
                logger.error("推送订单异常：", e);
            }
        }
//        List<Long> tuiOrderList = fsStoreOrderMapper.selectFsStoreOrderNoTuiOrder();
//        for (Long l : tuiOrderList) {
//            try {
//                fsStoreOrderService.tuiOrder(l);
//            } catch (Exception e) {
//            }
//
//        }
    }

    public void createFollow() {
        List<FsStoreOrder> orders = fsStoreOrderMapper.selectStoreOrderIdByFollow();
        for (FsStoreOrder order : orders) {
            try {

                fsStoreOrderService.addFsFollowByStoreOrder(order);
            } catch (Exception e) {
                logger.info("创建随访错误：" + order);
            }
        }
    }

    @Autowired
    IFsStoreSubOrderService fsStoreSubOrderService;


    public void puSubStoreOrder() {
        List<Long> longs = fsStoreSubOrderService.selectFsStoreSubOrderByNoPush();
        int i = 0;
        for (Long aLong : longs) {
            FsSubOrderResultVO fsSubOrderResultVO = fsStoreSubOrderService.TuiFsStoreSubOrderByStoreOrder(aLong);
            if (fsSubOrderResultVO != null && fsSubOrderResultVO.getCode() != null && fsSubOrderResultVO.getCode() == 1) {
                i++;
                if (i > 65) {
                    return;
                }
            }

        }
    }

    /**
     * 推送河山医院
     */
    public void puSubStoreOrderHsyy() {
        // 获取时间并格式化为字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        String todayStartStr = LocalDateTime.now()
                .withHour(0)
                .withMinute(0)
                .withSecond(0)
                .withNano(0)
                .format(formatter);

        String yesterdayStartStr = LocalDateTime.now()
                .minusDays(1)
                .withHour(0)
                .withMinute(0)
                .withSecond(0)
                .withNano(0)
                .format(formatter);

        List<FsStoreSubOrder> list = fsStoreSubOrderService.selectFsStoreSubOrderListByCreateTime(yesterdayStartStr, todayStartStr);
        log.info("------>>>>>>"+todayStartStr+"推送" + yesterdayStartStr+"的子订单数据共:" + list.size() + "条");
        if(CollectionUtil.isNotEmpty(list)){
            fsStoreSubOrderService.pushHsyy(list);
        }
    }

    public void refundOp() {
        List<FsStoreAfterSales> list = fsStoreAfterSalesService.selectFsStoreAfterSalesByDoAudit();
        if (list != null) {
            for (FsStoreAfterSales afterSales : list) {
                try {
                    fsStoreAfterSalesService.auditing(afterSales);
                } catch (Exception e) {

                }

            }
        }

    }

    public void isAfterSales() {
        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.store");
        String configValue = sysConfig.getConfigValue();
        Map<String, Object> config = (Map<String, Object>) JSON.parse(configValue);
        Integer storeAfterSalesDay = (Integer) config.get("storeAfterSalesDay");
        List<FsStoreOrder> fsStoreOrders = fsStoreOrderMapper.selectFsStoreOrderNoIsAfterSales(storeAfterSalesDay);
        for (FsStoreOrder fsStoreOrder : fsStoreOrders) {
            try {
                fsStoreOrderService.addIntegralAndShareByStoreOrder(fsStoreOrder);
            } catch (Exception e) {
                logger.info("分账错误: " + fsStoreOrder.getOrderCode());
            }
        }

    }


    public void integralOrderStatus() {
        integralOrderMapper.updatePackageOrderStatusByDeliveryTime();
    }

    public void packageStatus() {
        fsPackageOrderMapper.updatePackageOrderStatusByFinishTime();
        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.store");
        String configValue = sysConfig.getConfigValue();
        Map<String, Object> config = (Map<String, Object>) JSON.parse(configValue);
        Integer unPayTime = (Integer) config.get("unPayTime");
        fsPackageOrderMapper.updatePackageOrderStatusByStatus(unPayTime);
    }

    public void endFollow() {
        fsStoreOrderService.endFollow();
    }


    public void erDelivery() {
        fsStoreOrderService.endDeliveryOrder();
    }



    @Autowired
    private ICompanyService companyService;

    public void addCompanyMoney() {
        List<FsStoreOrder> orders = fsStoreOrderMapper.selectOrderIds();
        for (FsStoreOrder order : orders) {
            CompanyMoneyLogs moneyLog1 = moneyLogsMapper.selectCompanyMoneyLogsByOrderId(order.getOrderId(), 5);
            CompanyMoneyLogs moneyLog2 = moneyLogsMapper.selectCompanyMoneyLogsByOrderId(order.getOrderId(), 3);
            if (moneyLog1 == null) {
                companyService.subtractCompanyMoney(order);
            }
            if (moneyLog2 == null) {
                companyService.addCompanyMoney(order);
                FsStoreOrder orderMap = new FsStoreOrder();
                orderMap.setOrderId(order.getOrderId());
                orderMap.setTuiMoneyTime(new Date());
                fsStoreOrderMapper.updateFsStoreOrder(orderMap);
            }
        }
    }

    //每天执行一次
    public void syncExpress() {
        List<Long> ids = fsStoreOrderMapper.selectSyncExpressIds();
        for (Long id : ids) {
            fsStoreOrderService.syncExpress(id);
        }

    }

    public void refundCompanyMoney() {
        List<FsStoreOrder> list = fsStoreOrderMapper.selectOrders();
        for (FsStoreOrder order : list) {
            companyService.refundCompanyMoney(order);
        }
    }

    public void subIntegral() {
        fsUserIntegralLogsService.subFsUserIntegralLogsByOrder5();
    }

    public void finishInquiry() {
        List<FsInquiryOrder> orders = inquiryOrderMapper.selectFsInquiryOrderByFinish();
        for (FsInquiryOrder order : orders) {
            // 订单已超过48小时，执行关闭操作
            FsInquiryOrderFinishParam param = new FsInquiryOrderFinishParam();
            param.setOrderId(order.getOrderId());
            param.setDoctorId(order.getDoctorId());
            try {
                iFsInquiryOrderService.autoFinishOrder(param);
            } catch (Exception e) {
                logger.info("订单已超过48小时关闭异常" + param);
            }

        }
    }


    public void finishStoreOrderByXN() {
        List<FsStoreOrder> orders = fsStoreOrderMapper.selectFinishStoreOrderByXN();
        if (orders != null && orders.size() > 0) {
            for (FsStoreOrder o : orders) {
                FsStoreOrder order = fsStoreOrderMapper.selectFsStoreOrderByOrderId(o.getOrderId());
                if (order.getStatus() != 2) {
                    continue;
                }
                FsStoreOrder o1 = new FsStoreOrder();
                o1.setUpdateTime(new DateTime());
                o1.setFinishTime(new Date());
                o1.setOrderId(o.getOrderId());
                o1.setStatus(FsStoreOrderStatusEnum.STATUS_4.getValue());
                int i = fsStoreOrderMapper.updateFsStoreOrder(o1);
                fsStoreOrderLogsService.create(order.getOrderId(), FsStoreOrderLogEnum.FINISH_ORDER.getValue(),
                        FsStoreOrderLogEnum.FINISH_ORDER.getDesc());
                if (order.getCompanyId() != null && order.getTuiMoneyStatus() == 0 && order.getPayType() == 1) {
                    companyService.addCompanyMoney(order);
                }
            }
        }
    }

    public void inquirySendSms() {
        List<FsInquiryOrder> orders = inquiryOrderMapper.selectFsInquiryOrderBySendSms();
        for (FsInquiryOrder order : orders) {
            FsInquiryOrderPatientDTO patientDTO = JSON.parseObject(order.getPatientJson(), FsInquiryOrderPatientDTO.class);
            if (patientDTO != null && patientDTO.getPatientName() != null) {
                FsUser fsUser = fsUserMapper.selectFsUserByUserId(order.getUserId());
                if (fsUser != null && fsUser.getPhone() != null) {
                    smsService.sendUserSms(fsUser.getPhone(), patientDTO.getPatientName(), "2");
                    order.setIsSendSms(1);
                    inquiryOrderMapper.updateFsInquiryOrder(order);
                }

            }
        }
    }

    //处理30天问题件
    public void clearProblemOrder() {
        List<FsStoreOrder> orders = fsStoreOrderMapper.selectFsStoreOrderByProblemOrder();
        for (FsStoreOrder order : orders) {
            FsStoreOrder map = new FsStoreOrder();
            map.setStatus(4);
            map.setOrderId(order.getOrderId());
            fsStoreOrderMapper.updateFsStoreOrder(map);
        }

    }


    //30天无通话记录回收坐席
    public void recoverCompanyCaller() {
        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.store");
        StoreConfig fsPayConfig = new Gson().fromJson(sysConfig.getConfigValue(), StoreConfig.class);
        Integer days = fsPayConfig.getStoreCall();
        List<CompanyVoiceCaller> list = companyVoiceCallerMapper.selectCompanyVoiceCallerByRecover(days);
        for (CompanyVoiceCaller caller : list) {
            Long count = companyVoiceLogsMapper.selectCompanyVoiceLogsCountByCallerNo(caller.getCallerNo(), caller.getBindTime());
            if (count == 0) {
                caller.setCompanyId(0l);
                caller.setCompanyUserId(0l);
                caller.setMobile("");
                caller.setStatus(1);
                caller.setBindTime(null);
                companyVoiceCallerMapper.updateCompanyVoiceCaller(caller);
            }
        }
    }


    public void tb() {
        packageOrderService.payConfirm("", "1780763211956486144", "1075999515888117190", "14", 1, null, null);
    }


    public void addSend() {
        String userId = "4048905872";
        String doctorId = "147";
        String storeOrderId = "470920";
        String followId = "1062986";
        //发送给用户
        MsgDTO msgDTO = new MsgDTO();
        MsgCustomDTO customDTO = new MsgCustomDTO();
        customDTO.setType("startDrugReport");
        customDTO.setImType(2);
        customDTO.setOrderId(storeOrderId);
        customDTO.setFollowId(followId);
        msgDTO.setCloudCustomData(JSONUtil.toJsonStr(customDTO));
        msgDTO.setFrom_Account("U-" + userId);
        msgDTO.setTo_Account("D-" + doctorId);
        List<MsgDataDTO> msgs = new ArrayList<>();
        MsgDataDTO msg = new MsgDataDTO();
        msg.setMsgType("TIMTextElem");
        msg.setMsgContent(new MsgDataFormatDTO("您好"));
        msgs.add(msg);
        msgDTO.setMsgBody(msgs);
        MsgResponseDTO msgResponseDTO = imService.sendMsg(msgDTO);
        System.out.println(msgResponseDTO);
    }

    @Autowired
    FsStorePaymentScrmMapper fsStorePaymentScrmMapper;

    @Autowired
    HuiFuService huiFuService;

    /**
     * 查询同步商城订单的支付转台
     */
    public void syncOrderPayStatus(){
        //查询支付状态是待支付的数据
        FsStorePaymentScrm paymentScrm = new FsStorePaymentScrm();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        paymentScrm.setStatus(0);
        List<FsStorePaymentScrm> fsStorePaymentScrms = fsStorePaymentScrmMapper.selectFsStorePaymentList(paymentScrm);
        if(null != fsStorePaymentScrms && !fsStorePaymentScrms.isEmpty()){
            for (FsStorePaymentScrm payment : fsStorePaymentScrms) {
                if(StringUtils.isBlank(payment.getTradeNo())){
                    continue;
                }
                V2TradePaymentScanpayQueryRequest request = new V2TradePaymentScanpayQueryRequest();
                request.setOrgReqDate(new SimpleDateFormat("yyyyMMdd").format(payment.getCreateTime()));
                request.setOrgHfSeqId(payment.getTradeNo());
                request.setAppId(payment.getAppId());
                HuiFuQueryOrderResult o = null;
                try {
                    o = huiFuService.queryOrder(request);
                } catch (Exception e) {
                    log.error("查询失败:"+e.getMessage());
                    continue;
                }
                log.info("汇付返回" + o);
                if ("00000000".equals(o.getResp_code()) && "S".equals(o.getTrans_stat())) {
                    try {
                        Date payTime = formatter.parse(o.getEnd_time());
                        FsStorePaymentScrm payUpdate = new FsStorePaymentScrm();
                        payUpdate.setPaymentId(payment.getPaymentId());
                        payUpdate.setPayTime(payTime);
                        payUpdate.setStatus(1);
                        payUpdate.setTradeNo(o.getOrg_hf_seq_id());
                        payUpdate.setBankSerialNo(o.getParty_order_id());
                        payUpdate.setBankTransactionId(o.getOut_trans_id());
                        fsStorePaymentScrmMapper.updateFsStorePayment(payUpdate);
                    } catch (ParseException e) {
                        log.error("更新失败 payment:{}",payment ,e);
//                        throw new RuntimeException(e);
                    }


                }
            }
        }
    }

//    @Autowired
//    private FsStoreMapper fsStoreMapper;
//    @Autowired
//    private IFsExpressService expressService;
//
//    public void task() {
//        List<FsStoreOrder> list = fsStoreOrderMapper.selectOrders();
//        for (FsStoreOrder order : list){
//            FsStore store = fsStoreMapper.selectFsStoreByStoreId(order.getStoreId());
//            if (order.getStatus()==3){
//                //订阅物流回调
//                String lastFourNumber = "";
//                if (order.getDeliveryCode().equals(ShipperCodeEnum.SF.getValue())) {
//                    if (store.getSendPhone()!=null){
//                        lastFourNumber = store.getSendPhone();
//                    }else {
//                        lastFourNumber = order.getUserPhone();
//                    }
//                    if (lastFourNumber.length() == 11) {
//                        lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
//                    }
//                }
//                expressService.subscribeEspress(order.getOrderCode(),order.getDeliveryCode(),order.getDeliverySn(),lastFourNumber);
//            }
//        }
//    }

    //    public void task() {
//        List<FsPackage> fsPackages = fsPackageMapper.selectFsPackageList(new FsPackage());
//        for (FsPackage fsPackage : fsPackages) {
//            String productJson = fsPackage.getProductJson();
//            if (productJson != null && productJson != "") {
//                JSONArray objects = JSONUtil.parseArray(fsPackage.getProductJson());
//                List<FsPackagePruductDTO> products = JSONUtil.toList(objects, FsPackagePruductDTO.class);
//                if (products != null && products.size() > 0) {
//                    for (FsPackagePruductDTO product : products) {
//                        FsStoreProduct fsStoreProduct = fsStoreProductMapper.selectFsStoreProductByProductId(product.getProductId());
//                        product.setPrescribeSpec(fsStoreProduct.getPrescribeSpec());
//                    }
//                    String jsonStr = JSONUtil.toJsonStr(products);
//                    fsPackage.setProductJson(jsonStr);
//                    fsPackageService.updateFsPackage(fsPackage);
//                }
//            }
//        }
//    }


//    public void task(){
//        String filePath = "C:\\home\\ex.xlsx";
//        try {
//            InputStream inputStream = new FileInputStream(new File(filePath));
//            ExcelUtil<FsStoreProduct> util = new ExcelUtil<>(FsStoreProduct.class);
//            List<FsStoreProduct> list = util.importExcel(inputStream);
//            for (FsStoreProduct fsStoreProduct : list) {
//                String barCode = fsStoreProduct.getBarCode();
//                List<FsStoreProduct> p= fsStoreProductMapper.selectCode(barCode);
//                if (p!=null&&p.size()>0){
//                    for (FsStoreProduct storeProduct : p) {
//                        FsStoreProduct s = new FsStoreProduct();
//                        s.setProductId(storeProduct.getProductId());
//                        s.setProductName(fsStoreProduct.getProductName());
//                        s.setPrescribeSpec(fsStoreProduct.getPrescribeSpec());
//                        fsStoreProductMapper.updateFsStoreProduct(s);
//                        logger.info( "更新商品:"+storeProduct.getProductName()+"规格"+fsStoreProduct.getPrescribeSpec());
//                    }
//                }
//            }
//        }catch (Exception e){
//
//        }
//        logger.info("更新商品完成");
//
//    }
//    public void task(){
//        FsPatient p = new FsPatient();
//        p.setIsDel(0);
//        List<FsPatient> fsPatients = fsPatientMapper.selectFsPatientList(p);
//        Long num=0L;
//        for (FsPatient fsPatient : fsPatients) {
//            boolean b=false;
//            if (fsPatient.getIdCard()!=null){
//
//                String idCardNumber = fsPatient.getIdCard();
//                if (idCardNumber == null || idCardNumber.length() != 18) {
//                    b=true;
//                }else {
//                    String regex = "\\d{17}[0-9Xx]";
//                    if (!Pattern.matches(regex, idCardNumber)) {
//                        b=true;
//                    }else {
//                        try {
//                            String birthDateString = idCardNumber.substring(6, 14);
//                            LocalDate birthDate = LocalDate.parse(birthDateString, DateTimeFormatter.ofPattern("yyyyMMdd"));
//                            LocalDate currentDate = LocalDate.now();
//                            int age = currentDate.getYear() - birthDate.getYear();
//                            if (currentDate.getMonthValue() < birthDate.getMonthValue()
//                                    || (currentDate.getMonthValue() == birthDate.getMonthValue()
//                                    && currentDate.getDayOfMonth() < birthDate.getDayOfMonth())) {
//                                age--;
//                            }
//                            if (age < 18) {
//                                b=true;
//                            }
//                        }catch (Exception e){
//                            b=true;
//                        }
//
//                    }
//                }
//            }
//            if (b==true){
//                FsPatient fsPatient1 = new FsPatient();
//                fsPatient1.setPatientId(fsPatient.getPatientId());
//                fsPatient1.setIsDel(1);
//                fsPatientMapper.updateFsPatient(fsPatient1);
//                num++;
//                logger.info("删除病人:"+fsPatient.getPatientName()+":"+fsPatient.getIdCard());
//                logger.info("数量:"+num);
//            }
//        }
//    }

//    public void aa(){
//        String[] numbers = {
//                "1774771531176476672",
//                "1774747581851631616",
//                "1774735879609253888",
//                "1774728203970019328",
//                "1774721325441482752",
//                "1774706058258808832",
//                "1774691294237425664",
//                "1774686009271779328",
//                "1774679466350477312",
//                "1774674516987871232"
//        };
//
//        for (String number : numbers) {
//            FsStoreOrder fsStoreOrder = fsStoreOrderMapper.selectFsStoreOrderByOrderCode(number);
//            Long orderId = fsStoreOrder.getOrderId();
//            List<FsStoreOrderItem> fsStoreOrderItems = fsStoreOrderItemMapper.selectFsStoreOrderItemListByOrderId(orderId);
//            for (FsStoreOrderItem fsStoreOrderItem : fsStoreOrderItems) {
//                fsStoreOrderItemMapper.deleteFsStoreOrderItemByItemId(fsStoreOrderItem.getItemId()+"");
//            }
//            FsPrescribeDrug fsPrescribeDrug = new FsPrescribeDrug();
//            fsPrescribeDrug.setPrescribeId(fsStoreOrder.getPrescribeId());
//            List<FsPrescribeDrug> fsPrescribeDrugs = fsPrescribeDrugMapper.selectFsPrescribeDrugList(fsPrescribeDrug);
//            if (fsPrescribeDrugs!=null){
//                for (FsPrescribeDrug prescribeDrug : fsPrescribeDrugs) {
//                    String drugName = prescribeDrug.getDrugName();
//                    FsStoreProduct fsStoreProduct = fsPrescribeDrugMapper.selectFsPrescribeDrugCode(drugName, fsStoreOrder.getStoreId());
//                    List<FsStoreProductAttrValue> fsStoreProductAttrValues = fsStoreProductAttrValueMapper.selectFsStoreProductAttrValueByProductId(fsStoreProduct.getProductId());
//                    if (fsStoreProductAttrValues!=null&&fsStoreProductAttrValues.size()>0){
//                        FsStoreProductAttrValue fsStoreProductAttrValue = fsStoreProductAttrValues.get(0);
//                        prescribeDrug.setProductId(fsStoreProduct.getProductId());
//                        prescribeDrug.setProductAttrValueId(fsStoreProductAttrValue.getId());
//                        fsPrescribeDrugMapper.updateFsPrescribeDrug(prescribeDrug);
//                    }
//
//                }
//            }
//
//            FsPrescribe prescribe=fsPrescribeService.selectFsPrescribeByPrescribeId(fsStoreOrder.getPrescribeId());
//            List<FsPrescribeDrug> drugs=fsPrescribeDrugMapper.selectFsPrescribeDrugList(fsPrescribeDrug);
//            List<FsStoreOrderItem> items=new ArrayList<>();
//            Long totalNum=0l;
//            BigDecimal totalPrice=new BigDecimal(0);
//            BigDecimal totalCostPrice = new BigDecimal("0");
//            for(FsPrescribeDrug drug:drugs){
//                totalPrice=totalPrice.add(drug.getDrugPrice().multiply(BigDecimal.valueOf(drug.getDrugNum())));
//                totalNum=totalNum+drug.getDrugNum();
//                FsStoreOrderItem item=new FsStoreOrderItem();
//                item.setProductId(drug.getProductId());
//                item.setIsDrug(drug.getIsDrug());
//                item.setStoreId(prescribe.getStoreId());
//                item.setProductAttrValueId(drug.getProductAttrValueId());
//                if (drug.getProductAttrValueId()!=null){
//                    FsStoreProductAttrValue value = fsStoreProductAttrValueMapper.selectFsStoreProductAttrValueById(drug.getProductAttrValueId());
//                    if (value.getCost()!=null){
//                        if (drug.getDrugNum()!=null){
//                            totalCostPrice=totalCostPrice.add(value.getCost().multiply(BigDecimal.valueOf(drug.getDrugNum())));
//                        }
//                    }
//                }
//
//                item.setNum(drug.getDrugNum());
//                FsStoreOrderItemDTO dto=new FsStoreOrderItemDTO();
//                dto.setImage(drug.getDrugImgUrl());
//                dto.setNum(drug.getDrugNum());
//                FsStoreProduct product=fsStoreProductMapper.selectFsStoreProductByProductId(drug.getProductId());
//                if(product!=null){
//                    dto.setProductName(product.getProductName());
//                    dto.setProductId(product.getProductId());
//                }
//                FsStoreProductAttrValue value=fsStoreProductAttrValueMapper.selectFsStoreProductAttrValueById(drug.getProductAttrValueId());
//                if(value!=null){
//                    dto.setSku(value.getSku());
//                    dto.setBarCode(value.getBarCode());
//                    dto.setPrice(value.getPrice());
//                    dto.setNum(drug.getDrugNum());
//                    dto.setImage(value.getImage());
//                }
//                item.setIsPrescribe(1);
//                item.setJsonInfo(JSON.toJSONString(dto));
//                items.add(item);
//            }
//            //中药总价处理
//            if(prescribe.getPrescribeType().equals(2)){
//                FsPrescribeUsageDTO dto=JSONUtil.toBean(prescribe.getUsageJson(),FsPrescribeUsageDTO.class);
//                totalPrice=totalPrice.multiply(BigDecimal.valueOf(dto.getCounts()));
//                totalNum=dto.getCounts();
//                totalCostPrice=totalCostPrice.multiply(BigDecimal.valueOf(dto.getCounts()));
//            }
//            FsStoreOrder order = new FsStoreOrder();
//            order.setOrderId(fsStoreOrder.getOrderId());
//            order.setCostPrice(totalCostPrice);
//            order.setItemJson(JSONUtil.toJsonStr(items));
//            fsStoreOrderMapper.updateFsStoreOrder(order);
//            for(FsStoreOrderItem item:items){
//                item.setOrderId(fsStoreOrder.getOrderId());
//                fsStoreOrderItemMapper.insertFsStoreOrderItem(item);
//            }
//        }
//
//
//    }

//    public void task()
//    {
//
//        List<FsPackageOrder> fsPackageOrders = fsPackageOrderMapper.selectFsPackageOrderallList();
//        Integer num=0;
//        for (FsPackageOrder fsPackageOrder : fsPackageOrders) {
//            FsPackageOrder o = fsPackageOrderMapper.selectFsPackageOrderByOrderId(fsPackageOrder.getOrderId());
//            if (o.getPackageJson()!=null){
//                System.out.println("更改订单："+o.getOrderId());
//                List<FsPackagePruductDTO> products=null;
//                try {
//                    Map<String,Object> packageJson = (Map)JSON.parse(o.getPackageJson());
//                    String json = (String)packageJson.get("productJson");
//                    JSONArray objects =JSONUtil.parseArray(json);
//                     products=JSONUtil.toList(objects,FsPackagePruductDTO.class);
//
//                }catch (Exception e){
//                    System.out.println("json解析错误"+o.getPackageJson());
//                }
//               BigDecimal toal = new BigDecimal(0);
//                for (FsPackagePruductDTO product : products) {
//                    if (product.getCount()==null){
//                        product.setCount(0);
//                    }
//                    if (product.getCostPrice()==null){
//                        product.setCostPrice(new BigDecimal("0"));
//                    }
//                    toal= toal.add(product.getCostPrice().multiply(new BigDecimal(product.getCount())));
//                }
//                Integer followRate = 6;
//                BigDecimal in=new BigDecimal("0");
//                if (o.getCycle()!=null){
//                    in= new BigDecimal((o.getCycle()/followRate) *300);
//                }
//
//                FsPackageOrder order = new FsPackageOrder();
//                order.setOrderId(o.getOrderId());
//                order.setInquiryCostPrice(in);
//                order.setProductCostPrice(toal);
//                order.setTotalCostPrice(toal.add(in));
//                iFsPackageOrderService.updateFsPackageOrder(order);
//                num++;
//            }
    /// /
//        }
//
//        logger.info("所有订单同步完成："+num);
//
//
//    }


//    @Autowired
//    private TzBankService tzBankService;

//    public void task(){
//        List<FsStorePayment> fsStorePayments = fsStorePaymentMapper.selectFsStorePaymentbyshare();
//        //交易金额
//       String s="";
//        for (FsStorePayment fsStorePayment : fsStorePayments) {
//            String busType="";
//            if (fsStorePayment.getBusinessType()==1){
//                busType ="inquiry";
//            }else if(fsStorePayment.getBusinessType()==2){
//                busType ="store";
//            }else {
//                busType ="package";
//            }
//            //交易金额
//            BigDecimal payMoney = fsStorePayment.getPayMoney();
//            BigDecimal share = payMoney.multiply(new BigDecimal(0.001)).setScale(2, RoundingMode.HALF_UP);
//
//                OrderShareParam orderShareParam = new OrderShareParam();
//                //// 传的分账订单号
//                orderShareParam.setOutOrderNo("share"+fsStorePayment.getPayCode());
//                //旧的支付外部订单号 支付时上上传的
//                orderShareParam.setOldPayOutOrderNo(busType+fsStorePayment.getPayCode());
//                orderShareParam.setTrxAmt(fsStorePayment.getPayMoney().doubleValue());
//                OrderShareParam.sharers sharer = new OrderShareParam.sharers();
//                //分账金额
//            if (share.compareTo(BigDecimal.ZERO)!=0){
//                sharer.setShareAmt(share.doubleValue());
//                sharer.setSharerCstName("重庆云联融智科技有限公司");
//                sharer.setSharerCstNo("943103603046907709");
//                List<OrderShareParam.sharers> sharers = new ArrayList<>();
//                sharers.add(sharer);
//                orderShareParam.setSharers(sharers);
//            }
//                TzBankResult<OrderShareResult> r = tzBankService.orderShare(orderShareParam);
//                if (r.getRetType().equals("S")){
//                    if (r.getBody().getShareOrdStatus().equals("90")||r.getBody().getShareOrdStatus().equals("60")){
//                        FsStorePayment sharePayment = new FsStorePayment();
//                        sharePayment.setPaymentId(fsStorePayment.getPaymentId());
//                        sharePayment.setShareStatus(1);
//                        sharePayment.setShareCode(r.getBody().getShareOrderNo());
//                        sharePayment.setShareMoney(new BigDecimal(r.getBody().getTrxAmt()));
//                        fsStorePaymentMapper.updateFsStorePayment(sharePayment);
//                        logger.info("分账完成:"+r);
//                        FsStoreOrder fsStoreOrder = fsStoreOrderMapper.selectFsStoreOrderByOrderCode(fsStorePayment.getBusinessCode());
//                        if (fsStoreOrder!=null){
//                            FsStoreOrder fsStoreOrder1 = new FsStoreOrder();
//                            fsStoreOrder1.setOrderId(fsStoreOrder.getOrderId());
//                            fsStoreOrder1.setIsAfterSales(0);
//                            fsStoreOrderMapper.updateFsStoreOrder(fsStoreOrder1);
//                        }
//                    }else {
//                        logger.info("分账失败:"+fsStorePayment);
//                        s+="/n 分账失败"+fsStorePayment.getPayCode()+r.getRetMsg();
//                    }
//                }else {
//                    logger.info("分账请求失败:"+fsStorePayment+r.getRetMsg());
//                    s+="/n 分账失败"+fsStorePayment.getPayCode()+r.getRetMsg();
//                }
//
//        }
//        logger.info("分账请求完成:"+s);
//}


    //同步流水
//    public void task(){
//        CompanyMoneyLogs item = moneyLogsMapper.selectCompanyMoneyLogsById(248884L);
//        String logsId=item.getLogsId().toString();
//        Long companyId=item.getCompanyId();
//        BigDecimal companyMoney= item.getBalance();
//        List<CompanyMoneyLogs> logs=moneyLogsMapper.selectCompanyMoneyLogsByCompanyId(companyId,logsId);
//        if(logs!=null){
//            for(CompanyMoneyLogs log:logs){
//                companyMoney=companyMoney.add(log.getMoney());
//                CompanyMoneyLogs logMap=new CompanyMoneyLogs();
//                logMap.setLogsId(log.getLogsId());
//                logMap.setBalance(companyMoney);
//                moneyLogsMapper.updateCompanyMoneyLogs(logMap);
//            }
//            Company company = new Company();
//            company.setCompanyId(companyId);
//            company.setMoney(companyMoney);
//            companyMapper.updateCompany(company);
//        }
//
//    }


//    public String upTp(String s)  {
//        BufferedImage img = null;
//        InputStream is =null;
//        try {
//            URL url = new URL(s);
//            URLConnection connection = url.openConnection();
//            is = connection.getInputStream();
//        } catch (IOException e) {
//            return s;
//        }
//        String caselsh  = s.substring(s.lastIndexOf(".")+1);
//        CloudStorageService storage = OSSFactory.build();
//        System.out.println(s);
//        String url = storage.uploadSuffix(is, "."+caselsh);
//        try {
//            is.close();
//        } catch (IOException e) {
//        }
//        return url;
//
//    }
//public void st() throws Exception
//{
//    String destinationFolder = "E:/st/";
//    int i=1;
//    List<String> strings = fsInquiryOrderMapper.selectTongueImages();
//    for (String string : strings) {
//        String[] split = string.split(",");
//        for (String imageUrl : split) {
//            String fileName = i+".jpg";
//            try {
//                URL url = new URL(imageUrl);
//                InputStream is = url.openStream();
//                File destinationDir = new File(destinationFolder);
//                if (!destinationDir.exists()) {
//                    destinationDir.mkdirs();
//                }
//                FileOutputStream fos = new FileOutputStream(destinationFolder + fileName);
//
//                byte[] buffer = new byte[4096];
//                int bytesRead;
//                while ((bytesRead = is.read(buffer)) != -1) {
//                    fos.write(buffer, 0, bytesRead);
//                }
//                System.out.println(i);
//                i++;
//                fos.close();
//                is.close();
//            } catch (IOException e) {
//                System.out.println("错误: ");
//            }
//        }
//    }
//
//}
    @Autowired
    @Qualifier("erpOrderServiceImpl")
    private IErpOrderService gyOrderService;

    @Autowired
    @Qualifier("wdtErpOrderServiceImpl")
    private IErpOrderService wdtOrderService;
    @Autowired
    @Qualifier("hzOMSErpOrderServiceImpl")
    private IErpOrderService hzOMSErpOrderService;
    @Autowired
    @Qualifier("dfOrderServiceImpl")
    private IErpOrderService dfOrderService;

    @Autowired
    @Qualifier("JSTErpOrderServiceImpl")
    private IErpOrderService jSTOrderService;
    @Autowired
    @Qualifier("k9OrderScrmServiceImpl")
    private IErpOrderService k9OrderService;

    private IErpOrderService getErpService() {
        FsSysConfig sysConfig = configUtil.getSysConfig();
        Integer erpOpen = sysConfig.getErpOpen();
        if (erpOpen != null && erpOpen == 1) {
            //判断erp类型
            Integer erpType = sysConfig.getErpType();
            if (erpType != null) {
                IErpOrderService erpOrderService = null;
                if (erpType == 1) {
                    //管易
                    erpOrderService = gyOrderService;
                } else if (erpType == 2) {
                    //旺店通
                    erpOrderService = wdtOrderService;
                } else if (erpType == 3) {
                    //
                    erpOrderService = hzOMSErpOrderService;
                } else if (erpType == 4) {
                    //代服
                    erpOrderService = dfOrderService;
                } else if (erpType == 5) {
                    erpOrderService = jSTOrderService;
                } else if (erpType == 6) {
                    erpOrderService = k9OrderService;
                }
                return erpOrderService;


            }
        }
        return null;
    }


    /**
     * 定时任务-im会员定时发课，每一分钟执行一次
     */
    public void sendOpenImCourse(){
        String redisKey = "openIm:batchSendMsg:sendCourse";
        Map<String, BatchSendCourseAllDTO> cacheMap = redisCache.getCacheMap(redisKey);
        if(cacheMap == null || cacheMap.isEmpty()){
            logger.info("=====================会员IM定时发课,不存在对应的redisKey==================");
            return;
        }
        List<Map.Entry<String, BatchSendCourseAllDTO>> toSendMap = cacheMap.entrySet().parallelStream().filter((v) -> {
            String[] split = v.getKey().split(":");
            long timestamp = Long.parseLong(split[2]);
            return timestamp < System.currentTimeMillis();
        }).collect(Collectors.toList());

        if(toSendMap.isEmpty()){
            logger.info("=====================会员IM定时发课,不存在可执行的发课任务==================");
            return;
        }
        for (Map.Entry<String, BatchSendCourseAllDTO> entry : toSendMap) {
            //执行发送消息任务
            BatchSendCourseAllDTO batchSendCourseAllDTO = entry.getValue();
            openIMService.batchSendCourseTask(batchSendCourseAllDTO.getBatchSendCourseDTO(), batchSendCourseAllDTO.getOpenImBatchMsgDTO(), batchSendCourseAllDTO.getProject(), batchSendCourseAllDTO.getImMsgSendDetailList());

            // 执行结束，删除
            this.redisTemplate.<String, BatchSendCourseAllDTO>opsForHash().delete(redisKey, entry.getKey());

        }

    }


    /**
     * 定时任务-im 会员催课，每一分钟执行一次
     */
    public void urgeOpenImCourse(){
        String redisKey = "openIm:batchSendMsg:urgeCourse";
        Map<String, BatchSendCourseAllDTO> cacheMap = redisCache.getCacheMap(redisKey);
        if(cacheMap == null || cacheMap.isEmpty()){
            logger.info("===================== 会员-IM发消息催课,不存在对应的redisKey==================");
            return;
        }
        List<Map.Entry<String, BatchSendCourseAllDTO>> toSendMap = cacheMap.entrySet().parallelStream().filter((v) -> {
            String[] split = v.getKey().split(":");
            long timestamp = Long.parseLong(split[2]);
            return timestamp < System.currentTimeMillis();
        }).collect(Collectors.toList());

        if(toSendMap.isEmpty()){
            logger.info("===================== 会员-IM发消息催课,不存在可发送的消息==================");
            return;
        }
        for (Map.Entry<String, BatchSendCourseAllDTO> entry : toSendMap) {
            //执行发送消息任务
            BatchSendCourseAllDTO batchSendCourseAllDTO = entry.getValue();
            openIMService.batchUrgeCourseTask(batchSendCourseAllDTO.getOpenImBatchMsgDTO(), batchSendCourseAllDTO.getImMsgSendDetailList());

            // 执行结束，删除
            this.redisTemplate.<String, BatchSendCourseAllDTO>opsForHash().delete(redisKey, entry.getKey());

        }
    }

    //定时任务刷新订单结算状态
    public void refreshOrderSettlementStatus(){
        fsStoreOrderScrmService.refreshOrderSettlementStatus();
    }

    //定时删除行为轨迹记录 (数据量太大 默认保留一天的)
    @Scheduled(cron = "0 0 1 * * ?")
    //@Scheduled(cron = "0 * * * * ?") //测试每分钟执行一次
    public void deleteUserOperationLog(){
        LambdaQueryWrapper<FsUserOperationLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.lt(FsUserOperationLog::getCreateTime, DateUtils.addDays(new Date(), -1));
        int deleteCount  = fsUserOperationLogMapper.delete(wrapper);
        log.info("定时删除行为轨迹记录 {} 条", deleteCount);
    }

    //同步支付状态
    public void synchronizePayStatus(){
        fsStorePaymentService.synchronizePayStatus();
    }

    /**
     * 超时取消订单
     */
    public void cancelOrder(){
        //查询超时订单
        SysConfig sysConfig= sysConfigService.selectConfigByConfigKey("his.store");
        StoreConfig config= JSONUtil.toBean(sysConfig.getConfigValue(),StoreConfig.class);
        Integer unPayTime = config.getUnPayTime(); //分钟
        if (unPayTime == null){
            return ;
        }
        //1.处方订单
        //查询超时未支付订单
        List<FsStoreOrder> orderList = orderService.selectOutTimeOrderList(unPayTime);
        //取消订单
        List<CompletableFuture<Void>> orderFutures = cancelOrdersAsync(orderList, order -> {
            orderService.cancelOrder(order.getOrderId());
        });

//        //2.课程订单
//        //查询超时未支付订单
//        List<FsUserCourseOrder> courseOrderlist = userCourseOrderService.selectOutTimeOrderList(unPayTime);
//        //取消订单
//        courseOrderlist.forEach(order->{
//            userCourseOrderService.cancelOrder(order.getOrderId());
//        });
        //3.服务包订单
        //查询超时未支付订单
        List<FsPackageOrder> packageOrderList = packageOrderService.selectOutTimeOrderList(unPayTime);
        //取消订单
        List<CompletableFuture<Void>> packageOrderFutures = cancelOrdersAsync(packageOrderList, order -> {
            FsPackageOrderCancelParam param = new FsPackageOrderCancelParam();
            param.setOrderId(order.getOrderId());
            packageOrderService.cancel(param);
        });

        // 等待所有任务完成
        waitForAllTasksToComplete(orderFutures);
        waitForAllTasksToComplete(packageOrderFutures);
    }

    /**
     * 异步取消订单
     * @param orders 订单列表
     * @param cancelAction 取消订单的逻辑
     * @param <T> 订单类型
     * @return CompletableFuture列表
     */
    private <T> List<CompletableFuture<Void>> cancelOrdersAsync(List<T> orders, Consumer<T> cancelAction) {
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        for (T order : orders) {
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                try {
                    cancelAction.accept(order);
                } catch (Exception e) {
                    // 记录异常日志
                    System.err.println("Failed to cancel order: " + order + ", Error: " + e.getMessage());
                }
            }, threadPoolTaskExecutor);
            futures.add(future);
        }
        return futures;
    }

    /**
     * 等待所有任务完成
     * @param futures CompletableFuture列表
     */
    private void waitForAllTasksToComplete(List<CompletableFuture<Void>> futures) {
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(
                futures.toArray(new CompletableFuture[0])
        );
        allFutures.join(); // 等待所有任务完成
    }


}
