package com.czg.controller.user;

import com.czg.account.dto.auth.GetPhoneDTO;
import com.czg.account.dto.auth.LoginTokenDTO;
import com.czg.account.dto.auth.UserAuthorizationLoginDTO;
import com.czg.account.entity.ShopInfo;
import com.czg.account.service.ShopInfoService;
import com.czg.account.service.UserAuthorizationService;
import com.czg.resp.CzgResult;
import com.czg.sa.MyStpLogic;
import com.czg.sa.StpKit;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 用户登录相关
 * @author Administrator
 */
@RestController
@RequestMapping("/user")
public class UserAuthorizationController {
    @Resource
    private UserAuthorizationService userAuthorizationService;
    @Resource
    private ShopInfoService shopInfoService;

    /**
     * 小程序登录
     * @param userAuthorizationLoginDTO 登录信息
     * @return 登录信息
     */
    @PostMapping("/login")
    public CzgResult<LoginTokenDTO> login(@RequestBody @Validated UserAuthorizationLoginDTO userAuthorizationLoginDTO) {
        return CzgResult.success(userAuthorizationService.login(userAuthorizationLoginDTO));
    }

    /**
     * 获取手机号
     * @param getPhoneDTO 获取手机号信息
     * @return 手机号
     */
    @PostMapping("/phone")
    public CzgResult<String> getPhone(@RequestBody @Validated GetPhoneDTO getPhoneDTO) {
        return CzgResult.success(userAuthorizationService.getPhone(getPhoneDTO));
    }

    /**
     * 通过code获取openId
     * @param code code
     * @param source 平台 wechat微信 支付宝alipay
     * @return 返回openId
     */
    @GetMapping("/openId")
    public CzgResult<Map<String, String>> getOpenId(@RequestParam String code, @RequestParam String source, @RequestParam Long shopId) {
        String openId = userAuthorizationService.getOpenId(code, source);
        if (openId == null){
            return CzgResult.failure("获取openId失败");
        }
        ShopInfo shopInfo = shopInfoService.getById(shopId);
        if (shopInfo == null){
            return CzgResult.failure("店铺信息不存在");
        }
        return CzgResult.success(Map.of(
                "openId", openId,
                "shopImage", shopInfo.getLogo(),
                "shopName", shopInfo.getShopName()
        ));
    }
}
