package cn.qg.qaplatform.service.stools.impl;

import cn.qg.qaplatform.config.SwitchDataSource;
import cn.qg.qaplatform.entity.stools.MsgTemplate;
import cn.qg.qaplatform.entity.stools.PhoneNoWhiteList;
import cn.qg.qaplatform.entity.zdata.XjfqGenProcessVo;
import cn.qg.qaplatform.mapper.stools.MsgMapper;
import cn.qg.qaplatform.mapper.stools.PhoneNoWhiteListMapper;
import cn.qg.qaplatform.service.stools.MsgService;
import cn.qg.qaplatform.service.zdata.xyqb.XyqbBasicQueryService;
import cn.qg.qaplatform.utils.HttpClientUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jayway.jsonpath.JsonPath;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class MsgServiceImpl extends ServiceImpl<MsgMapper, MsgTemplate> implements MsgService {

    @Autowired
    XyqbBasicQueryService xyqbBasicQueryService;

    @Autowired
    PhoneNoWhiteListMapper phoneNoWhiteListMapper;

    /**
     * 发送push
     */
    @Override
    public boolean sendPush(String namespace, String phoneNo, String contentId, List<String> contentArgs) {
        String userId = xyqbBasicQueryService.getUserInfoByPhoneNo(namespace, phoneNo).getUserId();
        String url = "https://msgapi-" + namespace + ".liangkebang.net/middle_office/send/message/appPush";
        List<Map<String, Object>> paramList = new ArrayList<>();
        Map<String, Object> sendMap = new HashMap<>();
        sendMap.put("merchantId", "3");
        sendMap.put("phoneNo", phoneNo);
        sendMap.put("userIds", userId);
        sendMap.put("contentId", contentId);
        if (contentArgs != null && contentArgs.size() > 0) {
            sendMap.put("contentArgs", contentArgs);
        }
        paramList.add(sendMap);
        Map<String, Object> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        log.info("开始发送push，url：{}, 参数：{}", url, paramList);
        JSONObject response = HttpClientUtils.doPostJson(url, JSON.toJSONString(paramList), headers);
        log.info("收到响应：{}", response);
        return JsonPath.read(response, "$.code").equals("0");
    }

    /**
     * 发送站内信
     */
    @Override
    public boolean sendStationLetter(String namespace, String phoneNo, String contentId, List<String> contentArgs) {
        String userId = xyqbBasicQueryService.getUserInfoByPhoneNo(namespace, phoneNo).getUserId();
        String url = "https://msgapi-" + namespace + ".liangkebang.net/middle_office/send/message/stationLetter";
        List<Map<String, Object>> paramList = new ArrayList<>();
        Map<String, Object> sendMap = new HashMap<>();
        sendMap.put("merchantId", "3");
        sendMap.put("phoneNo", phoneNo);
        sendMap.put("userIds", userId);
        sendMap.put("contentId", contentId);
        if (contentArgs != null && contentArgs.size() > 0) {
            sendMap.put("contentArgs", contentArgs);
        }
        paramList.add(sendMap);
        Map<String, Object> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        log.info("开始发送站内信，url：{}, 参数：{}", url, paramList);
        JSONObject response = HttpClientUtils.doPostJson(url, JSON.toJSONString(paramList), headers);
        log.info("收到响应：{}", response);
        return JsonPath.read(response, "$.code").equals("0");
    }

    /**
     * 发送行业短信
     */
    @Override
    public boolean sendMsgQuick(String namespace, String phoneNo, String contentId, List<String> contentArgs) {
        handlePhoneNoWhiteList(namespace, phoneNo);
        XjfqGenProcessVo xjfqGenProcessVo = xyqbBasicQueryService.getUserInfoByPhoneNo(namespace, phoneNo);
        String userId;
        if (xjfqGenProcessVo == null) {
            log.info("用户中心查不到手机号{}，因此本次不发送短信.", phoneNo);
            return false;
        } else {
            userId = xjfqGenProcessVo.getUserId();
        }
        String url = "https://msgapi-" + namespace + ".liangkebang.net/middle_office/send/message/quick";
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("merchantId", "3");
        paramsMap.put("phoneNo", phoneNo);
        paramsMap.put("userIds", userId);
        paramsMap.put("contentId", contentId);
        if (contentArgs != null && contentArgs.size() > 0) {
            paramsMap.put("contentArgs", contentArgs);
        }
        Map<String, Object> headers = new HashMap<>();
        log.info("开始发送营销短信，url:{}, 参数：{}", url, paramsMap);
        JSONObject response = HttpClientUtils.doPostJson(url, JSON.toJSONString(paramsMap), headers);
        log.info("收到响应：{}", response);
        return JsonPath.read(response, "$.code").equals("0");
    }

    /**
     * 发送营销短信
     */
    @Override
    public boolean sendMsgMarket(String namespace, String phoneNo, String contentId, List<String> contentArgs) {
        handlePhoneNoWhiteList(namespace, phoneNo);
        SwitchDataSource.dataSourceSwitch(namespace, "msg");
        QueryWrapper<PhoneNoWhiteList> whiteListQueryWrapper = new QueryWrapper<>();
        whiteListQueryWrapper.eq("phone_no", phoneNo);
        PhoneNoWhiteList phoneNoWhite = phoneNoWhiteListMapper.selectOne(whiteListQueryWrapper);
        if (phoneNoWhite == null) {
            log.info("该手机号不在白名单：{}，先将其添加到手机号白名单.", phoneNo);
            PhoneNoWhiteList phoneNoWhiteListEntity = new PhoneNoWhiteList();
            phoneNoWhiteListEntity.setPhoneNo(phoneNo);
            phoneNoWhiteListEntity.setUserName(phoneNo);
            phoneNoWhiteListEntity.setListType("1");
            phoneNoWhiteListEntity.setDeleted(0);
            phoneNoWhiteListMapper.insert(phoneNoWhiteListEntity);
        } else {
            log.info("{}该手机号已在手机号白名单.", phoneNo);
        }
        String url = "https://msgapi-" + namespace + ".liangkebang.net/middle_office/send/message/market";
        Map<String, Object> paramsMap = new HashMap<>();
        Map<String, Object> headers = new HashMap<>();
        paramsMap.put("merchantId", "3");
        paramsMap.put("phoneNo", phoneNo);
        paramsMap.put("contentId", contentId);
        paramsMap.put("platformId", "8");
        if (contentArgs != null && contentArgs.size() > 0) {
            paramsMap.put("contentArgs", contentArgs);
        }
        List<Map<String, Object>> paramList = new ArrayList<>();
        paramList.add(paramsMap);
        headers.put("Content-Type", "application/json");
        log.info("开始发送营销短信，url:{}, 参数：{}", url, paramList);
        JSONObject response = HttpClientUtils.doPostJson(url, JSON.toJSONString(paramList), headers);
        log.info("收到响应：{}", response);
        return JsonPath.read(response, "$.code").equals("0");
    }

    /**
     * 判断是否在白名单，如果不在，则添加到短信白名单
     * @param namespace 环境
     * @param phoneNo 手机号
     */
    public void handlePhoneNoWhiteList(String namespace, String phoneNo) {
        SwitchDataSource.dataSourceSwitch(namespace, "msg");
        QueryWrapper<PhoneNoWhiteList> whiteListQueryWrapper = new QueryWrapper<>();
        whiteListQueryWrapper.eq("phone_no", phoneNo);
        PhoneNoWhiteList phoneNoWhite = phoneNoWhiteListMapper.selectOne(whiteListQueryWrapper);
        if (phoneNoWhite == null) {
            log.info("该手机号不在白名单：{}，先将其添加到手机号白名单.", phoneNo);
            PhoneNoWhiteList phoneNoWhiteListEntity = new PhoneNoWhiteList();
            phoneNoWhiteListEntity.setPhoneNo(phoneNo);
            phoneNoWhiteListEntity.setUserName("测试");
            phoneNoWhiteListEntity.setListType("1");
            phoneNoWhiteListEntity.setDeleted(0);
            phoneNoWhiteListMapper.insert(phoneNoWhiteListEntity);
        } else {
            log.info("{}该手机号已在手机号白名单.", phoneNo);
        }
    }
}
