package cn.iocoder.yudao.module.system.api.subscribe;

import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.system.api.subscribe.dto.MsgData;
import cn.iocoder.yudao.module.system.api.subscribe.dto.SubscribeMessageReqDTO;
import cn.iocoder.yudao.module.system.service.social.SocialClientService;
import lombok.SneakyThrows;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

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

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 功能描述 微信小程序发送订阅消息
 *
 * @author: yj
 * @date: 2024年02月25日 11:35
 */
@RestController // 提供 RESTful API 接口，给 Feign 调用
@Validated
public class SubscribeMessageSendApiImpl implements SubscribeMessageSendApi {

    @Resource
    private SocialClientService socialClientService;

    @SneakyThrows
    @Override
    public CommonResult<Long> sendApprovalResultNotification(SubscribeMessageReqDTO reqDTO) {
        socialClientService.getWxMaService().getMsgService().sendSubscribeMsg(initWxMaSubscribeMessage(reqDTO));
        return success(1L);
    }

    @SneakyThrows
    @Override
    public CommonResult<Long> sendProcessToDoReminder(SubscribeMessageReqDTO reqDTO) {
        socialClientService.getWxMaService().getMsgService().sendSubscribeMsg(initWxMaSubscribeMessage(reqDTO));
        return success(1L);
    }

    @SneakyThrows
    @Override
    public CommonResult<Long> sendCompanyNotice(SubscribeMessageReqDTO reqDTO) {
        socialClientService.getWxMaService().getMsgService().sendSubscribeMsg(initWxMaSubscribeMessage(reqDTO));
        return success(1L);
    }

    @SneakyThrows
    @Override
    public CommonResult<Long> sendWorkLogComment(SubscribeMessageReqDTO reqDTO) {
        socialClientService.getWxMaService().getMsgService().sendSubscribeMsg(initWxMaSubscribeMessage(reqDTO));
        return success(1L);
    }

    private WxMaSubscribeMessage initWxMaSubscribeMessage(SubscribeMessageReqDTO reqDTO) {
        WxMaSubscribeMessage message = WxMaSubscribeMessage.builder()
                .toUser(reqDTO.getToUser())
                .templateId(reqDTO.getTemplateId())
                .build();
        message.setMiniprogramState(reqDTO.getMiniprogramState());
        List<MsgData> dataList = reqDTO.getData();
        for (MsgData msgData : dataList) {
            WxMaSubscribeMessage.MsgData wxMsgData = new WxMaSubscribeMessage.MsgData();
            wxMsgData.setName(msgData.getName());
            wxMsgData.setValue(msgData.getValue());
            message.addData(wxMsgData);
        }
        message.setPage(reqDTO.getPage());
        return message;
    }

}
