package com.zanxiang.game.module.manage.service.api;

import com.zanxiang.game.module.base.ServerInfo;
import com.zanxiang.game.module.base.rpc.IWxApiServiceRpc;
import com.zanxiang.game.module.manage.pojo.dto.GameAppletDTO;
import com.zanxiang.game.module.manage.pojo.dto.KfUploadTempMediaDTO;
import com.zanxiang.game.module.manage.service.IGameAppletService;
import com.zanxiang.module.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;

import java.net.URI;
import java.util.Map;

/**
 * @author : lingfeng
 * @time : 2024-02-26
 * @description : 客服聊天腾讯API接口
 */
@Slf4j
@Service
public class KfWxApiService {

    @Autowired
    private RestTemplate restTemplate;

    @DubboReference(providedBy = ServerInfo.SERVER_SDK_DUBBO_NAME)
    private IWxApiServiceRpc wxApiServiceRpc;

    @Autowired
    private IGameAppletService gameAppletService;

    /**
     * 通过腾讯API给玩家发送消息
     */
    public Tuple2<Long, String> sendCustomMessageApi(Long gameId, Map<String, Object> msgParamMap) {
        GameAppletDTO gameAppletDTO = gameAppletService.getByGameId(gameId);
        if (gameAppletDTO == null) {
            return Tuples.of(400L, "小程序信息不存在");
        }
        //客服消息参数构造
        log.error("客服消息发送参数, paramMap : {}", JsonUtil.toString(msgParamMap));
        //获取接口token
        String accessToken = wxApiServiceRpc.getAccessToken(gameAppletDTO.getAppId(), gameAppletDTO.getAppSecret());
        URI uri = UriComponentsBuilder.fromHttpUrl("https://api.weixin.qq.com/cgi-bin/message/custom/send")
                .queryParam("access_token", accessToken)
                .build().toUri();
        // 发送请求
        String result;
        try {
            result = restTemplate.postForObject(uri, msgParamMap, String.class);
        } catch (Exception e) {
            log.error("客服消息发送异常, e : {}", e.getMessage());
            return Tuples.of(400L, e.getMessage());
        }
        log.error("客服消息发送结果, result : {}", result);
        Map<String, String> resultMap = JsonUtil.toMap(result, Map.class, String.class);
        return Tuples.of(Long.valueOf(resultMap.get("errcode")), resultMap.get("errmsg"));
    }

    /**
     * 上传临时素材
     */
    public Tuple2<Long, String> mediaUpload(Long gameId, MultipartFile files) {
        GameAppletDTO gameAppletDTO = gameAppletService.getByGameId(gameId);
        if (gameAppletDTO == null) {
            return Tuples.of(400L, "小程序信息不存在");
        }
        //客服消息参数构造
        log.error("客服消息发送参数, gameId : {}", gameId);
        //获取接口token
        String accessToken = wxApiServiceRpc.getAccessToken(gameAppletDTO.getAppId(), gameAppletDTO.getAppSecret());
        URI uri = UriComponentsBuilder.fromHttpUrl("https://api.weixin.qq.com/cgi-bin/media/upload")
                .queryParam("access_token", accessToken)
                .queryParam("type", "image")
                .build().toUri();
        //最外层请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        //素材内容请求头
        HttpHeaders formHeader = new HttpHeaders();
        formHeader.setContentDispositionFormData("media", files.getOriginalFilename());
        formHeader.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<Resource> formEntity = new HttpEntity<>(files.getResource(), formHeader);
        map.add("media", formEntity);
        //http请求头
        HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(map, httpHeaders);
        String result;
        try {
            result = restTemplate.postForObject(uri, httpEntity, String.class);
        } catch (Exception e) {
            log.error("客服消息上传临时素材异常, e : {}", e.getMessage());
            return Tuples.of(400L, e.getMessage());
        }
        log.error("客服消息上传临时素材结果, result : {}", result);
        KfUploadTempMediaDTO resultDTO = JsonUtil.toObj(result, KfUploadTempMediaDTO.class);
        log.error("客服消息上传临时素材结果, resultDTO : {}", resultDTO);
        //返回
        return resultDTO.isSuccess() ? Tuples.of(KfUploadTempMediaDTO.CODE_SUCCESS, resultDTO.getMedia_id())
                : Tuples.of(resultDTO.getErrcode(), resultDTO.getErrmsg());
    }
}
