package com.zanxiang.game.module.sdk.service.impl;

import cn.hutool.http.ContentType;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zanxiang.game.module.base.pojo.enums.StatusEnum;
import com.zanxiang.game.module.mybatis.entity.ListenCall;
import com.zanxiang.game.module.sdk.pojo.result.CardCheckResult;
import com.zanxiang.game.module.sdk.pojo.result.IpCheckResult;
import com.zanxiang.game.module.sdk.service.IAliApiService;
import com.zanxiang.game.module.sdk.service.IListenCallService;
import com.zanxiang.module.util.JsonUtil;
import com.zanxiang.module.util.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;

import java.util.List;

/**
 * @author : lingfeng
 * @time : 2023-12-12
 * @description : 阿里云市场api
 */
@Slf4j
@Service
public class AliApiServiceImpl implements IAliApiService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IListenCallService listenCallService;

    /**
     * 云市场应用标识
     */
    private final String APP_CODE = "f395b1587fc04a49a975f908660fb1e9";

    @Override
    public void listenCall(Long gameId, String param) {
        List<ListenCall> listenCallList = listenCallService.list(new LambdaQueryWrapper<ListenCall>()
                .eq(ListenCall::getGameId, gameId)
                .eq(ListenCall::getStatus, StatusEnum.YES.getCode())
        );
        if (CollectionUtils.isEmpty(listenCallList)) {
            return;
        }
        listenCallList.forEach(listenCall -> this.phoneCall(param, listenCall.getPhoneNum()));
    }

    @Override
    public void phoneCall(String param, String mobile) {
        RestTemplate restTemplate = new RestTemplate();
        String host = "https://jumfixed.market.alicloudapi.com/voice-notify/send";
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "APPCODE " + this.APP_CODE);
        headers.set("Content-Type", ContentType.FORM_URLENCODED.getValue());
        //参数
        MultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>();
        requestParams.add("mobile", mobile);
        requestParams.add("templateId", "JMJNAWUQOJP9");
        requestParams.add("param", param);
        String result = null;
        try {
            ResponseEntity<String> responseEntity = restTemplate.exchange(host, HttpMethod.POST,
                    new HttpEntity<>(requestParams, headers), String.class);
            result = responseEntity.getBody();
        } catch (Exception e) {
            log.error("阿里语音呼叫失败, requestParams : {}, e : {}", JsonUtil.toString(requestParams), e.getMessage());
        }
        log.error("阿里语音呼叫结果, result : {}", result);
    }

    @Override
    public Tuple2<Boolean, String> userCardCheck(String cardName, String cardId) {
        String url = "https://eid.shumaidata.com/eid/check";
        //请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "APPCODE " + this.APP_CODE);
        MultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>();
        requestParams.add("name", cardName);
        requestParams.add("idcard", cardId);
        CardCheckResult result;
        try {
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST,
                    new HttpEntity<>(requestParams, headers), String.class);
            String body = responseEntity.getBody();
            result = JsonUtil.toObj(body, CardCheckResult.class);
        } catch (Exception e) {
            log.error("请求阿里实名认证接口异常, cardName : {}, cardId : {}, e : {}", cardName, cardId, e.getMessage());
            throw new BaseException("请求阿里实名认证接口异常");
        }
        if (result == null || result.isFail()) {
            log.error("请求阿里实名认证接口返回值为空,cardName : {},cardId : {}, result : {}", cardName, cardId, JsonUtil.toString(result));
            throw new BaseException("实名认证失败");
        }
        log.error("实名认证结果, result : {}", JsonUtil.toString(result));
        return Tuples.of(result.past(), result.getAddress());
    }

    @Override
    public IpCheckResult userIpCheck(String ip) {
        String url = "https://ipcity.market.alicloudapi.com/ip/city/query";
        //构造请求参数
        UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(url).queryParam("ip", ip);
        //请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "APPCODE " + this.APP_CODE);
        RequestEntity<Object> requestEntity = new RequestEntity<>(headers, HttpMethod.GET, uriBuilder.build().toUri());
        //请求
        IpCheckResult result;
        try {
            ResponseEntity<String> responseEntity = restTemplate.exchange(requestEntity, String.class);
            String body = responseEntity.getBody();
            result = JsonUtil.toObj(body, IpCheckResult.class);
        } catch (Exception e) {
            log.error("请求阿里ip检测接口异常, ip : {}, e : {}", ip, e.getMessage());
            throw new BaseException("请求阿里ip监测接口异常");
        }
        if (result == null || result.isFail()) {
            log.error("请求阿里ip检测接口返回值为空, ip : {}, result : {}", ip, JsonUtil.toString(result));
            throw new BaseException("请求阿里ip检测接口返回值为空");
        }
        log.error("ip检测结果, result : {}", JsonUtil.toString(result));
        return result;
    }
}
