package cn.pluss.platform.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.getui.push.v2.sdk.ApiHelper;
import com.getui.push.v2.sdk.GtApiConfiguration;
import com.getui.push.v2.sdk.api.PushApi;
import com.getui.push.v2.sdk.common.ApiResult;
import com.getui.push.v2.sdk.dto.req.Audience;
import com.getui.push.v2.sdk.dto.req.AudienceDTO;
import com.getui.push.v2.sdk.dto.req.Settings;
import com.getui.push.v2.sdk.dto.req.message.PushBatchDTO;
import com.getui.push.v2.sdk.dto.req.message.PushChannel;
import com.getui.push.v2.sdk.dto.req.message.PushDTO;
import com.getui.push.v2.sdk.dto.req.message.PushMessage;
import com.getui.push.v2.sdk.dto.req.message.android.AndroidDTO;
import com.getui.push.v2.sdk.dto.req.message.android.ThirdNotification;
import com.getui.push.v2.sdk.dto.req.message.android.Ups;
import com.getui.push.v2.sdk.dto.req.message.ios.Alert;
import com.getui.push.v2.sdk.dto.req.message.ios.Aps;
import com.getui.push.v2.sdk.dto.req.message.ios.IosDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class MobV2PushUtil {

    public static final String appKey = "9f5Nw6Bvb982HvsN3sG1y5";
    public static final String appId = "jzSkfM0Wsk8uSDL2zwGu07";
    public static final String masterSecret = "rKk62FdLE486boNJHWBPb1";

    public String getToken() throws IOException, NoSuchAlgorithmException {

        Map<String, Object> map = new HashMap<>();
        Long timestamp = new Date().getTime();

        String content = appKey + timestamp + masterSecret;

        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update(content.getBytes("UTF-8"));
        String sign = byte2Hex(messageDigest.digest());

        map.put("sign", sign);
        map.put("timestamp", timestamp);
        map.put("appkey", appKey);

        String json = new ObjectMapper().writeValueAsString(map);

        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> httpEntity = new HttpEntity<>(json, header);

        RestTemplate restTemplate = new RestTemplate();
        // 设置为UTF8编码
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

        String tokenInfo = restTemplate.postForObject(
                "https://restapi.getui.com/v2/" + appId + "/auth", httpEntity,
                String.class);

        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(tokenInfo);
        JsonNode code = jsonNode.get("code");
        if (code.asText().equals("0")) {
            return jsonNode.get("data").get("token").asText();
        }
        return null;
    }

    public static void sendSingleByAlias(List<String> alias, String title, String content, String ext) {

        GtApiConfiguration apiConfiguration = new GtApiConfiguration();
        //填写应用配置，参数在“Uni Push”下的“应用配置”页面中获取
        apiConfiguration.setAppId(appId);
        apiConfiguration.setAppKey(appKey);
        apiConfiguration.setMasterSecret(masterSecret);
        apiConfiguration.setDomain("https://restapi.getui.com/v2/");
        // 实例化ApiHelper对象，用于创建接口对象
        ApiHelper apiHelper = ApiHelper.build(apiConfiguration);

        // 创建对象，建议复用。目前有PushApi、StatisticApi、UserApi
        PushApi pushApi = apiHelper.creatApi(PushApi.class);


        PushBatchDTO pushBatchDTO = new PushBatchDTO();

        for (String value : alias) {
            //根据cid进行单推
            PushDTO<Audience> pushDTO = new PushDTO<Audience>();
            // 设置推送参数，requestid需要每次变化唯一
            pushDTO.setRequestId(System.currentTimeMillis() + "");
            Settings settings = new Settings();
            pushDTO.setSettings(settings);
            //消息有效期，走厂商消息必须设置该值
            settings.setTtl(3600000);

            //在线走个推通道时推送的消息体
            PushMessage pushMessage = new PushMessage();
            pushDTO.setPushMessage(pushMessage);
            //此格式的透传消息由 unipush 做了特殊处理，会自动展示通知栏。开发者也可自定义其它格式，在客户端自己处理。
            //pushMessage.setTransmission(" {title:\"标题\",content:\"内容\",payload:\"快银到账1万元\"}");
            pushMessage.setTransmission(" {title:\"" + title + "\",content:\"" + content + "\"," + ext);

            // 设置接收人信息
            Audience audience = new Audience();
            //audience.addAlias("244");
            audience.addAlias(value);
            //audience.addCid("6a757df41e3861b613daeb93091f4eee");
            pushDTO.setAudience(audience);


            //设置离线推送时的消息体
            PushChannel pushChannel = new PushChannel();
            //安卓离线厂商通道推送的消息体
            AndroidDTO androidDTO = new AndroidDTO();
            Ups ups = new Ups();
            ThirdNotification thirdNotification = new ThirdNotification();
            ups.setNotification(thirdNotification);
            thirdNotification.setTitle("安卓离线展示的标题");
            thirdNotification.setBody("安卓离线展示的内容");
            thirdNotification.setClickType("intent");
            //注意：intent参数必须按下方文档（特殊参数说明）要求的固定格式传值，intent错误会导致客户端无法收到消息
            thirdNotification.setIntent("intent://io.dcloud.unipush/?#Intent;scheme=unipush;launchFlags=0x4000000;component=io.dcloud.HBuilder/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title=测试标题;S.content=测试内容;S.payload=test;end");
            androidDTO.setUps(ups);
            pushChannel.setAndroid(androidDTO);

            //ios离线apn通道推送的消息体
            Alert alert = new Alert();
            alert.setTitle("苹果离线通知栏标题");
            alert.setBody("苹果离线通知栏内容");
            Aps aps = new Aps();
            aps.setContentAvailable(0);
            aps.setSound("default");
            aps.setAlert(alert);
            IosDTO iosDTO = new IosDTO();
            iosDTO.setAps(aps);
            iosDTO.setType("notify");
            pushChannel.setIos(iosDTO);
            pushDTO.setPushChannel(pushChannel);

            pushBatchDTO.addPushDTO(pushDTO);
        }


        ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushBatchByAlias(pushBatchDTO);

        if (apiResult.isSuccess()) {
            // success
            System.out.println(apiResult.getData());
        } else {
            // failed
            System.out.println("code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg());
        }

    }

    /**
     * 将byte转为16进制
     *
     * @param bytes
     * @return
     */
    private static String byte2Hex(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                // 1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }


}
