package com.fs.gtPush.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.gtPush.domain.PushReqBean;
import com.fs.gtPush.domain.PushResult;
import com.fs.gtPush.domain.UniPushLog;
import com.fs.gtPush.service.UniPushLogService;
import com.fs.gtPush.service.uniPush2Service;
import com.fs.gtPush.utils.PushUtils;
import com.fs.qw.mapper.QwExternalContactMapper;
import com.fs.qw.vo.QwExternalContactFsUserVO;
import com.fs.store.domain.FsUser;
import com.fs.store.service.IFsUserService;
import com.fs.voice.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class uniPush2ServiceImpl implements uniPush2Service {
    private static final String url = "https://fc-mp-de6e03a9-c1a3-439b-9eec-d0dc3c565e4e.next.bspapp.com/push";
    @Autowired
    private UniPushLogService logService;
    @Autowired
    private IFsUserService userService;

    @Autowired
    private QwExternalContactMapper qwExternalContactMapper;

    @Override
    public PushResult pushMessage(PushReqBean push) {
        String result = HttpUtil.post(url, JSON.toJSONString(push));
        return JSONUtil.toBean(result, PushResult.class);
    }


    @Override
    public void pushOne(Long userId, Long businessId, String purl, String title, String content, Float type, Integer desType) {
        PushReqBean param = getParam(userId, purl,title,content,type);
        PushResult pushResult = null;
        UniPushLog pushAddLog = new UniPushLog();
        if (param != null) {
            pushResult = pushMessage(param); //推送消息
            pushAddLog.setJpushId(param.getPush_clientid().toString());
            pushAddLog.setPushMsg(JSON.toJSONString(param));

        }
        pushAddLog.setType(type);
        pushAddLog.setDesType(desType);
        pushAddLog.setUserId(userId);
        pushAddLog.setBusinessId(businessId);
        pushAddLog.setCreateTime(DateUtils.getNowDate());
        UniPushLog uniPushLog = PushUtils.returnMsg(pushResult,pushAddLog);
        logService.insertUniPushLog(uniPushLog);
    }

    @Override
    public PushReqBean getParam(Long userId,String purl,String title,String content,Float type){
        if (userId !=null) {
            FsUser fsUser = userService.selectFsUserByUserId(userId);
            if (fsUser !=null){
                String jpushId = fsUser.getJpushId();
                if (StringUtils.isNotBlank(jpushId) && !"0".equals(jpushId) && !"string".equals(jpushId)){
                    HashMap<String, Object> map = new HashMap<>();
                    HashMap<String, Object> map2 = new HashMap<>();
                    if (StringUtils.isNotBlank(purl)){
                        map.put("url",purl);
                    }
                    if (content.length()>50 || title.length()>20){
                        return null;//通知栏标题，长度小于20;通知栏内容，长度小于50
                    }
                    Map<String, Object> xmConfig = new HashMap<>();

                    if (type!=null){
                        String channel = "";
                        if (type.toString().contains("0")){
                            channel = "113892"; //订单
                        } else if (type.toString().contains("1")){
                            channel = "113891";
                        } else if (type.toString().contains("2")){
                            channel = "113791"; //系统类
                        }
                        if (StringUtils.isNotBlank(channel)){
                            xmConfig.put("/extra.channel_id", channel);
                            map2.put("XM", xmConfig);
                        }

                    }
                    return new PushReqBean(
                            jpushId,
                            title,
                            content,
                            map,
                            map2
                    );
                }
            }
        }
        return null;
    }

//    @Override
//    public void pushSopAppLinkMsg(Long fsUserId, String linkTile, String linkDescribe, String link) {
//        if (fsUserId ==null) {
//            log.error("推送失败：小程序id为空："+fsUserId+"|"+link);
//            return;
//        }
//        PushReqBean sopAppLinkParams = getSopAppLinkParams(fsUserId, linkTile, linkDescribe, link);
//        if (sopAppLinkParams ==null){
//            log.error("推送失败：参数有异常："+fsUserId+"|"+link);
//           return;
//        }
//        PushResult pushResult = pushMessage(sopAppLinkParams);
//        if (pushResult ==null){
//            return;
//        }
//        if (pushResult.getErrCode()!=null && (pushResult.getErrCode() == 0 || pushResult.getErrCode() == 200) ){
//            log.info("推送成功：{}",pushResult.getErrMsg()+"|"+fsUserId);
//        }else {
//            log.error("推送失败:{}",pushResult.getErrMsg()+"|"+fsUserId);
//        }
//
//    }
//
//    @Override
//    public PushReqBean getSopAppLinkParams(Long fsUserId, String linkTile, String linkDescribe, String link) {
//
//        FsUser fsUser = userService.selectFsUserByUserId(fsUserId);
//        if (fsUser ==null){
//            return  null;
//        }
//
//        String jpushId = fsUser.getJpushId();
//
//        if (StringUtils.isNotBlank(jpushId) && !"0".equals(jpushId) && !"string".equals(jpushId)){
//
//            HashMap<String, Object> map = new HashMap<>();
//            map.put("url",link);
//
//            HashMap<String, Object> map2 = new HashMap<>();
//
//            Map<String, Object> xmConfig = new HashMap<>();
//            xmConfig.put("/extra.channel_id", "133891");
//            map2.put("XM", xmConfig);
//
//            PushReqBean pushReqBean = new PushReqBean(
//                    jpushId,
//                    linkTile,
//                    linkDescribe,
//                    map,
//                    map2
//            );
//            return pushReqBean;
//        }
//
//        return null;
//    }

    @Override
    public void pushSopAppLinkMsgByExternal(Long externalId, String linkTile, String linkDescribe, String link) {
        if (externalId ==null) {
            log.error("推送失败：客户id为空："+externalId+"|"+link);
            return;
        }
        PushReqBean sopAppLinkParams = getSopAppLinkParamsByExternal(externalId, linkTile, linkDescribe, link);

        if (sopAppLinkParams ==null){
            log.error("推送失败：参数有异常："+externalId+"|"+link);
            return;
        }
        PushResult pushResult = pushMessage(sopAppLinkParams);
        if (pushResult ==null){
            return;
        }
        if (pushResult.getErrCode()!=null && (pushResult.getErrCode() == 0 || pushResult.getErrCode() == 200) ){
            log.info("推送成功：{}",pushResult.getErrMsg()+"|"+externalId);
        }else {
            log.error("推送失败:{}",pushResult.getErrMsg()+"|"+externalId);
        }

    }

    @Override
    public PushReqBean getSopAppLinkParamsByExternal(Long externalId,String linkTile,String linkDescribe,String link) {

        QwExternalContactFsUserVO contactFsUserVO = qwExternalContactMapper.selectQwExternalContactByIdForFsUser(externalId);

        if (contactFsUserVO != null && (!StringUtil.strIsNullOrEmpty(contactFsUserVO.getJpushId())
                && !"0".equals(contactFsUserVO.getJpushId())
                && !"string".equals(contactFsUserVO.getJpushId()))  ) {

                HashMap<String, Object> map = new HashMap<>();
                map.put("url",link);

                HashMap<String, Object> map2 = new HashMap<>();

                Map<String, Object> xmConfig = new HashMap<>();
                xmConfig.put("/extra.channel_id", "133891");
                map2.put("XM", xmConfig);

                PushReqBean pushReqBean = new PushReqBean(
                        contactFsUserVO.getJpushId(),
                        linkTile,
                        linkDescribe,
                        map,
                        map2
                );
                return pushReqBean;

        }else {
            log.error("客户信息异常："+contactFsUserVO+"|"+externalId);
        }
        return null;
    }
}
