package com.upyuns.platform.rs.universal.biz;


import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.ServiceHelper;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
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.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.upyuns.platform.rs.universal.mapper.MessagePushMapper;
import com.upyuns.platform.rs.universal.constant.PushJumpType;
import com.upyuns.platform.rs.universal.constant.PushSendType;
import com.upyuns.platform.rs.universal.entity.MessagePush;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class JPushBiz extends BaseBiz<MessagePushMapper, MessagePush> {


    @Value("${universal.MASTER_SECRET}")
    private  String MASTER_SECRET;
    @Value("${universal.APP_KEY}")
    private  String APP_KEY;

    public static final String ALERT = "Test from API Example - alert";

    //推送给所有平台设备
    public ObjectRestResponse jpushToAllPlat(String title){
        ClientConfig clientConfig = ClientConfig.getInstance();
        final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
        PushPayload payload = PushPayload.alertAll(title);
        try {
            PushResult result = jpushClient.sendPush(payload);
            log.debug("\n推送结果:"+result);
           return  ObjectRestResponse.succ();
        } catch (APIConnectionException e) {
            // Connection error, should retry later
            log.debug("\nConnection error, should retry later"+e);
            return  ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,e.getMessage());
        } catch (APIRequestException e) {
            // Should review the error, and fix the request
            log.debug("\nShould review the error, and fix the request"+ e);
            log.debug("\nHTTP Status: " + e.getStatus());
            log.debug("\nError Code: " + e.getErrorCode());
            log.debug("\nError Message: " + e.getErrorMessage());
            return  ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,e.getMessage());
        }
    }

    //推送给所有平台设备
    public ObjectRestResponse jpushToAllPlat1(){
        ClientConfig clientConfig = ClientConfig.getInstance();
        final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
        PushPayload payload = buildPushObject_android_newly_support();
        try {
            PushResult result = jpushClient.sendPush(payload);
            log.debug("\n推送结果:"+result);
            return  ObjectRestResponse.succ();
        } catch (APIConnectionException e) {
            // Connection error, should retry later
            log.debug("\nConnection error, should retry later"+e);
            return  ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,e.getMessage());
        } catch (APIRequestException e) {
            // Should review the error, and fix the request
            log.debug("\nShould review the error, and fix the request"+ e);
            log.debug("\nHTTP Status: " + e.getStatus());
            log.debug("\nError Code: " + e.getErrorCode());
            log.debug("\nError Message: " + e.getErrorMessage());
            return  ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,e.getMessage());
        }
    }


    public static PushPayload buildPushObject_android_newly_support() {

        JsonObject inbox = new JsonObject();
        inbox.add("line1", new JsonPrimitive("line1 string"));
        inbox.add("line2", new JsonPrimitive("line2 string"));
        inbox.add("contentTitle", new JsonPrimitive("title string"));
        inbox.add("summaryText", new JsonPrimitive("+3 more"));

        JsonObject intent = new JsonObject();
        intent.add("url", new JsonPrimitive("intent:#Intent;component=com.jiguang.push/com.example.jpushdemo.SettingActivity;end"));

        Notification notification = Notification.newBuilder()
                .addPlatformNotification(AndroidNotification.newBuilder()
                        .setAlert("测试通知内容")
                        .setBigPicPath("https://xxtest.upyuns.com/image/app/oyI48qqcy3m38iCFffFc3UeZLcm1s3.png")
                        .setBigText("long text")
                        .setBuilderId(1)
                        .setCategory("CATEGORY_SOCIAL")
                        .setInbox(inbox)
                        .setStyle(3)
                        .setTitle("测试通知标题")
                        .setPriority(1)
                        .setLargeIcon("https://xxtest.upyuns.com/image/admin/stock.jpg")
                        .setIntent(intent)
                        .build())
                .build();
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.all())
                .setNotification(notification)
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .setSendno(ServiceHelper.generateSendno())
                        .build())
                .build();
    }


    //推送
    public ObjectRestResponse jpushToAlias(Integer id,String userIds,String orderNo){
        ClientConfig clientConfig = ClientConfig.getInstance();
        final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
        PushPayload payload = buildPushObject_android_id(id,userIds,orderNo);
        if (payload==null){
            return  ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,"参数无效");
        }
        try {
            PushResult result = jpushClient.sendPush(payload);
            log.debug("\n推送结果:"+result);
            return  ObjectRestResponse.succ();
        } catch (APIConnectionException e) {
            // Connection error, should retry later
            log.debug("\nConnection error, should retry later"+e);
            return  ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,e.getMessage());
        } catch (APIRequestException e) {
            // Should review the error, and fix the request
            log.debug("\nShould review the error, and fix the request"+ e);
            log.debug("\nHTTP Status: " + e.getStatus());
            log.debug("\nError Code: " + e.getErrorCode());
            log.debug("\nError Message: " + e.getErrorMessage());
            return  ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,e.getMessage());
        }
    }


    public  PushPayload buildPushObject_android_id(Integer id,String userIds,String orderNo) {
        Example example =new Example(MessagePush.class);
        example.createCriteria().andEqualTo("id",id).andEqualTo("isDel",0);
        MessagePush messagePush=mapper.selectOneByExample(example);
        if (messagePush==null||messagePush.getType()==null){
            log.info("无有效数据--id=="+id);
            return  null;
        }
        Audience audience=Audience.all();
        if (messagePush.getType()==2){
            if (StringUtils.isBlank(userIds)){
                log.info("无有效数据--type=="+messagePush.getType()+"------userId=="+userIds);
                return  null;
            }
            audience=Audience.alias(userIds);
        }
        JsonObject intent = new JsonObject();
        if (StringUtils.isNotBlank(messagePush.getIntent())){
            intent= getJsonObject(messagePush.getIntent());
        }
        Map<String, String> extras = new HashMap<String, String>();
        extras.put("onclickType",messagePush.getJumpType()+"");
        if (StringUtils.isNotBlank(orderNo)){
        extras.put("orderNo",orderNo);
        }
        String urlJson=messagePush.getUrlJson();
        String url="";
        String title="";
        if (StringUtils.isNotBlank(messagePush.getUrlJson())){
            JSONObject jsonObject=JSONObject.parseObject(urlJson);
             url=jsonObject.getString("url");
             title=jsonObject.getString("title");

        }
        extras.put("url",url);
        extras.put("title",title);
        Notification notification = Notification.newBuilder()
                .addPlatformNotification(AndroidNotification.newBuilder()
                        .setAlert(messagePush.getAlert())
                        .setBigPicPath(messagePush.getBigPicPath())
                        .setBigText(messagePush.getBigText())
                        .setBuilderId(1)
                        .setCategory("CATEGORY_SOCIAL")
                        .setInbox(messagePush.getInbox())
                        .setStyle(messagePush.getStyle())
                        .setTitle(messagePush.getTitle())
                        .setPriority(1)
                        .setIntent(intent)
                        .addExtras(extras)
                        .build())
                .build();
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(audience)
                .setNotification(notification)
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .setSendno(ServiceHelper.generateSendno())
                        .build())
                .build();
    }

    //字符串转JsonObject
    public  JsonObject  getJsonObject(String json){
        Gson g = new Gson();
        return  g.fromJson(json, JsonObject.class);

    }

    //编辑推送内容
    public  ObjectRestResponse updMessagePush(MessagePush messagePush){
       Integer id= messagePush.getId();
       if (id==null){
           insertSelective(messagePush);
       }else {
           updateSelectiveById(messagePush);
       }
       return  ObjectRestResponse.succ();
    }

    //删除推送内容
    public  ObjectRestResponse delMessagePush(Integer id){
        MessagePush messagePush=new MessagePush();
        messagePush.setId(id);
        messagePush.setIsDel(1);
        updateSelectiveById(messagePush);
        return  ObjectRestResponse.succ();
    }

    //获取列表
    public  ObjectRestResponse getList(Integer page,Integer limit,String title,Integer type){
        Example example =new Example(MessagePush.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isDel",0);
        if (StringUtils.isNotBlank(title)){
            criteria.andLike("title","%"+title+"%");
        }
        if (type!=null&&type!=0){
            criteria.andEqualTo("type",type);
        }
        example.setOrderByClause("id desc ");
        return  ObjectRestResponse.succ(PageDataVO.pageInfo(page, limit, ()->mapper.selectByExample(example)));
    }

    //获取枚举列表
    public  List<Map<String,Object>> getSendTypes(){
        return PushSendType.getList();
    }
    //获取枚举列表
    public List<Map<String,Object>> getJumpTypes(){
        return PushJumpType.getList();
    }




}
