package com.ruoyi.push;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gexin.rp.sdk.base.IBatch;
import com.gexin.rp.sdk.base.IIGtPush;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.gexin.rp.sdk.template.style.Style0;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.exception.enums.CoreExceptionEnum;
import com.ruoyi.enums.user.UserEnums;
import com.ruoyi.frequency.customer.entity.Customer;
import com.ruoyi.frequency.customer.service.CustomerService;
import com.ruoyi.utils.BusinessUtil;
import com.ruoyi.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author: uniapp消息通知
 * @Description:
 * @Date: Created in 2020/5/12 20:31
 */
@Component
public class PushToSingle {

    private String appId;
    private String appKey;
    private String mastersecret;


    @Value("${push.uniapp.appid}")
    private String userAppId;
    @Value("${push.uniapp.appkey}")
    private String userAppKey;
    @Value("${push.uniapp.mastersecret}")
    private String userMastersecret;

    static final String host = "http://sdk.open.api.igexin.com/apiex.htm";


    //透传消息
    private void constructClientTransMsg(String cid, String msg, IBatch batch, Integer type) throws Exception {

        SingleMessage message = new SingleMessage();
        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setTransmissionContent(msg);
        template.setTransmissionType(2); // 透传消息接受方式设置，1：立即启动APP，2：客户端收到消息后需要自行处理

        template.setAPNInfo(getAPNPayload(msg, null, null)); //详见【推送模板说明】iOS通知样式设置

        message.setData(template);
        message.setOffline(true);
        message.setOfflineExpireTime(24 * 1000 * 3600);
        // 厂商通道下发策略
        message.setStrategyJson("{\"default\":4,\"ios\":4,\"st\":4}");

        // 设置推送目标，填入appid和clientId
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(cid);
        batch.add(message, target);
    }

    //通知消息
    private void constructClientLinkMsg(String cid, String title, String text, IBatch batch, Integer userType) throws Exception {
        SingleMessage message = new SingleMessage();
        NotificationTemplate template = new NotificationTemplate();
        // 设置APPID与APPKEY
        template.setAppId(appId);
        template.setAppkey(appKey);

        Style0 style = new Style0();
        // 设置通知栏标题与内容
        style.setTitle(title);
        style.setText(text);
        // 配置通知栏图标
        style.setLogo("icon.png");
        // 配置通知栏网络图标
        style.setLogoUrl("");
        // 设置通知是否响铃，震动，或者可清除
        style.setRing(true);
        style.setVibrate(true);
        style.setClearable(true);
        template.setStyle(style);

//        template.setAPNInfo(getAPNPayload(title,text,null,null)); //详见【推送模板说明】iOS通知样式设置

        message.setData(template);
        message.setOffline(true);
        message.setOfflineExpireTime(360 * 1000);
        // 厂商通道下发策略
        message.setStrategyJson("{\"default\":4,\"ios\":4,\"st\":4}");

        // 设置推送目标，填入appid和clientId
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(cid);
        batch.add(message, target);
    }


    /**
     * IOS的APNs消息
     *
     * @param body
     * @param badge
     * @param customMsg
     * @return
     */
    private static APNPayload getAPNPayload(String body, String badge, Map<String, String> customMsg) {
        APNPayload payload = new APNPayload();
        JSONObject json = JSONObject.parseObject(body);
        payload.setContentAvailable(0);
        // ios 12.0 以上可以使用 Dictionary 类型的 sound
//            payload.setSound("pushsound.caf");
        payload.addCustomMsg("content", body);
        payload.addCustomMsg("text", json.getString("text"));
        payload.addCustomMsg("title", json.getString("title"));
        payload.addCustomMsg("objectId", json.getString("objectId"));
        payload.addCustomMsg("objectType", json.getString("objectType"));
        payload.addCustomMsg("userType", json.getString("userType"));
        payload.addCustomMsg("type", json.getString("type"));
        payload.setAlertMsg(getDictionaryAlertMsg(body));
        return payload;
    }

    /**
     * IOS通知提示样式
     *
     * @param body
     * @param body
     * @return
     */
    private static APNPayload.DictionaryAlertMsg getDictionaryAlertMsg(String body) {
        APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
        JSONObject json = JSONObject.parseObject(body);
        alertMsg.setBody(json.getString("text"));
//      alertMsg.setActionLocKey("显示关闭和查看两个按钮的消息");
//      alertMsg.setLocKey("loc-key1");
//      alertMsg.addLocArg("loc-ary1");
//      alertMsg.setLaunchImage("调用已经在应用程序中绑定的图形文件名");
        // iOS8.2以上版本支持
        alertMsg.setTitle(json.getString("title"));
//      alertMsg.setTitleLocKey("自定义通知标题");
//      alertMsg.addTitleLocArg("自定义通知标题组");
        return alertMsg;
    }

