package com.fs.app.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.uuid.IdUtils;
import com.fs.fastGpt.domain.FastGptRole;
import com.fs.fastGpt.service.AiHookService;
import com.fs.fastGpt.service.IFastGptRoleService;
import com.fs.his.domain.FsStoreOrder;
import com.fs.his.dto.ExpressInfoDTO;
import com.fs.his.dto.TracesDTO;
import com.fs.his.enums.ShipperCodeEnum;
import com.fs.his.service.IFsExpressService;
import com.fs.his.service.IFsStoreOrderService;
import com.fs.qw.domain.QwExternalContact;
import com.fs.qw.domain.QwUser;
import com.fs.qw.domain.QwUserVideo;
import com.fs.qw.mapper.QwExternalContactMapper;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.qw.service.IQwExternalContactService;
import com.fs.qw.service.IQwUserService;
import com.fs.qw.service.IQwUserVideoService;
import com.fs.qw.service.IQwUserVoiceLogService;
import com.fs.sop.mapper.QwSopLogsMapper;
import com.fs.sop.mapper.SopUserLogsInfoMapper;
import com.fs.sop.params.GetQwSopLogsByJsApiParam;
import com.fs.voice.utils.StringUtil;
import com.fs.wxwork.dto.*;
import com.fs.wxwork.service.WxWorkService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.fs.his.utils.PhoneUtil.decryptPhone;


@Api("企微消息")
@RestController
@RequestMapping(value="/msg")
@Slf4j
public class QwMsgController {
    @Autowired
     RedisCache redisCache;
    @Autowired
    AiHookService aiHookService;
    @Autowired
    QwUserMapper qwUserMapper;
    @Autowired
    WxWorkService wxWorkService;
    @Autowired
    IQwUserService qwUserService;
    @Autowired
    IQwUserVideoService qwUserVideoService;
    @Autowired
    IQwUserVoiceLogService qwUserVoiceLogService;
    @Autowired
    IFsStoreOrderService fsStoreOrderService;
    @Autowired
    IQwExternalContactService externalContactService;
    @Autowired
    QwExternalContactMapper qwExternalContactMapper;
    @Autowired
    SopUserLogsInfoMapper sopUserLogsInfoMapper;
    @Autowired
    QwSopLogsMapper qwSopLogsMapper;
    @Autowired
    private IFastGptRoleService fastGptRoleService;
    @Autowired
    private IFsExpressService expressService;
    @Autowired
    private IFsStoreOrderService storeOrderService;

