package cn.iocoder.yudao.module.base.controller.app;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.jx.domain.DriveSchoolGuide;
import cn.iocoder.yudao.module.jx.service.DriveSchoolGuideService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.util.SendSmsUtil;
import lombok.Data;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import cn.iocoder.yudao.module.base.vo.SubscriptionMessageDTO;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/wxPush/message")
public class MessageController {

    @Autowired
    @Qualifier("jxWxMaService")
    private WxMaService jxWxMaService;

    @Autowired
    private DriveSchoolGuideService driveSchoolGuideService;

    @Resource
    private AdminUserApi userApi;


    /**
     * 发送一次性订阅消息
     */
    @PostMapping("/sendOnce")
    public ResponseEntity<Map<String, Object>> sendOnce(
            @RequestBody SubscriptionMessageDTO messageDTO) {

        Map<String, Object> response = new HashMap<>();

        try {

            // 构建消息
            WxMaSubscribeMessage message = new WxMaSubscribeMessage();
            message.setToUser(messageDTO.getOpenid());
            message.setTemplateId(messageDTO.getTemplateId());
            // 设置跳转页面
            message.setPage(messageDTO.getPage());

            // 添加模板内容
            messageDTO.getData().forEach((key, value) -> {
                message.addData(new WxMaSubscribeMessage.MsgData(key, value.getValue()));
            });

            // 发送订阅消息
            jxWxMaService.getMsgService().sendSubscribeMsg(message);

            // 发送短信
            /*if(messageDTO.getPage() != null){
                String page = messageDTO.getPage();
                if (page.contains("tenantId=")) {
                    String tenantId = page.substring(page.indexOf("tenantId=") + 9);
                    this.sendSms(tenantId);
                }
            }*/

            response.put("success", true);
            response.put("message", "发送成功");
            return ResponseEntity.ok(response);

        } catch (WxErrorException e) {
            // 微信接口错误处理
            response.put("success", false);
            response.put("errorCode", e.getError().getErrorCode());
            response.put("message", "微信接口错误: " + e.getError().getErrorMsg());
            return ResponseEntity.status(500).body(response);

        } catch (Exception e) {
            // 其他错误处理
            response.put("success", false);
            response.put("message", "系统错误: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 向用户发送短信
     * @return
     */
    @GetMapping("/sendSms")
    public void sendSms(String tenantId) {
        // 通过tenantId获取需要发送的短信内容
        List<DriveSchoolGuide> driveSchoolGuides = driveSchoolGuideService.listByTenantId(tenantId);
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserRespDTO user = userApi.getUser(userId);
        String mobile = user.getUsername();
        if(!driveSchoolGuides.isEmpty()){
            String msgText = driveSchoolGuides.get(0).getMsgText();
            // 发送短信
            if(!msgText.isEmpty() && !mobile.isEmpty()){
                SendSmsUtil.sendMsgCommon(new String[]{msgText}, mobile, "1400852709", "驾悦同行小程序", "2143603");
            }
        }
    }


    @GetMapping("/checkConfig")
    @PermitAll
    public String checkConfig() {
        // 获取当前 WxMaService 的配置
        WxMaConfig config = jxWxMaService.getWxMaConfig();

        return String.format(
                "当前使用的配置：\nAppID: %s\nSecret: %s\nToken: %s\nAESKey: %s",
                config.getAppid(),
                config.getSecret(),
                config.getToken(),
                config.getAesKey()
        );
    }
}
