package com.fs.wxwork.service;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fs.aiSoundReplication.param.TtsRequest;
import com.fs.aiSoundReplication.service.impl.TtsServiceImpl;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.exception.CustomException;
import com.fs.company.mapper.CompanyUserMapper;
import com.fs.company.param.VcCompanyUser;
import com.fs.config.ai.AiHostProper;
import com.fs.fastgptApi.vo.AudioVO;
import com.fs.qw.domain.QwIpadServer;
import com.fs.qw.service.IQwIpadServerService;
import com.fs.wxwork.dto.*;
import com.fs.wxwork.utils.WxWorkHttpUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
@RequiredArgsConstructor
public class WxWorkServiceImpl implements WxWorkService {
    /**
     * 基础地址
     */
    //private static final String BASE_URL = "http://47.94.7.218:8089/wxwork";
    @Autowired
    RedisCache redisCache;
    @Autowired
    IQwIpadServerService qwIpadServerService;
    @Autowired
    AiHostProper aiHostProper;
    @Autowired
    private CompanyUserMapper companyUserMapper;
    @Autowired
    private TtsServiceImpl ttsServiceImpl;

    public String getUrl(Long serverId) {
        String url = redisCache.getCacheObject("serverId:" + serverId);
        if (url != null && !url.isEmpty()) {
            return url;
        }
        System.out.println("serverId:" + serverId);
        QwIpadServer qwIpadServer = qwIpadServerService.selectQwIpadServerById(serverId);
        if (qwIpadServer == null || qwIpadServer.getUrl() == null) {
            throw new CustomException("未获取到服务地址与端口");
        }
        redisCache.setCacheObject("serverId:" + serverId, qwIpadServer.getUrl(), 2, TimeUnit.HOURS);
        return qwIpadServer.getUrl();
    }


    private static final String BASE_URL = "http://36.138.18.118:8083/wxwork";