    @GetMapping("/sendExpressInfo/{orderId}")
    public R sendExpressInfo(@PathVariable Long orderId){
        String isSend = redisCache.getCacheObject("fs:express:info:send:" +orderId);
        if(isSend == null){
            redisCache.setCacheObject("fs:express:info:send:" +orderId, "1",2, TimeUnit.MINUTES);
            FsStoreOrder order = fsStoreOrderService.selectFsStoreOrderByOrderId(orderId);
            if(order != null && order.getUserId() != null){
                List<QwExternalContact> qwExternalContact = externalContactService.selectQwExternalContactByFsUserIdAndCompany(order.getUserId(),order.getCompanyUserId());
                if(qwExternalContact != null && !qwExternalContact.isEmpty()){
                    for (QwExternalContact externalContact : qwExternalContact) {
                        Long qwUserId = externalContact.getQwUserId();
                        if(qwUserId != null ){
                            QwUser qwUser = qwUserMapper.selectQwUserById(qwUserId);
                            if(qwUser != null && qwUser.getUid() != null && qwUser.getFastGptRoleId() != null && qwUser.getServerId() != null && qwUser.getServerStatus() == 1 && qwUser.getIpadStatus() == 1){
                                FastGptRole fastGptRole = fastGptRoleService.selectFastGptRoleByRoleId(qwUser.getFastGptRoleId());
                                if(fastGptRole.getLogistics() == 0){
                                    log.error("物流功能未开启,roleId：" + qwUser.getFastGptRoleId() + "订单号：" + orderId);
                                    return R.ok();
                                }
                                Long sendId = externalContact.getWxUserId();
                                if (sendId == null || sendId <= 0) {
                                    WxWorkUserId2VidDTO wxWorkUserId2VidDTO = new WxWorkUserId2VidDTO();
                                    wxWorkUserId2VidDTO.setOpenid(Collections.singletonList(externalContact.getExternalUserId()));
                                    wxWorkUserId2VidDTO.setUuid(qwUser.getUid());
                                    WxWorkResponseDTO<List<WxWorkVid2UserIdRespDTO>> WxWorkVid2UserIdRespDTO = wxWorkService.UserId2Vid(wxWorkUserId2VidDTO,qwUser.getServerId());
                                    List<WxWorkVid2UserIdRespDTO> data = WxWorkVid2UserIdRespDTO.getData();
                                    if(data != null && !data.isEmpty()){
                                        sendId = data.get(0).getUser_id();
                                        if (sendId != null && externalContact.getId() != null) {
                                            QwExternalContact upd = new QwExternalContact();
                                            upd.setId(externalContact.getId());
                                            upd.setWxUserId(sendId);
                                            qwExternalContactMapper.updateQwExternalContact(upd);
                                        }
                                    }
                                }
                                StringBuilder sBuilder = new StringBuilder();
                                if(sendId != null){
                                    switch (order.getStatus())
                                    {
                                        case -1:
                                        case -2:
                                        case 1:
                                            break;
                                        case 2:
                                            sBuilder.append("您好，您有一个包裹正在准备发货，请耐心等待;\n");
                                            if(order.getDeliverySn() != null && !order.getDeliverySn().isEmpty()){
                                                sBuilder.append(" 物流单号为：").append(order.getDeliverySn()).append("\n");
                                            }
                                            sBuilder.append("\uD83C\uDF39\uD83C\uDF39\uD83C\uDF39");
                                            break;
                                        case 3:
                                            ExpressInfoDTO express = getExpress(order.getOrderId());
                                            if("211".equals(express.getStateEx())){
                                                //你好，这边查询到您购买的XXX（购买套餐）在XXX（时间）已经送到了，送货员电话为XXX（送货员信息）
                                                sBuilder.append("这边查询到您有一个包裹 ");
                                                if(express != null && express.getTraces() != null && !express.getTraces().isEmpty()){
                                                    List<TracesDTO> traces = express.getTraces();
                                                    TracesDTO tracesDTO = traces.get(traces.size() - 1);
                                                    sBuilder.append(" 在").append(tracesDTO.getAcceptTime()).append("已经送到了\n");
                                                    sBuilder.append(" 物流单号为：").append(order.getDeliverySn()).append("\n");
                                                    sBuilder.append("物流信息：").append(tracesDTO.getAcceptStation()).append("\n");
                                                }else{
                                                    sBuilder.append(" 已经送到了\n");
                                                }
                                                sBuilder.append("\uD83C\uDF39\uD83C\uDF39\uD83C\uDF39");
                                            }
                                            break;
                                        case 4:
                                        case 5:
                                    }
                                    if(!"".contentEquals(sBuilder)){
                                        //2.发送模板中的文字内容
                                        String content = sBuilder.toString();
                                        content = content.replace("（有事呼叫我，勿找平台，少一次投诉，多一份感恩）", "");
                                        WxWorkSendTextMsgDTO wxWorkSendTextMsgDTO = new WxWorkSendTextMsgDTO();
                                        wxWorkSendTextMsgDTO.setSend_userid(sendId);
                                        wxWorkSendTextMsgDTO.setUuid(qwUser.getUid());
                                        wxWorkSendTextMsgDTO.setContent(content);
                                        wxWorkSendTextMsgDTO.setIsRoom(false);
                                        wxWorkService.SendTextMsg(wxWorkSendTextMsgDTO,qwUser.getServerId());
                                    }
                                    return R.ok();
                                }
                            }
                        }
                    }
                }
            }
        }
        return R.ok();
    }

