package com.xinelu.quartz.task;


import com.alibaba.fastjson.JSON;
import com.aliyuncs.exceptions.ClientException;
import com.xinelu.manage.domain.shortmessagesendrecord.ShortMessageSendRecord;
import com.xinelu.manage.domain.textmessage.SmsReport;
import com.xinelu.manage.domain.textmessage.TaskMessageBackEntity;
import com.xinelu.manage.mapper.shortmessagesendrecord.ShortMessageSendRecordMapper;
import com.xinelu.manage.mapper.signpatientmanageroute.SignPatientManageRouteMapper;
import com.xinelu.manage.vo.signpatientmanageroute.SignPatientManageRouteVO;
import com.xinelu.quartz.service.SendTextMessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description 短信相关定时任务
 * @Author zh
 * @Date 2024-07-22
 */
@Slf4j
@Component("sendTextMessageTask")
public class SendTextMessageTask {

    @Resource
    private SendTextMessageService sendTextMessageService;
    @Resource
    private ShortMessageSendRecordMapper shortMessageSendRecordMapper;
    @Resource
    private SignPatientManageRouteMapper signPatientManageRouteMapper;

    /**
     * 签约患者管理任务路径节点短信发送定时任务
     */
    public void automaticSendTextMessageTask() throws ClientException {
        log.info("开始执行签约患者管理任务短信推送定时任务......");
        sendTextMessageService.sendTextMessageSendTask();
        log.info("完成订阅签约患者管理任务路径节点推送定时任务......");
    }
    @Transactional(rollbackFor = Exception.class)
    public void smsReportBack() {
        log.info("开始执行同步短信回调数据定时任务......");
        TaskMessageBackEntity taskMessageBackEntity = new TaskMessageBackEntity();
        taskMessageBackEntity.setReadState(0);
        List<TaskMessageBackEntity> taskMessageBackEntityList = sendTextMessageService.taskMessageBack(taskMessageBackEntity);
        List<ShortMessageSendRecord> shortMessageSendRecords = new ArrayList<>();
        if (CollectionUtils.isEmpty(taskMessageBackEntityList)) {
            log.info("完成同步短信回调数据定时任务，未查询到未读短信回执......");
        }
        // 回调数据提取
        List<SmsReport> smsReports = new ArrayList<>();
        taskMessageBackEntityList.forEach(entity -> {
            // JSONString 转 SmsReport
            smsReports.addAll(JSON.parseArray(entity.getMessageBackData().toString(), SmsReport.class));
        });
        log.info("短信数据提取完成，共" + smsReports.size() + "条");
        if (CollectionUtils.isNotEmpty(smsReports)) {
            List<Long> outIds = smsReports.stream().filter(Objects::nonNull).map(SmsReport::getOut_id).filter(Objects::nonNull)
                    .map(id -> {
                        try {
                            return Long.parseLong(id);
                        } catch (NumberFormatException e) {
                            // 打印日志或忽略，这里返回 null 然后被下一个 filter 过滤
                            return null;
                        }
                    })
                    .filter(Objects::nonNull)  // 过滤掉转换失败的 null
                    .distinct().collect(Collectors.toList());
            if (CollectionUtils.isEmpty(outIds)) {
                log.info("短信数据缺少任务信息！");
                return;
            }
            List<SignPatientManageRouteVO> signPatientManageRoutes = signPatientManageRouteMapper.selectRouteByBatchSendTaskRecordId(outIds);
            for (SmsReport smsReport : smsReports) {
                // 回调数据解析
                SignPatientManageRouteVO signPatientManageRoute = signPatientManageRoutes.stream().filter(Objects::nonNull)
                        .filter(item -> smsReport.getPhone_number().equals(item.getPhone()) && item.getBatchSendTaskRecordId().equals(Long.parseLong(smsReport.getOut_id())))
                        .findFirst().orElse(new SignPatientManageRouteVO());
                if (StringUtils.isBlank(signPatientManageRoute.getPhone()) || Objects.isNull(signPatientManageRoute.getId())){
                    continue;
                }
                sendTextMessageService.taskTextMessageSendBack(smsReport, shortMessageSendRecords, signPatientManageRoute);
            }
        }
        if (CollectionUtils.isNotEmpty(shortMessageSendRecords) && shortMessageSendRecords.size() > 0) {
            log.info("新增短信发送记录" + shortMessageSendRecords.size() + "条");
            shortMessageSendRecordMapper.insertShortMessageSendRecords(shortMessageSendRecords);
        }
        if (CollectionUtils.isEmpty(shortMessageSendRecords) && shortMessageSendRecords.size() == 0) {
            return;
        }
        List<Integer> ids = taskMessageBackEntityList.stream().filter(Objects::nonNull).map(TaskMessageBackEntity::getId).collect(Collectors.toList());
        // 修改阿里云服务器回调数据已读状态
        if (CollectionUtils.isNotEmpty(ids)) {
            log.info("修改中站记录" + ids.size() + "条");
            sendTextMessageService.updateReadState(1, ids);
        }
        log.info("完成同步短信回调数据定时任务......");
    }

    public void clearCallbackData() {
        log.info("开始执行清除过期的百度外呼回调数据定时任务......");
        // 清除一个月前的数据
        int count = sendTextMessageService.deleteData();
        log.info("完成清除过期的百度外呼回调数据定时任务,共清除" + count + "条......");
    }
}