    @Autowired
    private CustomerService customerService;


    private void setConfig(Integer userType) {

        switch (UserEnums.getUserEnums(userType)){
            case customer:
                this.appId = userAppId;
                this.appKey = userAppKey;
                this.mastersecret = userMastersecret;
                break;
            case store:
                break;
        }
    }

    @Autowired
    private BusinessUtil businessUtil;

    /**
     * @param title
     * @param content
     * @param clientId
     * @param objectId 业务id
     * @param type
     */
//    @Async("sendToAlias")
    public void sendToAlias(UserVo userVo, Integer messageType, String title, String content, String clientId, Long objectId, Long messageId, Integer type) {
        //判断能不能推送

        if (StrUtil.isBlank(clientId)) {
            return;
        }

        Integer closeMessage = (Integer)businessUtil.getUserFieldValue(userVo,"closeMessage");

        if ( closeMessage == 1) {
            return;
        }
        //参数填值
        setConfig(userVo.getUserType());

        IIGtPush push = new IGtPush(host, appKey, mastersecret);
        IBatch batch = push.getBatch();

        try {
            // 透传消息
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("title", title);
            jsonObject.put("text", content);
            jsonObject.put("objectId", objectId + "");
            jsonObject.put("type", type +"");
            jsonObject.put("messageType", messageType +"");
            jsonObject.put("messageId", messageId + "");
            jsonObject.put("content", jsonObject.toString());
            System.out.println(jsonObject.toString());
            //透传 不提示
            constructClientTransMsg(clientId, jsonObject.toString(), batch, type);
            // 通知消息
//            constructClientLinkMsg(clientId, title, text, batch, userType);
            batch.submit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @param clientId
     * @param type
     */
    @Async("sendToAlias")
    public void sendToAliasImplicit(String clientId, Integer type, Integer userType) {
        //判断能不能推送

        if (StrUtil.isBlank(clientId)) {
            return;
        }

        //根据不同的用户类型 判断能不能推送
        switch (userType){
            case 1:
                Customer customer = customerService.getOne(new QueryWrapper<Customer>().lambda()
                        .eq(Customer::getClientId, clientId).last(" limit 1"));
                if (customer == null || customer.getCloseMessage() == 1) {
                    return;
                }
                break;
            default:
                throw new CustomException(CoreExceptionEnum.ERROR_PARAM);
        }

        //参数填值
        setConfig(userType);

        IIGtPush push = new IGtPush(host, appKey, mastersecret);
        IBatch batch = push.getBatch();

        try {
            // 透传消息
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("title", "title");
            jsonObject.put("text", "text");
            jsonObject.put("objectId", "objectId");
            jsonObject.put("type", type);
            jsonObject.put("content", jsonObject.toString());
            System.out.println(jsonObject.toString());
            //透传 不提示
            constructClientTransMsg(clientId, jsonObject.toString(), batch, type);
            // 通知消息
//            constructClientLinkMsg(clientId, title, text, batch, userType);
            batch.submit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param title
     * @param text
     * @param clientId
     * @param objectId   业务id
     * @param objectType
     * @param userType   1 用户 2 商家
     * @param type
     */
    public void sendToAliasUpdateVideo(String title, String text, String clientId, Object objectId, Integer objectType, Integer userType, Integer type, Object[] params) {
        IIGtPush push = new IGtPush(host, appKey, mastersecret);
        IBatch batch = push.getBatch();

        try {
            // 透传消息
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("title", title);
            jsonObject.put("text", text);
            jsonObject.put("objectId", objectId);
            jsonObject.put("objectType", objectType);
            jsonObject.put("userType", userType);
            jsonObject.put("type", type);
            jsonObject.put("likeNum", params[0]);
            jsonObject.put("commentNum", params[2]);
            jsonObject.put("collectNum", params[3]);
            jsonObject.put("isLike", params[4]);
            jsonObject.put("isCollect", params[5]);

            jsonObject.put("content", jsonObject.toString());
            System.out.println(jsonObject.toString());
            //透传 不提示
            constructClientTransMsg(clientId, jsonObject.toString(), batch, type);
            // 通知消息
//            constructClientLinkMsg(clientId, title, text, batch, userType);
            batch.submit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
