package com.willalp.wx.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.willalp.common.utils.DateUtils;
import com.willalp.common.utils.StringUtils;
import com.willalp.push.service.IHsAppPushService;
import com.willalp.wx.domain.WxMsgConfig;
import com.willalp.wx.domain.WxMsgTemplateApproval;
import com.willalp.wx.domain.WxMsgTemplateApprovalResult;
import com.willalp.wx.enums.WxTemplateKeyEnum;
import com.willalp.wx.service.WxMsgService;
import com.willalp.wx.utils.WxUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class WxMsgServiceImpl implements WxMsgService {

    protected static final Logger log = LoggerFactory.getLogger(WxMsgServiceImpl.class);

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private WxUtils wxUtils;

    @Resource
    private IHsAppPushService pushService;

    /*发送请求*/
    public JSONObject postData(String url, WxMsgConfig param) {
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(type);
        HttpEntity<WxMsgConfig> httpEntity = new HttpEntity<>(param, headers);
        JSONObject jsonResult = restTemplate.postForObject(url, httpEntity, JSONObject.class);
        return jsonResult;
    }

    @Override
    public boolean sendQRCodeMsg(String openId, Object obj, WxTemplateKeyEnum wxTemplateKeyEnum, boolean isQuery) {
        boolean sendSuccess = false;
        if (StringUtils.isBlank(openId)) {
            log.error("OPEN_ID - 为空，推送失败");
            return false;
        }
        openId = isQuery ? pushService.getOpenIdByUserNo(openId) : openId;
        WxMsgConfig requesData = new WxMsgConfig();
        requesData.setTouser(openId);
        requesData.setTemplate_id(wxTemplateKeyEnum.getValue());
        requesData.setData(obj);
        //小程序默认统一页面
        requesData.setPage("/pages/tabbar/wpTabbar");
        log.info("推送消息请求参数：{}", JSON.toJSONString(requesData));
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + wxUtils.getAccessToken();
        log.info("推送消息请求地址：{}", url);
        JSONObject responseData = postData(url, requesData);
        log.info("推送消息返回参数：{}", JSON.toJSONString(responseData));
        Integer errorCode = responseData.getInteger("errcode");
        String errorMessage = responseData.getString("errmsg");
        if (errorCode == 0) {
            sendSuccess = true;
            log.info("推送消息发送成功");
        } else {
            log.info("推送消息发送失败,errcode：{},errorMessage：{}", errorCode, errorMessage);
            sendSuccess = false;
        }
        return sendSuccess;
    }

    @Override
    public void sendApprovalMsg(String title, String sendUser, String applyUn, Date createTime) {
        //生成审批结果消息列表
        WxMsgTemplateApproval wxMsgTemplateApproval = new WxMsgTemplateApproval();
        wxMsgTemplateApproval.setThing5(wxUtils.getFormat(title));
        wxMsgTemplateApproval.setThing11(wxUtils.getFormat(applyUn));
        wxMsgTemplateApproval.setTime12(wxUtils.getFormat(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", createTime)));
        sendQRCodeMsg(sendUser, wxMsgTemplateApproval, WxTemplateKeyEnum.APPROVAL_WAIT, true);

    }

    @Override
    public void sendResultMsg(String title, String result, String sendUser) {
        //推送微信审批结果通知
        WxMsgTemplateApprovalResult wxMsgTemplateApproval = new WxMsgTemplateApprovalResult();
        wxMsgTemplateApproval.setPhrase4(wxUtils.getFormat(result));
        wxMsgTemplateApproval.setDate3(wxUtils.getFormat(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", new Date())));
        wxMsgTemplateApproval.setThing6(wxUtils.getFormat(title));
        sendQRCodeMsg(sendUser, wxMsgTemplateApproval, WxTemplateKeyEnum.APPROVAL_RESULT, true);
    }
}