package com.yeejoin.amos.jpush.service.jpush;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.yeejoin.amos.jpush.common.enums.JPushTypeEnum;
import com.yeejoin.amos.jpush.service.business.param.PushMsgParam;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.PushPayload.Builder;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.Notification;

@Service
@Component
public class AppMessagePushService {


    protected static final Logger log = LoggerFactory
            .getLogger(AppMessagePushService.class);

    @Value("${params.isPush}")
    private String isPush;

    private static  RestTemplate restTemplate;
    private static ObjectMapper objectMapper = new ObjectMapper();
    //端口443
    protected static final String URL ="https://device.jpush.cn/";
    
    protected static final String APP_KEY = "1b3f7b961200f4b236811dfe";
    protected static final String MASTER_SECRET = "8b650e645fb3a43c96be02b2";
     private static JPushClient jpushClient = new JPushClient(MASTER_SECRET,
            APP_KEY);
    public static String buildJpushUserKey(String userId) {
//        return XJConstant.JPUSH_USER_KEY + "_" + userId;
    	 return  userId;
    }
    public void sendMessage(List<PushMsgParam> responses) {
        try {
            if (responses != null && "true".equals(isPush)) {
                for (PushMsgParam response : responses) {
                    PushPayload payload = buildPushPayload(response);
                    jpushClient.sendPush(payload);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            e.printStackTrace();
        }
    }

    public static PushPayload buildPushPayload(PushMsgParam response) {
     	    Builder builder= PushPayload.newBuilder();
    	    builder.setPlatform(Platform.all());
    	    //设置如果用户不在线、离线消息保存的时间
    	    Options options=Options.sendno();
    	    options.setTimeToLive(86400l);  
    	    options.setApnsProduction(true);  
    	    builder.setOptions(options);
    	    //设置推送方式    	    
    	    List<String> recivers = response.getRecivers();
            List<String> users = Lists.newArrayList();
            recivers.forEach(e -> users.add(buildJpushUserKey(e)));    	    
    	    if (JPushTypeEnum.ALL.getCode().equals(response.getType())) {
    	    	  builder.setAudience(Audience.all());//Audience设置为all，说明采用广播方式推送，所有用户都可以接收到
            } else if (JPushTypeEnum.TAG.getCode().equals(response.getType())) {
            	  builder.setAudience(Audience.tag(users));//根据标签推送
            } else {
            	  builder.setAudience(Audience.alias(users));//根据别名推送
            }
    	    builder.setNotification(Notification.newBuilder()
            .addPlatformNotification(AndroidNotification.newBuilder().addExtras(response.getExtras()).setAlert(response.getContent()).setTitle(response.getSubject()).build())
            .build());
    	    PushPayload pushPayload=builder.build();
    	    return pushPayload;
    }
    
    public void sendMessage(PushMsgParam response) {
        try {
            if (null != response && "true".equals(isPush)) {
           	Builder builder= PushPayload.newBuilder();
          	    builder.setPlatform(Platform.all());          	  
          	    Options options=Options.sendno();
          	    options.setTimeToLive(86400l);  
          	    options.setApnsProduction(true);  
          	    builder.setOptions(options);
          	    //设置推送方式          	    
          	    List<String> recivers = response.getRecivers();
                  List<String> users = Lists.newArrayList();
                  recivers.forEach(e -> users.add(buildJpushUserKey(e)));
                  builder.setAudience(Audience.all());
                  builder.setNotification(Notification.newBuilder()
          	      .addPlatformNotification(AndroidNotification.newBuilder().addExtras(response.getExtras()).setAlert(response.getContent()).setTitle(response.getSubject()).build())
                  .build());
          	      PushPayload payload=builder.build();
                  jpushClient.sendPush(payload);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            e.printStackTrace();

        }
    }
		    public static  void pushNoticeMany( PushMsgParam response){
		    	 PushPayload payload = buildPushPayload(response);
                 try {
					jpushClient.sendPush(payload);
				} catch (APIConnectionException e) {					
					e.printStackTrace();
				} catch (APIRequestException e) {					
					e.printStackTrace();
				}		      
		     }

     //删除一个别名，以及该别名与设备的绑定关系。
	 public static boolean PushDevice(String alias) {
		    CloseableHttpClient httpClient = null;
	        CloseableHttpResponse httpResponse = null;		  
	        try {
	        httpClient = HttpClients.createDefault();
	        HttpDelete httpDelete = new HttpDelete(URL +"v3/aliases/"+alias);		        
	        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)
	                .setConnectionRequestTimeout(35000)
	                .setSocketTimeout(60000)
	                .build();		      
	        httpDelete.setConfig(requestConfig);
	        httpDelete.addHeader("Accept", "application/json");
	        httpDelete.addHeader("Authorization", "Basic "+Base64(APP_KEY+":"+MASTER_SECRET));	       
	      	          
	            httpResponse = httpClient.execute(httpDelete);
	            return true;
	        }  catch (Exception e) {
	        	e.printStackTrace();
	        	 return false;
	        } finally {
	            // 关闭资源
	            if (null != httpResponse) {
	                try {
	                    httpResponse.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	            if (null != httpClient) {
	                try {
	                    httpClient.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
	 }
     //设置设备的别名与标签
	 public static boolean PushDeviceRegistration(String registrationId,String alias) {
		    CloseableHttpClient httpClient = null;
	        CloseableHttpResponse httpResponse = null;	
	        try {
	        httpClient = HttpClients.createDefault();
	        HttpPost httpPost = new HttpPost(URL +"v3/devices/"+registrationId);		        
	        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)
	                .setConnectionRequestTimeout(35000)
	                .setSocketTimeout(60000)
	                .build();		      
	        httpPost.setConfig(requestConfig);
	        httpPost.addHeader("Accept", "application/json");
	        httpPost.addHeader("Authorization", "Basic "+Base64(APP_KEY+":"+MASTER_SECRET));
	        if (null != alias ) {
	            Map<String, Object> nvps = new HashMap<>();
	            // 通过map集成entrySet方法获取entity
	          nvps.put("alias", alias);
	          nvps.put("tags", "");
	          nvps.put("mobile", "");
	          String json= JSON.toJSONString(nvps);
	      	  StringEntity stringEntity = new StringEntity(json,"UTF-8");//解决中文乱码问题
	          httpPost.setEntity(stringEntity);
	          httpResponse = httpClient.execute(httpPost);
	          return true;
	        }else{
	        	 return false;
	        }		         
	        }  catch (Exception e) {
	        	e.printStackTrace();
	        	 return false;
	        } finally {
	            // 关闭资源
	            if (null != httpResponse) {
	                try {
	                    httpResponse.close();
	                } catch (IOException e) {
	                    e.printStackTrace();	                    
	                }
	            }
	            if (null != httpClient) {
	                try {
	                    httpClient.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	        }	      	       
	 }
     //Base64转码
	 public static String  Base64(String code) {
		 final Base64.Encoder encoder = Base64.getEncoder();
		 byte[] textByte;
		 try {
			 textByte = code.getBytes("UTF-8");
			 //编码
			 String encodedText = encoder.encodeToString(textByte);
			 return encodedText;
		} catch (UnsupportedEncodingException e) {			
			e.printStackTrace();
			return "";
		}				
	}
			
}