    @Override
    public WxWorkResponseDTO<WxWorkInitRespDTO> init(WxWorkInitDTO param, Long serverId) {
        String url = getUrl(serverId) + "/init";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxWorkInitRespDTO>>() {
        });
    }

    @Override
    public WxWorkResponseDTO SetCallbackUrl(WxWorkSetCallbackUrlDTO param, Long serverId) {
        String url = getUrl(serverId) + "/SetCallbackUrl";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO>() {
        });
    }

    @Override
    public WxWorkResponseDTO<WxWorkSendTextMsgRespDTO> SendTextMsg(WxWorkSendTextMsgDTO param, Long serverId) {
        String url = getUrl(serverId) + "/SendTextMsg";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxWorkSendTextMsgRespDTO>>() {
        });
    }

    @Override
    public WxWorkSendAppMsgRespDTO SendAppMsg(WxWorkSendAppMsgDTO param, Long serverId) {
        String url = getUrl(serverId) + "/SendAppMsg";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkSendAppMsgRespDTO>() {
        });
    }

    @Override
    public WxWorkResponseDTO<WxwSendLinkMsgRespDTO> SendLinkMsg(WxwSendLinkMsgDTO param, Long serverId) {
        String url = getUrl(serverId) + "/SendLinkMsg";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxwSendLinkMsgRespDTO>>() {
        });
    }

    @Override
    public WxWorkResponseDTO<WxWorkGetQrCodeRespDTO> getQrCode(WxWorkGetQrCodeDTO param, Long serverId) {
        String url = getUrl(serverId) + "/getQrCode";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxWorkGetQrCodeRespDTO>>() {
        });
    }

    @Override
    public WxWorkResponseDTO<List<WxwGetExternalContactRespDTO>> getExternalContacts(WxwGetExternalContactsDTO param, Long serverId) {
        String url = getUrl(serverId) + "/GetExternalContacts";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<List<WxwGetExternalContactRespDTO>>>() {
        });
    }

    @Override
    public WxWorkResponseDTO<WxwGetExternalContactsPageDTO> getIpadExternalContactPage(WxwGetExternalContactsDTO param, Long serverId) {
        String url = getUrl(serverId) + "/GetExternalContacts";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxwGetExternalContactsPageDTO>>() {
        });
    }

    @Override
    public WxWorkResponseDTO CheckCode(WxWorkCheckCodeDTO param, Long serverId) {
        String url = getUrl(serverId) + "/CheckCode";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO>() {
        });
    }

    @Override
    public WxWorkResponseDTO<WxwSecondaryValidationRespDTO> SecondaryValidation(WxWorkGetQrCodeDTO param, Long serverId) {
        String url = getUrl(serverId) + "/SecondaryValidation";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxwSecondaryValidationRespDTO>>() {
        });
    }

    @Override
    public WxWorkResponseDTO automaticLogin(WxWorkGetQrCodeDTO param, Long serverId) {
        String url = getUrl(serverId) + "/automaticLogin";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO>() {
        });
    }

    @Override
    public WxWorkResponseDTO<WxwLoginOutRespDTO> LoginOut(WxWorkGetQrCodeDTO param, Long serverId) {
        String url = getUrl(serverId) + "/LoginOut";
        try {
            return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxwLoginOutRespDTO>>() {
            });
        } catch (Exception e) {
            log.error("LoginOut error", e);
            return null;
        }

    }

    @Override
    public WxWorkResponseDTO<WxwMarkAsReadRespDTO> MarkAsRead(WxwMarkAsReadDTO param, Long serverId) {
        String url = getUrl(serverId) + "/MarkAsRead";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxwMarkAsReadRespDTO>>() {
        });
    }

    @Override
    public WxWorkResponseDTO<WxwSendGroupsMsgRespDTO> SendGroupsMsg(WxwSendGroupsMsgDTO param, Long serverId) {
        String url = getUrl(serverId) + "/SendGroupsMsg";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxwSendGroupsMsgRespDTO>>() {
        });
    }

    @Override
    public WxWorkResponseDTO<WxwGetRunClientRespDTO> getRunClient(Long serverId) {
        String url = getUrl(serverId) + "/GetRunClient";
        return WxWorkHttpUtil.postWithType(url, null, new TypeReference<WxWorkResponseDTO<WxwGetRunClientRespDTO>>() {
        });
    }

    @Override
    public WxWorkResponseDTO RevokeMsg(WxwRevokeMsgDTO param, Long serverId) {
        String url = getUrl(serverId) + "/RevokeMsg";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO>() {
        });
    }

    @Override
    public WxWorkResponseDTO<WxwSendCDNImgMsgRespDTO> SendCDNImgMsg(WxwSendCDNImgMsgDTO param, Long serverId) {
        String url = getUrl(serverId) + "/SendCDNImgMsg";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxwSendCDNImgMsgRespDTO>>() {
        });

    }

    @Override
    public WxWorkResponseDTO<WxwSendCDNFileMsgRespDTO> SendCDNFileMsg(WxwSendCDNFileMsgDTO param, Long serverId) {
        String url = getUrl(serverId) + "/SendCDNFileMsg";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxwSendCDNFileMsgRespDTO>>() {
        });
    }

    @Override
    public WxWorkResponseDTO<WxwSendCDNVoiceMsgRespDTO> SendCDNVoiceMsg(WxwSendCDNVoiceMsgDTO param, Long serverId) {
        String url = getUrl(serverId) + "/SendCDNVoiceMsg";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxwSendCDNVoiceMsgRespDTO>>() {
        });
    }

    @Override
    public WxWorkResponseDTO<WxwSendCDNVideoMsgRespDTO> SendCDNVideoMsg(WxwSendCDNVideoMsgDTO param, Long serverId) {
        String url = getUrl(serverId) + "/SendCDNVideoMsg";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxwSendCDNVideoMsgRespDTO>>() {
        });
    }

    @Override
    public WxWorkResponseDTO<WxwSendVideoNumberRespDTO> sendVideoNumber(WxwSendVideoNumberDTO param, Long serverId) {
        String url = getUrl(serverId) + "/SendVideoNumber";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxwSendVideoNumberRespDTO>>() {
        });
    }

    @Override
    public WxWorkResponseDTO<WxwSendEmotionMessageRespDTO> SendEmotionMessage(WxwSendEmotionMessageDTO param, Long serverId) {
        String url = getUrl(serverId) + "/SendEmotionMessage";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxwSendEmotionMessageRespDTO>>() {
        });
    }

    @Override
    public WxWorkResponseDTO<WxwSendBusinessCardMsgRespDTO> SendBusinessCardMsg(WxwSendBusinessCardMsgDTO param, Long serverId) {
        String url = getUrl(serverId) + "/SendBusinessCardMsg";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxwSendBusinessCardMsgRespDTO>>() {
        });
    }

    @Override
    public WxWorkResponseDTO<WxwSendLocationMsgRespDTO> SendLocationMsg(WxwSendLocationMsgDTO param, Long serverId) {
        String url = getUrl(serverId) + "/SendLocationMsg";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxwSendLocationMsgRespDTO>>() {
        });
    }

    @Override
    public WxWorkResponseDTO<WxwSendTextAtMsgTwoRespDTO> sendTextAtMsgTwo(WxwSendTextAtMsgTwoDTO param, Long serverId) {
        String url = getUrl(serverId) + "/SendTextAtMsgTwo";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxwSendTextAtMsgTwoRespDTO>>() {
        });
    }

    @Override
    public WxWorkResponseDTO<WxwSyncAllDataRespDTO> syncAllData(WxwSyncAllDataDTO param, Long serverId) {
        String url = getUrl(serverId) + "/SyncAllData";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxwSyncAllDataRespDTO>>() {
        });
    }

    @Override
    public WxWorkResponseDTO<WxwSendCDNBigVideoMsgRespDTO> SendCDNBigVideoMsg(WxwSendCDNBigVideoMsgDTO param, Long serverId) {
        String url = getUrl(serverId) + "/SendCDNBigVideoMsg";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxwSendCDNBigVideoMsgRespDTO>>() {
        });
    }

    @Override
    public String getCorpId(String uuid, Long corpId, Long serverId) {
        String sCorpId = redisCache.getCacheObject("ipad:corpId:" + corpId);
        if (sCorpId != null && !sCorpId.isEmpty()) {

            return sCorpId;
        }
        String url = getUrl(serverId) + "/GetCorpInfo";
        WxWorkCorpDTO param = new WxWorkCorpDTO();
        param.setUuid(uuid);
        param.setCorpid(corpId);

        WxWorkResponseDTO<WxWorkCorpRespDTO> listWxWorkResponseDTO = WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxWorkCorpRespDTO>>() {
        });
        WxWorkCorpRespDTO data = listWxWorkResponseDTO.getData();
        List<WxWorkCorpRespDTO.CorpInfo> list = data.getList();
        if (list != null && !list.isEmpty()) {

            WxWorkCorpRespDTO.CorpInfo corpInfo = list.get(0);


            String scorpId = corpInfo.getScorp_id();

            if (scorpId != null && !scorpId.isEmpty()) {
                redisCache.setCacheObject("ipad:corpId:" + corpId, scorpId);

                return scorpId;
            }
        }

        return "";
    }

    @Override
    public WxWorkResponseDTO<List<WxWorkVid2UserIdRespDTO>> Vid2UserId(WxWorkVid2UserIdDTO param, Long serverId) {
        String url = getUrl(serverId) + "/Vid2UserId";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<List<WxWorkVid2UserIdRespDTO>>>() {
        });
    }

    @Override
    public WxWorkResponseDTO<WxwSpeechToTextEntityRespDTO> SpeechToTextEntity(WxwSpeechToTextEntityDTO param, Long serverId) {
        String url = getUrl(serverId) + "/SpeechToTextEntity";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxwSpeechToTextEntityRespDTO>>() {
        });
    }

    @Override
    public WxWorkResponseDTO<WxwUploadCdnLinkFileRespDTO> uploadCdnLinkFile(WxwUploadCdnLinkFileDTO param, Long serverId) {

        String url = getUrl(serverId) + "/UploadCdnLinkFile";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxwUploadCdnLinkFileRespDTO>>() {
        });
    }

    @Override
    public WxWorkResponseDTO<WxwUploadCdnLinkImgRespDTO> uploadCdnLinkImg(WxwUploadCdnLinkImgDTO param, Long serverId) {
        String url = getUrl(serverId) + "/CdnUploadImgLink";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxwUploadCdnLinkImgRespDTO>>() {
        });
    }

    @Override
    public WxwSilkVoceDTO getSilkVoice(String param, Long companyUserId) {
        String url = aiHostProper.getVoiceApi() + "/app/common/voice?voice=" + param + "&id=" + companyUserId;
        String json = WxWorkHttpUtil.get(url);
        WxwSilkVoceDTO wxwSilkVoceDTO = JSON.parseObject(json, WxwSilkVoceDTO.class);
        return wxwSilkVoceDTO;
    }

    @Override
    public WxWorkResponseDTO<List<WxWorkVid2UserIdRespDTO>> UserId2Vid(WxWorkUserId2VidDTO param, Long serverId) {
        String url = getUrl(serverId) + "/UserId2Vid";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<List<WxWorkVid2UserIdRespDTO>>>() {
        });
    }

    /**
     * 外部联系人图片视频文件下载
     *
     * @param param    参数
     * @param serverId 服务器ID
     * @return WxWorkResponseDTO
     */
    @Override
    public WxWorkResponseDTO<String> downloadWeChatFile(WxwDownloadWeChatFileDTO param, Long serverId) {
        String url = getUrl(serverId) + "/DownloadWeChatFile";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<String>>() {
        });
    }

    /**
     * CDN下载文件重置版本
     *
     * @param param    参数
     * @param serverId 服务器ID
     * @return WxWorkResponseDTO
     */
    @Override
    public WxWorkResponseDTO<String> downloadFile(WxDownloadFileDTO param, Long serverId) {
        String url = getUrl(serverId) + "/DownloadFile";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<String>>() {
        });
    }

    /**
     * CDN上传网络图片
     *
     * @param param    参数
     * @param serverId 服务器ID
     * @return WxWorkResponseDTO
     */
    @Override
    public WxWorkResponseDTO<WxCdnUploadImgLinkResp> cdnUploadImgLink(WxCdnUploadImgLinkDTO param, Long serverId) {
        String url = getUrl(serverId) + "/CdnUploadImgLink";
        return WxWorkHttpUtil.postWithType(url, param, new TypeReference<WxWorkResponseDTO<WxCdnUploadImgLinkResp>>() {
        });
    }

    @Override
    public WxwSilkVoceDTO getSilkVoiceDoubao(String content, Long companyUserId) {
        VcCompanyUser vcCompanyUser = companyUserMapper.selectVcCompanyUserByCompanyUserId(companyUserId);
        try {
            if (vcCompanyUser == null)throw new RuntimeException("用户不存在");
        }catch (Exception e){
            log.error(String.format("用户id不存在于豆包: %s",companyUserId));
            return null;
        }

        AudioVO audioVO = ttsServiceImpl.textToSpeech(new TtsRequest(null,null,vcCompanyUser.getSpeakerId(),content));
        vcCompanyUser.setLatestTextToSpeechUrl(audioVO.getUrl());
        companyUserMapper.updateVcCompanyUser(vcCompanyUser);
        WxwSilkVoceDTO wxwSilkVoceDTO = new WxwSilkVoceDTO();
        WxwSilkVoceDTO.Data data = new WxwSilkVoceDTO.Data();
        data.setUrl(audioVO.getUrl());
        data.setDuration(audioVO.getDuration());
        wxwSilkVoceDTO.setData(data);
        wxwSilkVoceDTO.setCode(200);
        log.info("豆包语音生成成功，url: {}", (audioVO.getUrl()));
        return wxwSilkVoceDTO;
    }
}
