package com.app.service.wx;

import com.alibaba.fastjson.JSONObject;
import com.app.dto.wx.WxSendMsgDto;
import com.app.util.DateUtil;
import com.app.util.HttpUtil;
import com.app.util.JacksonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.NumberFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 订阅消息（微信已经废弃模版消息功能）
 */
@Slf4j
@Service
public class WXTemplateService {

    @Autowired
    private HttpUtil httpUtil;

    @Autowired
    private WXService wxService;

    public void sendTemplate(JSONObject jsonObject) {
        String responseBody = httpUtil.post(String.format("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s", wxService.getAccessToken()), jsonObject);
        WxSendMsgDto dto = JacksonUtil.fromJSON(responseBody, WxSendMsgDto.class);

        if (!"ok".equals(dto.getErrmsg())) {
            log.error("模版消息发送失败。errcode: [{}], errmsg: [{}], data: [{}]", dto.getErrcode(), dto.getErrmsg(), jsonObject);
            throw new RuntimeException("模版消息发送失败");
        }

        log.info("模版消息发送成功。errcode: [{}], errmsg: [{}], data: [{}]", dto.getErrcode(), dto.getErrmsg(), jsonObject);
    }

    public void sendPaySuccessTemplate(String openid, String openCourseOrderId, String openCourseName, Double openCoursePrice, Date payEndTime) {
        if (StringUtils.isEmpty(openid)) {
            return;
        }

        NumberFormat curFormat = NumberFormat.getCurrencyInstance(Locale.CHINA);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser", openid);
        jsonObject.put("template_id", "du-UXaZb4ay1EnVtwMa9Xz0zt4Hi36hTeIi8asWVxvE");
        jsonObject.put("page", "pages/home/main/main");
        jsonObject.put("data", new JSONObject() {{
            put("character_string1", new JSONObject() {{
                put("value", openCourseOrderId);
            }}); // 订单编号
            put("thing2", new JSONObject() {{
                put("value", openCourseName);
            }}); // 课程名称
            put("amount3", new JSONObject() {{
                put("value", String.format("%s元", curFormat.format(openCoursePrice)));
            }}); // 订单金额
            put("date4", new JSONObject() {{
                put("value", DateUtil.format(payEndTime, "yyyy-MM-dd HH:mm:ss"));
            }}); // 购买时间
            put("thing5", new JSONObject() {{
                put("value", "您已购买成功，请关注上课时间。");
            }}); // 温馨提示
        }});

        sendTemplate(jsonObject);
    }

    public void sendRefundTemplate(String openid, String openCourseOrderId, String openCourseName, Integer state, Double openCoursePrice) {
        if (StringUtils.isEmpty(openid)) {
            return;
        }

        NumberFormat curFormat = NumberFormat.getCurrencyInstance(Locale.CHINA);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser", openid);
        jsonObject.put("template_id", "H24RMz_UuzbAt4Wsw4S_f1MR2rz0-DCnhTzuhpgXS0Y");
        jsonObject.put("page", "pages/home/main/main");
        jsonObject.put("data", new JSONObject() {{
            put("character_string1", new JSONObject() {{
                put("value", openCourseOrderId);
            }}); // 订单号
            put("name2", new JSONObject() {{
                put("value", openCourseName);
            }}); // 课程名称
            put("name3", new JSONObject() {{
                put("value", state == -1 ? "未通过" : "已通过");
            }}); // 退款状态
            put("amount4", new JSONObject() {{
                put("value", String.format("%s元", curFormat.format(openCoursePrice)));
            }}); // 退款金额
        }});

        sendTemplate(jsonObject);
    }

}
