package com.fs.app.controller;

import com.alibaba.fastjson.JSON;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.utils.uuid.IdUtils;
import com.fs.fastGpt.service.AiHookService;
import com.fs.qw.domain.QwUser;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.qw.service.IQwUserVoiceLogService;
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.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Api("企微消息")
@RestController
@RequestMapping(value="/msg")
@Slf4j
public class QwMsgController {
    @Autowired
     RedisCache redisCache;
    @Autowired
    AiHookService aiHookService;
    @Autowired
    QwUserMapper qwUserMapper;
    @Autowired
    WxWorkService wxWorkService;
    @Autowired
    IQwUserVoiceLogService qwUserVoiceLogService;

    @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:
                System.out.println("扫码返回");
                break;
            case 100002:
                System.out.println("取消扫码");
              //  redisCache.setCacheObject("qrCodeUid:"+wxWorkMsgResp.getUuid(),100002,10, TimeUnit.MINUTES);
                break;
            case 100003:
                System.out.println("确认扫码返回");

                break;
            case 104001:
                System.out.println("登录成功");

                JSONObject jsonObject = new JSONObject(wxWorkMsgResp.getJson());
                QwUser qu = qwUserMapper.selectQwUserById(id);
                Long corpId = jsonObject.getLong("Corpid");
                System.out.println("回调中的"+corpId);
                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);
                    System.out.println("公司不匹配不给登录");
                    WxWorkGetQrCodeDTO wxWorkGetQrCodeDTO = new WxWorkGetQrCodeDTO();
                    wxWorkGetQrCodeDTO.setUuid(wxWorkMsgResp.getUuid());
                    wxWorkService.LoginOut(wxWorkGetQrCodeDTO,serverId);
                    System.out.println("调用退出登录");
                    break;
                }
                if (!qu.getQwUserId().equals(jsonObject.get("acctid"))){
                    redisCache.setCacheObject("qrCodeUid:"+wxWorkMsgResp.getUuid(),23,10, TimeUnit.MINUTES);
                    System.out.println("账号不匹配不给登录");
                    WxWorkGetQrCodeDTO wxWorkGetQrCodeDTO = new WxWorkGetQrCodeDTO();
                    wxWorkGetQrCodeDTO.setUuid(wxWorkMsgResp.getUuid());
                    wxWorkService.LoginOut(wxWorkGetQrCodeDTO,serverId);
                    System.out.println("调用退出登录");
                    break;
                }
                QwUser qwUser = new QwUser();
                qwUser.setId(id);
                qwUser.setVid(jsonObject.get("Vid").toString());
                qwUser.setIpadStatus(1);
                qwUserMapper.updateQwUser(qwUser);
                System.out.println("存Vid");
                redisCache.setCacheObject("qrCodeUid:"+wxWorkMsgResp.getUuid(),104001,10, TimeUnit.MINUTES);
                break;
            case 100006:
                System.out.println("企业切换");
                break;
            case 100004:
                System.out.println("需要验证二维码消息");
                redisCache.setCacheObject("qrCodeUid:"+wxWorkMsgResp.getUuid(),100004,10, TimeUnit.MINUTES);
                break;
            case 100012:
                System.out.println("需要二次验证");
                redisCache.setCacheObject("qrCodeUid:"+wxWorkMsgResp.getUuid(),100012,10, TimeUnit.MINUTES);

                break;
            case 100005:
                System.out.println("手机端结束登录");
                log.info("手机端结束登录:"+wxWorkMsgResp.getJson());
                qwUserStatus(wxWorkMsgResp.getUuid(),0);
                break;
            case 100008:
                System.out.println("当前账号在其他设备登录");
                log.info("当前账号在其他设备登录:"+wxWorkMsgResp.getJson());
                qwUserStatus(wxWorkMsgResp.getUuid(),0);
                break;
            case 100007:
                System.out.println("异常断开");
                log.info("异常断开:"+wxWorkMsgResp.getJson());
                qwUserStatus(wxWorkMsgResp.getUuid(),0);
                break;
            case 100009:
                System.out.println("二次验证");
                log.info("二次验证:"+wxWorkMsgResp.getJson());
                qwUserStatus(wxWorkMsgResp.getUuid(),0);
                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();
                    System.out.println("接收人："+wxWorkMessageDTO.getReceiver());
                    System.out.println("发送人："+wxWorkMessageDTO.getSender());
                    System.out.println("内容："+content);
                    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);
                        WxwSpeechToTextEntityRespDTO data = dto.getData();
                        content = data.getText();
                        System.out.println("语音消息"+content);
                    }
                    else if (wxWorkMessageDTO.getMsgtype() == 101){
                        content = processImageMessage(serverId, wxWorkMessageDTO, wxWorkMsgResp);
                        System.out.println("用户发送图片"+content);
                    }
                    // gif 表情消息
                    else if (wxWorkMessageDTO.getMsgtype() == 104){
                        content = wxWorkMessageDTO.getUrl();
                        System.out.println("用户发送表情"+content);
                    }

                    if (2000000000000000L-receiver>0){
                        System.out.println("客户发送");
                        aiHookService.qwHookNotifyAiReply(id,sender,content,wxWorkMsgResp.getUuid(),wxWorkMessageDTO.getMsgtype());
                    }else {
                        System.out.println("销售发送");
                        aiHookService.qwHookNotifyAddMsg(id,receiver,content,wxWorkMsgResp.getUuid());
                    }

                }
                //语音通话
                if (wxWorkMessageDTO.getMsgtype()==40){
                    if (wxWorkMessageDTO.getRecordtype()==null){
                        break;
                    }
                    Long receiver = wxWorkMessageDTO.getReceiver();
                    Long extId=null;
                    Integer totalSeconds=0;
                    if (2000000000000000L-receiver>0){
                         extId = wxWorkMessageDTO.getSender();
                        System.out.println("客户发起");
                    }else {
                        System.out.println("销售发起");
                        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 * 3600 + minutes * 60 + seconds;
                                System.out.println("总通话秒数: " + totalSeconds);
                            }
                        }
                    } else if (recordType==2){
                        System.out.println("通话挂断");
                    }else {
                        break;
                    }

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

                break;

        }




        return map;
    }

    /**
     * 处理图片消息
     * @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){
        Long id = redisCache.getCacheObject("qrCode:uuid:"+uid);
        QwUser qwUser = new QwUser();
        qwUser.setId(id);
        qwUser.setIpadStatus(status);
        qwUserMapper.updateQwUser(qwUser);
    }

}
