package com.iotechn.unimall.biz.service.notify;

import com.iotechn.unimall.core.util.SHAUtil;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * Description: 借用Uni-Notify 公共服务器推送通知的实现
 * User: rize
 * Date: 2019/12/27
 * Time: 16:19
 */
public class UniNotifyAdminNotifyBizServiceImpl implements AdminNotifyBizService {

    @Value("${com.iotechn.admin.notify.uninotify.app-id}")
    private String appId;

    @Value("${com.iotechn.admin.notify.uninotify.app-secret}")
    private String appSecret;

    @Value("${com.iotechn.admin.notify.uninotify.url}")
    private String serverUrl;

    private  OkHttpClient okHttpClient = new OkHttpClient();

    private static  Logger logger = LoggerFactory.getLogger(UniNotifyAdminNotifyBizServiceImpl.class);

    @Override
    public void newOrder() {
        try {
            FormBody formBody = new FormBody.Builder()
                    .add("_gp", "template")
                    .add("_mt", "newOrderNotify")
                    //要通知的管理员Id
                    .add("userId", "admin")
                    .add("appId", this.appId)
                    .add("timestamp", System.currentTimeMillis() + "")
                    .build();
            String sign = getSign(formBody);
            String string = okHttpClient.newCall(new Request.Builder().url(serverUrl + "?sign=" + sign).post(formBody).build()).execute().body().string();
            logger.info(string);
        } catch (Exception e) {
            logger.error("[通知管理员] 异常", e);
        }
    }

    private String getSign(FormBody formBody) throws Exception {
        Set<String> sortSet = new TreeSet<>();
        for (int i = 0; i < formBody.size(); i++) {
            sortSet.add(formBody.value(i));
        }
        sortSet.add(this.appSecret);
        return SHAUtil.shaEncode(URLEncoder.encode(sortSet.stream().collect(Collectors.joining()), "utf-8"));
    }
}
