package com.xxfc.platform.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.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
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.xxfc.platform.universal.constant.PushJumpType;
import com.xxfc.platform.universal.constant.PushSendType;
import com.xxfc.platform.universal.entity.MessagePush;
import com.xxfc.platform.universal.mapper.MessagePushMapper;
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;

    @Value("${universal.DEBUG}")
    private  boolean debug;

    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 {
            log.debug("\n推送参数:"+payload.toJSON());
            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;
            }
            String [] userIdList=userIds.split(",");
            audience=Audience.alias(userIdList);
        }else {
            if (!debug){
                String [] userIdList=userIds.split(",");
                audience=Audience.alias(userIdList);
            }
        }
        JsonObject intent = new JsonObject();
        if (StringUtils.isNotBlank(messagePush.getIntent())){
            intent= getJsonObject(messagePush.getIntent());
        }
        Map<String, String> extras = new HashMap<>();
        extras.put("onclickType",messagePush.getJumpType()+"");
        if (StringUtils.isNotBlank(orderNo)){
        extras.put("orderNo",orderNo);
        }
        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())
                .addPlatformNotification(IosNotification.newBuilder()
                        .setAlert(messagePush.getAlert())
                        .setBadge(1)
                        .setSound("default")
                        .setMutableContent(true)
                        .addExtras(setExtras(extras,messagePush))
                        .build())
                .build();
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(audience)
                .setNotification(notification)
                .setOptions(Options.newBuilder()
                        .setApnsProduction(debug)
                        .setSendno(ServiceHelper.generateSendno())
                        .build())
                .build();
    }

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

    }

    public  Map<String, String>  setExtras(Map<String, String> extras,MessagePush messagePush){
        Integer style=messagePush.getStyle();
        switch (style){
            case  1:
                extras.put("push_title",messagePush.getTitle());
            case  2:
                extras.put("push_title",messagePush.getTitle());
            case  3:
                extras.put("push_title",messagePush.getTitle());
                extras.put("big_pic_path",messagePush.getBigPicPath());
        }

        return extras;
    }

    //编辑推送内容
    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);
        }
        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();
    }




}