    public ExpressInfoDTO getExpress(Long id){
        FsStoreOrder order=storeOrderService.selectFsStoreOrderByOrderId(id);

        ExpressInfoDTO expressInfoDTO=null;
        if(com.fs.common.utils.StringUtils.isNotEmpty(order.getDeliverySn())){
            String lastFourNumber = "";
            if (order.getDeliveryCode().equals(ShipperCodeEnum.SF.getValue())) {

                lastFourNumber = order.getUserPhone();
                if (lastFourNumber.length() == 11) {
                    lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
                }else if (lastFourNumber.length()>11){
                    String jm = decryptPhone(lastFourNumber);
                    lastFourNumber = StrUtil.sub(jm, jm.length(), -4);
                }
            }
            expressInfoDTO=expressService.getExpressInfo(order.getOrderCode(),order.getDeliveryCode(),order.getDeliverySn(),lastFourNumber);

            if((expressInfoDTO.getStateEx()!=null&&expressInfoDTO.getStateEx().equals("0"))&&(expressInfoDTO.getState()!=null&&expressInfoDTO.getState().equals("0"))){
                lastFourNumber = "19923690275";
                if (order.getDeliveryCode().equals(ShipperCodeEnum.SF.getValue())) {
                    if (lastFourNumber.length() == 11) {
                        lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
                    }
                }

                expressInfoDTO=expressService.getExpressInfo(order.getOrderCode(),order.getDeliveryCode(),order.getDeliverySn(),lastFourNumber);

            }
        }
        return expressInfoDTO;
    }


