package com.imdroid.beidou.controller;

import com.imdroid.beidou.auth.SessionUtils;
import com.imdroid.beidou.common.HttpResult;
import com.imdroid.beidou.config.WxMiniProperties;
import com.imdroid.beidou.data.dto.MiniSnTicketBodyDTO;
import com.imdroid.beidou.data.vo.mini.DeviceSnTicketVO;
import com.imdroid.beidou.utils.WXUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 微信小程序相关API调用控制器
 *
 * @author LiGang
 * @date 2023/11/12 10:38
 */
@RestController
@RequestMapping("/mini")
@RequiredArgsConstructor
public class MiniProgramController {

    private final WxMiniProperties wxMiniProperties;
    private final WXUtils wxUtils;

    /**
     * 获取设备snTicket
     *
     * @param request the http servlet request
     */
    @GetMapping(value = "/getsnticket")
    public HttpResult getSnTicket(HttpServletRequest request) {
        Long userId = SessionUtils.getUserId(request);
        if (userId == null) {
            return HttpResult.fail("用户id为空");
        }
        MiniSnTicketBodyDTO snTicketBodyDTO = new MiniSnTicketBodyDTO(String.valueOf(userId), wxMiniProperties.getModelId());
        String snTicket = wxUtils.getSnTicket(snTicketBodyDTO);
        if (snTicket == null) {
            return HttpResult.fail("获取snTicket失败");
        }
        return HttpResult.success(new DeviceSnTicketVO(String.valueOf(userId), snTicket, wxMiniProperties.getModelId()));
    }
}
