package com.cool.store.controller;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.context.CurrentUserHolder;
import com.cool.store.dto.login.FeiShuLoginDTO;
import com.cool.store.dto.login.UserIdInfoDTO;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.http.ISVHttpRequest;
import com.cool.store.response.ResponseResult;
import com.cool.store.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @author zhangchenbiao
 * @FileName: LoginController
 * @Description:登录
 * @date 2023-05-19 17:22
 */
@RestController
@Slf4j
public class LoginController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private ISVHttpRequest isvHttpRequest;


    @PostMapping(value = "/feiShuLogin")
    public ResponseResult feiShuLogin(@RequestBody FeiShuLoginDTO param) {
        log.info("feiShuLogin data={}", JSONObject.toJSONString(param));
        String code = param.getCode();
        try {
            String value = "code=" + code;
            UserIdInfoDTO userInfo = isvHttpRequest.getUserIdByCode(value);
            if(Objects.isNull(userInfo)){
                throw new ServiceException(ErrorCodeEnum.LOGIN_ERROR);
            }
            log.info("userInfo:{}", JSONObject.toJSONString(userInfo));
            String userId = userInfo.getOpenId();
            return ResponseResult.success(loginService.feiShuLogin(userId, Boolean.TRUE, StringUtils.EMPTY));
        } catch (ServiceException e) {
            log.error(e.getMessage(), e);
            throw new ServiceException(ErrorCodeEnum.LOGIN_ERROR);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new ServiceException(ErrorCodeEnum.LOGIN_ERROR);
        }
    }

    @GetMapping("/getUserInfoByToken")
    public ResponseResult getUserInfoByToken(){
        return ResponseResult.success(CurrentUserHolder.getUser());
    }

}
