package cn.newfeifan.mall.module.trade.utils.push;

import cn.hutool.core.codec.Base64;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.newfeifan.mall.module.member.service.user.MemberUserService;
import cn.newfeifan.mall.module.system.dal.dataobject.config.SystemConfigDO;
import cn.newfeifan.mall.module.system.service.config.SystemConfigService;
import cn.newfeifan.mall.module.trade.controller.admin.jpushmessagelog.vo.JPushMessageLogSaveReqVO;
import cn.newfeifan.mall.module.trade.enums.wxmessage.WcChatMessageTemplateIdEnum;
import cn.newfeifan.mall.module.trade.service.jpushmessagelog.JPushMessageLogService;
import cn.newfeifan.mall.module.trade.utils.push.pojo.NotificationData;
import cn.newfeifan.mall.module.trade.utils.push.pojo.Options;
import cn.newfeifan.mall.module.trade.utils.push.pojo.RequestBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class JPushUtils {
    @Value("${jpush.app-key}")
    private String appKey;
    @Value("${jpush.secret}")
    private String secret;

    @Resource
    private JPushMessageLogService jPushService;
    @Resource
    private SystemConfigService configService;
    @Resource
    private MemberUserService memberUserService;

    /**
     * 获取请求体
     *
     * @param rsgIds 极光注册id
     * @param alert  推送内容
     * @param title  推送标题
     * @return 请求体
     */
    public RequestBody getRequestBody(List<String> rsgIds, String alert, String title, String url) {
        RequestBody requestBody = RequestBody.builder().build();
        requestBody.setPlatform("all");
        requestBody.setAudience(new RequestBody.Audience().setRegistration_id(rsgIds));

        NotificationData notificationData = new NotificationData();
        notificationData.setAlert("Hello, content！");
        NotificationData.Notification notification = new NotificationData.Notification();
        notification.setAlert(alert);
        notification.setTitle(title);
        notification.setBuilder_id(1);
        notification.setIntent(new NotificationData.Intent().setUrl("letcgo://gizmos?" + url));

        notificationData.setAndroid(notification);
        requestBody.setNotification(notificationData);

        Options options = Options.builder()
                .time_to_live(86400)
                .classification(1)
                .third_party_channel(Options.ThirdPartyChannel
                        .builder()
                        .huawei(Options.Channel
                                .builder()
                                .importance("NORMAL")
                                .category("WORK")
                                .build())
                        .xiaomi(Options.Channel
                                .builder()
                                .channel_id("NORMAL")
                                .build())
                        .honor(Options.Channel
                                .builder()
                                .importance("NORMAL")
                                .build())
                        .oppo(Options.Channel
                                .builder()
                                .channel_id("message")
                                .build())
                        .vivo(Options.Channel
                                .builder()
                                .distribution("secondary_push")
                                .category("IM")
                                .build())
                        .build())
                .build();
        requestBody.setOptions(options);
        return requestBody;
    }

    /**
     * 获取url
     *
     * @param title        标题
     * @param memberUserId 用户id
     * @param objectId     对象id
     * @return url
     */
    public String getUrl(String title, Long memberUserId, Long objectId) {
        SystemConfigDO redisConfig = configService.getRedisConfig();
        String username = memberUserService.getUsernameByUserId(memberUserId);
        if (title.equals(WcChatMessageTemplateIdEnum.ORDER_DELIVERY2.getName())) {
            //订单已发货
            return redisConfig.getMallDomain() + "/#/pages/order/detail?id=" + objectId + "&username=" + username;
        } else if (title.equals(WcChatMessageTemplateIdEnum.AFTER_SALE_CHECK2.getName())) {
            //售后订单审核完成
            return redisConfig.getMallDomain() + "/#/pages/order/aftersale/detail?id=" + objectId + "&username=" + username;
        } else if (title.equals(WcChatMessageTemplateIdEnum.AFTER_SALE_NO_CHECK2.getName())) {
            //售后订单待审核
            return redisConfig.getMerchantDomain() + "/after-sale";
        } else if (title.equals(WcChatMessageTemplateIdEnum.ORDER_NO_DELIVERY2.getName())) {
            //订单待发货
            return redisConfig.getMerchantDomain() + "/order";
        }
        return null;
    }

    /**
     * 推送消息
     */
    public void jPush(RequestBody requestBody, Long memberUserId, Long systemUserId, Long objectId) {
        String url = "https://api.jpush.cn/v3/push";

        String authString = appKey + ":" + secret;
        String encodedAuthString = Base64.encode(authString);


        try {
            RequestConfig clientConfig = RequestConfig.custom().setConnectionRequestTimeout(30000).setSocketTimeout(30000).setConnectTimeout(30000).build();
            CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(clientConfig).build();

            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Authorization", "Basic " + encodedAuthString);
            httpPost.setHeader("Content-Type", "application/json");
            JSONObject message = JSONUtil.parseObj(JSONUtil.toJsonStr(requestBody));
            httpPost.setEntity(new StringEntity(message.toString(), ContentType.APPLICATION_JSON));

            CloseableHttpResponse execute = client.execute(httpPost);

            int statusCode = execute.getStatusLine().getStatusCode();
            log.info("请求状态:{}", statusCode);

            HttpEntity entity = execute.getEntity();
            String str = EntityUtils.toString(entity);
            log.info("请求结果:{}", str);

            // 记录推送日志
            JPushMessageLogSaveReqVO jPushMessageLogSaveReqVO = JPushMessageLogSaveReqVO.builder()
                    .regId(JSONUtil.toJsonStr(requestBody.getAudience().getRegistration_id()))
                    .memberUserId(memberUserId)
                    .systemUserId(systemUserId)
                    .objectId(objectId)
                    .jpushParams(message.toString())
                    .sendTime(LocalDateTime.now())
                    .responseResult(str)
                    .build();
            jPushService.createJPushMessageLog(jPushMessageLogSaveReqVO);
        } catch (Exception e) {
            log.info("用户rsgId:{}", JSONUtil.toJsonStr(requestBody.getAudience().getRegistration_id()));
            log.info("推送异常:{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }
}
