package com.fs.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.app.socket.QwImSocket;
import com.fs.app.util.AudioUtils;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.utils.StringUtils;
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.IQwCompanyService;
import com.fs.qw.service.IQwUserVoiceLogService;
import com.fs.qw.vo.QwMessageListVO;
import com.fs.wxwork.dto.*;
import com.fs.wxwork.service.WxWorkService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
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;
    @Autowired
    private IQwCompanyService qwCompanyService;

    @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 = JSON.parseObject(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);
                qwUser.setAvatar(jsonObject.get("avatar").toString());
                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;
                }

                Long receiver = wxWorkMessageDTO.getReceiver();
                Long sender = wxWorkMessageDTO.getSender();

                // 1客户 2销售
                int sendType = 2;

                // 消息发送者用户ID
                Long userId = receiver;
                if (2000000000000000L - receiver > 0){
                    sendType = 1;
                    userId = sender;
                }

                if (wxWorkMessageDTO.getMsgtype()==2||wxWorkMessageDTO.getMsgtype()==0||wxWorkMessageDTO.getMsgtype()==16){

                    String content = wxWorkMessageDTO.getContent();
                    System.out.println("接收人："+wxWorkMessageDTO.getReceiver());
                    System.out.println("发送人："+wxWorkMessageDTO.getSender());
                    System.out.println("内容："+content);

                    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);
                    }
                    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() == 2 || wxWorkMessageDTO.getMsgtype() == 0) {
                        processTextMessage(id, userId, content, wxWorkMsgResp, sendType);
                    }
                    // 语音消息
                    if (wxWorkMessageDTO.getMsgtype() == 16) {
                        processVoiceMessage(serverId, content, wxWorkMessageDTO, wxWorkMsgResp, id, userId, sendType);
                    }
                }
                //语音通话
                if (wxWorkMessageDTO.getMsgtype()==40){
                    if (wxWorkMessageDTO.getRecordtype()==null){
                        break;
                    }
                    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();
                        if (recordwording != null && !recordwording.isEmpty()){
                            // 1. 正则匹配 "mm:ss"
                            Pattern pattern = Pattern.compile("(\\d+):(\\d+)");
                            Matcher matcher = pattern.matcher(recordwording);
                            if (matcher.find()) {
                                int minutes = Integer.parseInt(matcher.group(1));
                                int seconds = Integer.parseInt(matcher.group(2));
                                totalSeconds = minutes * 60 + seconds;
                                System.out.println("总通话秒数: " + totalSeconds);
                            }
                        }
                    } else if (recordType==2){
                        System.out.println("通话挂断");
                    }else {
                        break;
                    }

                    qwUserVoiceLogService.addQuUserVoiceByIpadCallback(id,extId,recordType,totalSeconds,wxWorkMsgResp.getUuid());
                }
                // 图片消息
                else if (wxWorkMessageDTO.getMsgtype() == 101){
                    processImageMessage(serverId, wxWorkMessageDTO, wxWorkMsgResp, id, userId, sendType);
                }
                // gif 表情消息
                else if (wxWorkMessageDTO.getMsgtype() == 104){
                    processEmotionDynamicMessage(wxWorkMessageDTO, wxWorkMsgResp, id, userId, sendType);
                }
                // 小程序消息
                else if (wxWorkMessageDTO.getMsgtype() == 78) {
                    processMiniAppMessage(serverId, wxWorkMessageDTO, wxWorkMsgResp, id, userId, sendType);
                }
                break;

        }




        return map;
    }

    /**
     * 小程序消息处理
     * @param serverId          服务器ID
     * @param wxWorkMessageDTO  消息DTO
     * @param wxWorkMsgResp     回调信息对象
     * @param id                企微用户ID
     * @param userId            消息发送者ID
     * @param sendType          发送者类型 1客户 2销售
     */
    private void processMiniAppMessage(Long serverId, WxWorkMessageDTO wxWorkMessageDTO, WxWorkMsgResp wxWorkMsgResp, Long id, Long userId, int sendType) {
        String thumbName = IdUtils.fastSimpleUUID() + ".jpg";
        WxWorkResponseDTO<String> fileUrlResp =
                aiHookService.getFileUrl(wxWorkMsgResp.getUuid(), wxWorkMessageDTO.getThumbFileId(), wxWorkMessageDTO.getThumbAESKey(), 1, thumbName, wxWorkMessageDTO.getSize(), serverId);
        if (fileUrlResp.getErrcode() != 0) {
            log.warn("获取图片地址失败: {}", fileUrlResp.getErrmsg());
            return;
        }

        JSONObject json = new JSONObject();
        json.put("appid", wxWorkMessageDTO.getAppid());
        json.put("appName", wxWorkMessageDTO.getAppName());
        json.put("weappIconUrl", wxWorkMessageDTO.getAppid());
        json.put("desc", wxWorkMessageDTO.getDesc());
        json.put("pagepath", wxWorkMessageDTO.getPagepath());
        json.put("title", wxWorkMessageDTO.getTitle());
        json.put("thumbnail", fileUrlResp.getData());

        // 储存发送参数
        JSONObject params = new JSONObject();
        params.put("desc", wxWorkMessageDTO.getDesc());
        params.put("appName", wxWorkMessageDTO.getAppName());
        params.put("title", wxWorkMessageDTO.getTitle());
        params.put("weappIconUrl", wxWorkMessageDTO.getWeappIconUrl());
        params.put("pagepath", wxWorkMessageDTO.getPagepath());
        params.put("username", wxWorkMessageDTO.getUsername());
        params.put("appid", wxWorkMessageDTO.getAppid());
        params.put("cdnkey", wxWorkMessageDTO.getThumbFileId());
        params.put("md5", wxWorkMessageDTO.getThumbMD5());
        params.put("aeskey", wxWorkMessageDTO.getThumbAESKey());
        params.put("fileSize", wxWorkMessageDTO.getSize());
        params.put("thumbnail", fileUrlResp.getData());
        qwCompanyService.saveSendParams(params);

        // 保存聊天消息
        QwMessageListVO message = aiHookService.saveQwMsg(id, userId, json.toString(), wxWorkMsgResp.getUuid(), sendType, wxWorkMsgResp.getJson(), 5);
        QwImSocket.broadcast(message);
    }

    /**
     * 处理文本消息
     * @param id                企微用户ID
     * @param userId            消息发送者ID
     * @param content           消息内容
     * @param wxWorkMsgResp     回调信息对象
     * @param sendType          发送者类型 1客户 2销售
     */
    private void processTextMessage(Long id, Long userId, String content, WxWorkMsgResp wxWorkMsgResp, Integer sendType) {
        // 保存聊天消息
        QwMessageListVO message = aiHookService.saveQwMsg(id, userId, content, wxWorkMsgResp.getUuid(), sendType, wxWorkMsgResp.getJson(), 1);
        QwImSocket.broadcast(message);
    }

    /**
     * 处理语音消息
     * @param serverId          服务器ID
     * @param wxWorkMessageDTO  消息DTO
     * @param content           翻译后的内容
     * @param wxWorkMsgResp     回调信息对象
     * @param id                企微用户ID
     * @param userId            消息发送者ID
     * @param sendType          发送者类型 1客户 2销售
     */
    private void processVoiceMessage(Long serverId, String content, WxWorkMessageDTO wxWorkMessageDTO, WxWorkMsgResp wxWorkMsgResp, Long id, Long userId, Integer sendType) {
        String voiceFileName = IdUtils.fastSimpleUUID() + ".silk";
        WxWorkResponseDTO<String> fileUrlResp =
                aiHookService.getFileUrl(wxWorkMsgResp.getUuid(), wxWorkMessageDTO.getVoice_id(), wxWorkMessageDTO.getAes_key(), 5, voiceFileName, wxWorkMessageDTO.getVoice_size(), serverId);
        if (fileUrlResp.getErrcode() != 0) {
            log.warn("获取语音地址失败: {}", fileUrlResp.getErrmsg());
            return;
        }

        // silk转map3
        String url = AudioUtils.convertSilk2Mp3(fileUrlResp.getData());
        if (StringUtils.isBlank(url)) {
            log.warn("转换silk语音格式失败");
            return;
        }

        // 转换内容为空时再尝试一次
        if (StringUtils.isBlank(content)) {
            WxwSpeechToTextEntityDTO ste = new WxwSpeechToTextEntityDTO();
            ste.setMsgid(wxWorkMessageDTO.getMsg_id());
            ste.setUuid(wxWorkMsgResp.getUuid());
            WxWorkResponseDTO<WxwSpeechToTextEntityRespDTO> dto = wxWorkService.SpeechToTextEntity(ste, serverId);
            content = dto.getData().getText();
        }

        JSONObject json = new JSONObject();
        json.put("url", url);
        json.put("content", content);

        // 保存聊天消息
        QwMessageListVO message = aiHookService.saveQwMsg(id, userId, json.toString(), wxWorkMsgResp.getUuid(), sendType, wxWorkMsgResp.getJson(), 4);
        QwImSocket.broadcast(message);
    }

    /**
     * 处理图片消息
     * @param serverId          服务器ID
     * @param wxWorkMessageDTO  消息DTO
     * @param wxWorkMsgResp     回调信息对象
     * @param id                企微用户ID
     * @param userId            消息发送者ID
     * @param sendType          发送者类型 1客户 2销售
     */
    private void processImageMessage(Long serverId, WxWorkMessageDTO wxWorkMessageDTO, WxWorkMsgResp wxWorkMsgResp, Long id, Long userId, Integer sendType) {
        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;
        }

        String content = fileUrlResp.getData();
        // 保存聊天消息
        QwMessageListVO message = aiHookService.saveQwMsg(id, userId, content, wxWorkMsgResp.getUuid(), sendType, wxWorkMsgResp.getJson(), 2);
        QwImSocket.broadcast(message);
    }

    /**
     * 处理动态表情消息
     * @param wxWorkMessageDTO  消息DTO
     * @param wxWorkMsgResp     回调信息对象
     * @param id                企微用户ID
     * @param userId            消息发送者ID
     * @param sendType          发送者类型 1客户 2销售
     */
    private void processEmotionDynamicMessage(WxWorkMessageDTO wxWorkMessageDTO, WxWorkMsgResp wxWorkMsgResp, Long id, Long userId, int sendType) {
        String content = wxWorkMessageDTO.getUrl();
        // 保存聊天消息
        QwMessageListVO message = aiHookService.saveQwMsg(id, userId, content, wxWorkMsgResp.getUuid(), sendType, wxWorkMsgResp.getJson(), 3);
        QwImSocket.broadcast(message);
    }

    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);
    }

}
