package com.kym.miniapp.controller;

import com.kym.common.R;
import com.kym.common.utils.wx.WxPbUtil;
import com.kym.entity.miniapp.UserCoupon;
import com.kym.service.mq.producer.UserCouponSender;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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


@RestController
@RequestMapping("/test")
public class TestController {


    private final UserCouponSender userCouponSender;

    private final WxMpService wxMpService;

    public TestController(UserCouponSender userCouponSender, WxMpService wxMpService) {

        this.userCouponSender = userCouponSender;
        this.wxMpService = wxMpService;
    }

    /**
     * 测试rabbitmq
     *
     * @return
     */
    @GetMapping(value = "/test")
    R<?> test() {
        for (int i = 0; i < 10; i++) {
            var userCoupon = new UserCoupon().setUserId(i + 1L);
            userCouponSender.sendMessage(userCoupon);
        }
        return R.success();
    }

    /**
     * 测试公众号消息
     *
     * @return
     */
    @GetMapping(value = "/test2")
    R<?> test2() {
        // 通过unionid获取公众号openid

        var params = Map.of(
                "character_string2.DATA", "order111222333",
                "thing9.DATA", "测试站点",
                "character_string3.DATA", "SN0001",
                "time4.DATA", "2024-07-29 12:00:00"
        );
        WxPbUtil.sendPublicTemplateMessage("", "SjszYYiHcN-GaEeZTKJsCcB6ACxYJWfTddkSywf1q1g", params, "", "");
        return R.success();
    }

    /**
     * 测试拉取公众号关注者列表
     * @return
     */
    @GetMapping(value = "/test3")
    R<?> test3() throws WxErrorException {
        // 获取公众号所有关注者列表
        WxMpUserList wxUserList = wxMpService.getUserService().userList();
        // 通过unionid获取公众号openid
        String lang = "zh_CN";
        var unionid2openid = new HashMap<>();
        wxUserList.getOpenids().forEach(openid -> {
            try {
                WxMpUser mpUser = wxMpService.getUserService().userInfo(openid,lang);
                unionid2openid.put(mpUser.getUnionId(),openid);
            } catch (WxErrorException e) {
                throw new RuntimeException(e);
            }
        });


        return R.success(wxUserList);
    }


}