    @PostMapping("/callback/{serverId}")
    @ResponseBody
    public Map<String,String> callback(@RequestBody String json,@PathVariable Long serverId ){
      //  System.out.println(json);
        WxWorkMsgResp wxWorkMsgResp = JSON.parseObject(json, WxWorkMsgResp.class);
        Integer type = wxWorkMsgResp.getType();
        HashMap<String, String> map = new HashMap<>();
        map.put("errorcode","0");
        map.put("errmsg","ok");
        Long id = redisCache.getCacheObject("qrCode:uuid:"+wxWorkMsgResp.getUuid());
        if (id==null){
            return map;
        }
        switch (type){
            case 100001:
                log.info("id:{}, 扫码返回", id);
                break;
            case 100002:
                log.info("id:{}, 取消扫码", id);
              //  redisCache.setCacheObject("qrCodeUid:"+wxWorkMsgResp.getUuid(),100002,10, TimeUnit.MINUTES);
                break;
            case 100003:
                log.info("id:{}, 确认扫码返回", id);

                break;
            case 104001:
                log.info("id:{}, 登录成功", id);

                JSONObject jsonObject = new JSONObject(wxWorkMsgResp.getJson());
                QwUser qu = qwUserMapper.selectQwUserById(id);
                Long corpId = jsonObject.getLong("Corpid");
                log.info("id:{}, 回调中的"+corpId, id);
                String sCorpId = wxWorkService.getCorpId(wxWorkMsgResp.getUuid(), corpId,serverId);
                if (sCorpId==null&& sCorpId.isEmpty()){
                    break;
                }
                if (!qu.getCorpId().equals(sCorpId)){
                    redisCache.setCacheObject("qrCodeUid:"+wxWorkMsgResp.getUuid(),22,10, TimeUnit.MINUTES);
                    log.info("id:{}, 公司不匹配不给登录", id);
                    WxWorkGetQrCodeDTO wxWorkGetQrCodeDTO = new WxWorkGetQrCodeDTO();
                    wxWorkGetQrCodeDTO.setUuid(wxWorkMsgResp.getUuid());
                    wxWorkService.LoginOut(wxWorkGetQrCodeDTO,serverId);
                    log.info("id:{}, 调用退出登录", id);
                    break;
                }
                if (!qu.getQwUserId().equals(jsonObject.get("acctid"))){
                    redisCache.setCacheObject("qrCodeUid:"+wxWorkMsgResp.getUuid(),23,10, TimeUnit.MINUTES);
                    log.info("id:{}, 账号不匹配不给登录", id);
                    WxWorkGetQrCodeDTO wxWorkGetQrCodeDTO = new WxWorkGetQrCodeDTO();
                    wxWorkGetQrCodeDTO.setUuid(wxWorkMsgResp.getUuid());
                    wxWorkService.LoginOut(wxWorkGetQrCodeDTO,serverId);
                    log.info("id:{}, 调用退出登录", id);
                    break;
                }
                QwUser qwUser = new QwUser();
                qwUser.setId(id);
                qwUser.setVid(jsonObject.get("Vid").toString());
                qwUser.setIpadStatus(1);
                qwUserMapper.updateQwUser(qwUser);
                log.info("id:{}, 存Vid", id);
                redisCache.setCacheObject("qrCodeUid:"+wxWorkMsgResp.getUuid(),104001,10, TimeUnit.MINUTES);
                break;
            case 100006:

                break;
            case 100004:
                log.info("id:{}, 需要验证二维码消息", id);
                redisCache.setCacheObject("qrCodeUid:"+wxWorkMsgResp.getUuid(),100004,10, TimeUnit.MINUTES);
                break;
            case 100012:
                log.info("id:{}, 需要二次验证:"+wxWorkMsgResp.getJson(), id);

                redisCache.setCacheObject("qrCodeUid:"+wxWorkMsgResp.getUuid(),100012,10, TimeUnit.MINUTES);

                break;
            case 100005:

                log.info("id:{}, 手机端结束登录:"+wxWorkMsgResp.getJson(), id);
                JSONObject jsonObject1 = new JSONObject(wxWorkMsgResp.getJson());
                qwUserStatus(wxWorkMsgResp.getUuid(),0, jsonObject1.getString("msg"));
                break;
            case 100008:
                QwUser vidUser = qwUserMapper.selectQwUserById(id);
                if (vidUser.getUid().equals(wxWorkMsgResp.getUuid())){
                    log.info("id:{}, 当前账号在其他设备登录:"+wxWorkMsgResp.getJson(), id);
                    JSONObject jsonObject2 = new JSONObject(wxWorkMsgResp.getJson());
                    qwUserStatus(wxWorkMsgResp.getUuid(),0, jsonObject2.getString("msg"));
                }
                log.info("id:{}, 当前账号重新登录:"+wxWorkMsgResp.getJson(), id);
                break;
            case 100007:
                log.info("id:{}, 异常断开:"+wxWorkMsgResp.getJson(), id);
                JSONObject jsonObject3 = new JSONObject(wxWorkMsgResp.getJson());
                qwUserStatus(wxWorkMsgResp.getUuid(),0, "异常断开 - " + jsonObject3.getString("msg"));
                break;
            case 100009:
                log.info("id:{}, 二次验证:"+wxWorkMsgResp.getJson(), id);
                JSONObject jsonObject4 = new JSONObject(wxWorkMsgResp.getJson());
                qwUserStatus(wxWorkMsgResp.getUuid(),0, "二次验证 - " + jsonObject4.getString("msg"));
                break;
            case 102001:
            case 102002:
                WxWorkMessageDTO wxWorkMessageDTO1 = JSON.parseObject(wxWorkMsgResp.getJson(), WxWorkMessageDTO.class);
                handleSopBlockOrDel(id,wxWorkMessageDTO1,wxWorkMsgResp.getUuid(),5);
                break;
            case 102000:
                WxWorkMessageDTO wxWorkMessageDTO = JSON.parseObject(wxWorkMsgResp.getJson(), WxWorkMessageDTO.class);
                if (wxWorkMessageDTO.getIs_room()!=0){
                    break;
                }
                if (wxWorkMessageDTO.getReferid()!=0){
                    break;
                }
                if (wxWorkMessageDTO.getMsgtype()==2||wxWorkMessageDTO.getMsgtype()==0||wxWorkMessageDTO.getMsgtype()==16||wxWorkMessageDTO.getMsgtype() == 101||wxWorkMessageDTO.getMsgtype() == 104){

                    String content = wxWorkMessageDTO.getContent();
                    log.info("id:{}, 接收人："+wxWorkMessageDTO.getReceiver(), id);
                    log.info("id:{}, 发送人："+wxWorkMessageDTO.getSender(), id);
                    log.info("id:{}, 内容："+content, id);
                    Long receiver = wxWorkMessageDTO.getReceiver();
                    Long sender = wxWorkMessageDTO.getSender();
                    if(wxWorkMessageDTO.getMsgtype()==16){
                        WxwSpeechToTextEntityDTO ste = new WxwSpeechToTextEntityDTO();
                        ste.setMsgid(wxWorkMessageDTO.getMsg_id());
                        ste.setUuid(wxWorkMsgResp.getUuid());
                        WxWorkResponseDTO<WxwSpeechToTextEntityRespDTO> dto = wxWorkService.SpeechToTextEntity(ste, serverId);
                        System.out.println(dto);
                        if(dto.getErrcode() != 0 || Objects.isNull(dto.getData()) || StringUtils.isBlank(dto.getData().getText())){
                            try {
                                TimeUnit.SECONDS.sleep(2); // 阻塞2秒
                            } catch (InterruptedException e) {
                                Thread.currentThread().interrupt(); // 处理中断异常
                                log.info("id:{}, 第一次语音转换失败", id);
                            }
                            dto = wxWorkService.SpeechToTextEntity(ste, serverId);
                        }
                        WxwSpeechToTextEntityRespDTO data = dto.getData();
                        content = data.getText();
                        if(content == null || content.isEmpty()){
                            content = "==语音转换失败==";
                        }
                        log.info("id:{}, 语音消息"+content, id);
                    }
                    else if (wxWorkMessageDTO.getMsgtype() == 101){
                        content = processImageMessage(serverId, wxWorkMessageDTO, wxWorkMsgResp);
                        log.info("id:{}, 用户发送图片"+content, id);
                    }
                    // gif 表情消息
                    else if (wxWorkMessageDTO.getMsgtype() == 104){
                        content = wxWorkMessageDTO.getUrl();
                        log.info("id:{}, 用户发送表情"+content, id);
                    }//视频号

                    if (2000000000000000L-receiver>0){
                        log.info("id:{}, 客户发送", id);
                        aiHookService.qwHookNotifyAiReply(id,sender,content,wxWorkMsgResp.getUuid(),wxWorkMessageDTO.getMsgtype());
                    }else {
                        log.info("销售发送");
                        aiHookService.qwHookNotifyAddMsgNew(id,receiver,content,wxWorkMsgResp.getUuid(),1);
                    }

                }
                //视频号
                if (wxWorkMessageDTO.getMsgtype()==141){
                    QwUser qwUserByAppKey = qwUserMapper.selectQwUserById(id);
                    log.info("进入到视频号：{}",qwUserByAppKey);

                    if(qwUserByAppKey.getVideoGetStatus() != null && qwUserByAppKey.getVideoGetStatus() == 1){
                        QwUserVideo qwUserVideo = qwUserVideoService.selectByObjectId(wxWorkMessageDTO.getObjectId(), qwUserByAppKey.getId());
                        if(qwUserVideo == null){
                            QwUserVideo userVideo=new QwUserVideo();
                            userVideo.setSenderName(wxWorkMessageDTO.getSender_name());
                            userVideo.setAppKey(qwUserByAppKey.getAppKey());
                            userVideo.setNickName(wxWorkMessageDTO.getNickname());
                            userVideo.setObjectId(wxWorkMessageDTO.getObjectId());
                            userVideo.setCoverUrl(wxWorkMessageDTO.getCover_url());
                            userVideo.setThumbUrl(wxWorkMessageDTO.getThumb_url());
                            userVideo.setAvatar(wxWorkMessageDTO.getAvatar());
                            userVideo.setDesc(wxWorkMessageDTO.getDesc());
                            userVideo.setUrl(wxWorkMessageDTO.getUrl());
                            userVideo.setExtras(wxWorkMessageDTO.getExtras());
                            userVideo.setObjectNonceId(wxWorkMessageDTO.getObjectNonceId());
                            userVideo.setQwUserId(qwUserByAppKey.getId());
                            userVideo.setCompanyUserId(qwUserByAppKey.getCompanyUserId());
                            userVideo.setCompanyId(qwUserByAppKey.getCompanyId());
                            qwUserVideoService.insertQwUserVideo(userVideo);
                            log.info("存储完成：userVideo={}",userVideo);
                        }
                    }
                }
                //语音通话
                if (wxWorkMessageDTO.getMsgtype()==40){
                    if (wxWorkMessageDTO.getRecordtype()==null){
                        break;
                    }
                    Long receiver = wxWorkMessageDTO.getReceiver();
                    Long extId=null;
                    long totalSeconds=0L;
                    if (2000000000000000L-receiver>0){
                         extId = wxWorkMessageDTO.getSender();
                        log.info("id:{}, 客户发起", id);
                    }else {
                        log.info("id:{}, 销售发起", id);
                        extId = wxWorkMessageDTO.getReceiver();
                    }
                    Integer recordType = wxWorkMessageDTO.getRecordtype();
                    if (recordType==5){
                        String recordwording = wxWorkMessageDTO.getRecordwording();
                        //String recordwording = "通话时长01:20:07";
                        if (recordwording != null && !recordwording.isEmpty()){
                            // 同时匹配 "HH:mm:ss" 和 "mm:ss" 格式
                            Pattern pattern = Pattern.compile("(\\d+):(\\d+)(?::(\\d+))?");
                            Matcher matcher = pattern.matcher(recordwording);
                            if (matcher.find()) {
                                int hours = 0;
                                int minutes;
                                int seconds;

                                // 如果有小时部分(匹配到3个组)
                                if (matcher.group(3) != null) {
                                    hours = Integer.parseInt(matcher.group(1));
                                    minutes = Integer.parseInt(matcher.group(2));
                                    seconds = Integer.parseInt(matcher.group(3));
                                }
                                else {// 只有分钟和秒(匹配到2个组)
                                    minutes = Integer.parseInt(matcher.group(1));
                                    seconds = Integer.parseInt(matcher.group(2));
                                }
                                totalSeconds = hours * 3600L + minutes * 60L + seconds;
                                log.info("id:{}, 总通话秒数: " + totalSeconds, id);
                            }
                        }
                    } else if (recordType==2){
                        log.info("id:{}, 通话挂断", id);
                    }else if (recordType==3){
                        log.info("通话未接听");
                    }else {
                        break;
                    }

                    qwUserVoiceLogService.addQuUserVoiceByIpadCallback(id,extId,recordType,totalSeconds,wxWorkMsgResp.getUuid());
                }

                break;

        }




        return map;
    }

