package cn.qg.qaplatform.controller.common;

import cn.qg.qaplatform.config.SwitchDataSource;
import cn.qg.qaplatform.entity.vo.MsgSendVo;
import cn.qg.qaplatform.entity.msg.MsgTemplate;
import cn.qg.qaplatform.entity.vo.XjfqGenProcessVo;
import cn.qg.qaplatform.entity.xyqbuser.User;
import cn.qg.qaplatform.service.msg.MsgTemplateService;
import cn.qg.qaplatform.service.msg.PhoneNoWhiteListService;
import cn.qg.qaplatform.service.xyqbUser.UserService;
import cn.qg.qaplatform.utils.HttpClientUtils;
import cn.qg.qaplatform.utils.Result;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jayway.jsonpath.JsonPath;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * 消息中心相关接口
 * @author libo
 * 2021-08-13
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/msg")
public class MsgController {

    @Autowired
    UserService userService;

    @Autowired
    PhoneNoWhiteListService phoneNoWhiteListService;

    @Autowired
    MsgTemplateService msgTemplateService;

    /**
     * 发送push
     * @param msgSendVo
     * @return
     */
    @PostMapping("/send/push")
    public Result sendPush(@RequestBody MsgSendVo msgSendVo) {
        String namespace = msgSendVo.getNamespace();
        String phoneNo = msgSendVo.getPhoneNo();
        String contentId = msgSendVo.getContentId();
        List<String> contentArgs = msgSendVo.getContentArgs();
        User user = userService.getUserInfoByPhoneNo(namespace, phoneNo);
        String userId;
        if (user == null) {
            log.info("用户中心查不到手机号{}，因此本次不发送push.", phoneNo);
            return Result.buildErrorStateResult("用户中心无此手机号，无法发送push", false);
        } else {
            userId = String.valueOf(user.getId());
        }
        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);
        try {
            JSONObject response = HttpClientUtils.doPostJson(url, JSON.toJSONString(paramList), headers);
            log.info("发送收到响应：{}", response);
            if (!JsonPath.read(response, "$.code").equals("0")) {
                return Result.buildErrorStateResult("发送失败，请检查msg服务！", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.buildErrorStateResult("发送异常，请检查msg服务是否正常！", false);
        }
        return Result.buildSuccessResult("发送成功！", true);
    }

    /**
     * 发送站内信
     * @param msgSendVo
     * @return
     */
    @PostMapping("/send/stationLetter")
    public Result sendStationLetter(@RequestBody MsgSendVo msgSendVo) {
        String namespace = msgSendVo.getNamespace();
        String phoneNo = msgSendVo.getPhoneNo();
        String contentId = msgSendVo.getContentId();
        List<String> contentArgs = msgSendVo.getContentArgs();
        User user = userService.getUserInfoByPhoneNo(namespace, phoneNo);
        String userId;
        if (user == null) {
            log.info("用户中心查不到手机号{}，因此本次不发送站内信.", phoneNo);
            return Result.buildErrorStateResult("用户中心无此手机号，无法发送站内信", false);
        } else {
            userId = String.valueOf(user.getId());
        }
        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);
        try {
            JSONObject response = HttpClientUtils.doPostJson(url, JSON.toJSONString(paramList), headers);
            log.info("收到响应：{}", response);
            if (!JsonPath.read(response, "$.code").equals("0")) {
                return Result.buildErrorStateResult("发送失败，请检查msg服务！", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.buildErrorStateResult("发送异常，请检查msg服务是否正常！", false);
        }
        return Result.buildSuccessResult("发送成功", true);
    }

    /**
     * 发送行业短信
     * @param msgSendVo
     * @return
     */
    @PostMapping("/send/quick")
    public Result sendMsgQuick(@RequestBody MsgSendVo msgSendVo) {
        String namespace = msgSendVo.getNamespace();
        String phoneNo = msgSendVo.getPhoneNo();
        String contentId = msgSendVo.getContentId();
        List<String> contentArgs = msgSendVo.getContentArgs();
        phoneNoWhiteListService.handlePhoneNoWhiteList(namespace, phoneNo);
        User user = userService.getUserInfoByPhoneNo(namespace, phoneNo);
        String userId;
        if (user == null) {
            log.info("用户中心查不到手机号{}，因此本次不发送短信.", phoneNo);
            return Result.buildErrorStateResult("用户中心未找到该手机号，短信不进行发送！", false);
        } else {
            userId = String.valueOf(user.getId());
        }
        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<>();
        headers.put("Content-Type", "application/json");
        log.info("开始发送行业短信，url:{}, 参数：{}", url, paramsMap);
        try {
            JSONObject response = HttpClientUtils.doPostJson(url, JSON.toJSONString(paramsMap), headers);
            log.info("收到响应：{}", response);
            if (!JsonPath.read(response, "$.code").equals("0")) {
                return Result.buildErrorStateResult("发送失败，请检查msg服务!", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.buildErrorStateResult("发送异常，请检查msg服务!", false);
        }
        return Result.buildSuccessResult("发送成功！", true);
    }

    /**
     * 发送营销短信
     * @param msgSendVo
     * @return
     */
    @PostMapping("/send/market")
    public Result sendMsgMarket(@RequestBody MsgSendVo msgSendVo) {
        String namespace = msgSendVo.getNamespace();
        String phoneNo = msgSendVo.getPhoneNo();
        String contentId = msgSendVo.getContentId();
        List<String> contentArgs = msgSendVo.getContentArgs();
        phoneNoWhiteListService.handlePhoneNoWhiteList(namespace, 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", "6");
        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);
        try {
            JSONObject response = HttpClientUtils.doPostJson(url, JSON.toJSONString(paramList), headers);
            log.info("收到响应：{}", response);
            if (!JsonPath.read(response, "$.code").equals("0")) {
                return Result.buildErrorStateResult("发送失败，请检查msg服务!", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.buildErrorStateResult("发送异常，请检查msg服务！", false);
        }
        return Result.buildSuccessResult("发送成功！", true);
    }

    /**
     * 获取短信模板列表
     * @param namespace 环境
     * @param templateType 模板类型
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/template/list")
    public Result getMsgTemplateList(String namespace, Integer templateType, Integer pageNum, Integer pageSize) {
        SwitchDataSource.dataSourceSwitch(namespace, "msg");
        Page<MsgTemplate> page = new Page<>(pageNum, pageSize);
        QueryWrapper<MsgTemplate> msgTemplateQueryWrapper = new QueryWrapper<>();
        msgTemplateQueryWrapper.eq("template_type", templateType);
        msgTemplateQueryWrapper.orderByDesc("id");
        IPage<MsgTemplate> msgTemplateIPage = msgTemplateService.page(page, msgTemplateQueryWrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("total", msgTemplateIPage.getTotal());
        map.put("list", msgTemplateIPage.getRecords());
        return Result.buildSuccessResult(map);
    }
}