    /**
     * 处理被拉黑的用户
     * @param qwUserId
     * @param wxWorkMessageDTO
     * @param uuid
     * @param status
     */
    private void handleSopBlockOrDel(Long qwUserId,WxWorkMessageDTO wxWorkMessageDTO,String uuid, Integer status){
        QwUser user = qwUserMapper.selectQwUserById(qwUserId);
        //查询接收人
        if(user==null){
            log.info("查询接收人为空");
        }
        if(user.getFastGptRoleId()==null){
            log.info("未绑定角色");
        }
        Long serverId = user.getServerId();
        log.info("服务器id"+serverId);
        if (serverId == null) {
            log.info("服务id为空");
        }

        WxWorkVid2UserIdDTO wxWorkVid2UserIdDTO = new WxWorkVid2UserIdDTO();
        wxWorkVid2UserIdDTO.setUser_id(Arrays.asList(wxWorkMessageDTO.getReceiver()));
        wxWorkVid2UserIdDTO.setUuid(uuid);
        //下面的方法是返回当前对象
        WxWorkResponseDTO<List<WxWorkVid2UserIdRespDTO>> WxWorkVid2UserIdRespDTO = wxWorkService.Vid2UserId(wxWorkVid2UserIdDTO,serverId);
        List<WxWorkVid2UserIdRespDTO> data = WxWorkVid2UserIdRespDTO.getData();
        if (data==null|| data.isEmpty()){

            log.info("未获取到extId"+wxWorkVid2UserIdDTO);
        }
        com.fs.wxwork.dto.WxWorkVid2UserIdRespDTO dto = data.get(0);

        QwExternalContact qwExternalContacts = qwExternalContactMapper.selectQwExternalContactByExternalUserIdAndQwUserId(dto.getOpenid(), user.getCorpId(),user.getQwUserId());
        if (qwExternalContacts==null){
            log.info("没有外部联系人");
        }

        //处理拉黑的
        String appKey = user.getAppKey();
        //客户编号
        String receiverOpenid = qwExternalContacts.getExternalUserId();

        if (StringUtil.strIsNullOrEmpty(appKey) || StringUtil.strIsNullOrEmpty(receiverOpenid)){
            log.error("删除或拉黑-处理营期失败数据不对："+appKey+"|"+receiverOpenid);
            return;
        }

        try {
            QwUser qwUser = qwUserMapper.selectQwUserByAppKey(appKey);
            if (qwUser!=null){

                //修改客户状态
                QwExternalContact contact=new QwExternalContact();
                contact.setStatus(status);
                contact.setUserId(qwUser.getQwUserId());
                contact.setCorpId(qwUser.getCorpId());
                contact.setExternalUserId(receiverOpenid);
                qwExternalContactMapper.updateQwExternalContactByUseridBlock(contact);


                log.info("删除或拉黑-处理营期-"+qwUser.getQwUserId()+"|"+qwUser.getCorpId()+"|"+receiverOpenid);

                //删除营期
                sopUserLogsInfoMapper.deleteByQwUserIdAndCorpIdToContactId(qwUser.getQwUserId(),qwUser.getCorpId(),receiverOpenid);

                //删除待发送记录
                GetQwSopLogsByJsApiParam apiParam=new GetQwSopLogsByJsApiParam();
                apiParam.setQwUserId(qwUser.getQwUserId());
                apiParam.setCorpId(qwUser.getCorpId());
                apiParam.setExternalUserId(receiverOpenid);
                qwSopLogsMapper.deleteQwSopLogsByJsApi(apiParam);
            }

        }catch (Exception e){
            log.error("删除或拉黑-处理营期失败："+appKey+"|"+receiverOpenid+"|"+e.getMessage());
        }

    }

    /**
     * 处理图片消息
     * @param serverId          服务器ID
     * @param wxWorkMessageDTO  消息DTO
     * @param wxWorkMsgResp     回调信息对象
     */
    private String processImageMessage(Long serverId, WxWorkMessageDTO wxWorkMessageDTO, WxWorkMsgResp wxWorkMsgResp) {
        String fileName = IdUtils.fastSimpleUUID() + ".jpg";
        WxWorkResponseDTO<String> fileUrlResp =
                aiHookService.getFileUrl(wxWorkMsgResp.getUuid(), wxWorkMessageDTO.getFile_id(), wxWorkMessageDTO.getAes_key(), wxWorkMessageDTO.getOpenim_cdn_authkey(), fileName, wxWorkMessageDTO.getFile_size(), serverId);
        if (fileUrlResp.getErrcode() != 0) {
            log.warn("获取图片地址失败: {}", fileUrlResp.getErrmsg());
            return null;
        }
        return fileUrlResp.getData();
    }




    void qwUserStatus(String uid, Integer status, String msg){
        Long id = redisCache.getCacheObject("qrCode:uuid:"+uid);
        QwUser qwUser = new QwUser();
        qwUser.setId(id);
        qwUser.setRemark(msg);
        qwUser.setIpadStatus(status);
        qwUserMapper.updateQwUser(qwUser);
        QwUser qwUser1 = qwUserMapper.selectQwUserById(id);
        if(uid.equals(qwUser1.getUid())){
            qwUserService.atMsg(qwUser1, "掉线提醒（"+msg+"）");
        }
    }

}
