package com.starry.admin.modules.weichat.service;

import com.starry.admin.modules.custom.module.entity.PlayCustomUserInfoEntity;
import com.starry.admin.modules.custom.service.IPlayCustomUserInfoService;
import com.starry.common.constant.Constants;
import com.starry.common.utils.StringUtils;
import java.util.Objects;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class WxCustomUserService {

    @Resource
    private IPlayCustomUserInfoService customUserInfoService;

    @Resource
    private HttpServletRequest request;

    @Resource
    private WxTokenService tokenService;

    /**
     * 获取当前登录顾客ID
     *
     * @return 当前登录顾客ID
     */
    public String getLoginUserId() {
        String userToken = request.getHeader(com.starry.common.constant.Constants.CUSTOM_USER_LOGIN_TOKEN);
        if (StringUtils.isEmpty(userToken)) {
            return "";
        }
        if (userToken.startsWith(com.starry.common.constant.Constants.TOKEN_PREFIX)) {
            userToken = userToken.replace(Constants.TOKEN_PREFIX, "");
        }
        // 解析token
        String userId;
        try {
            userId = tokenService.getWxUserIdByToken(userToken);
        } catch (Exception e) {
            return "";
        }
        PlayCustomUserInfoEntity entity = customUserInfoService.selectById(userId);
        if (Objects.isNull(entity)) {
            return "";
        }
        return userToken.equals(entity.getToken()) ? userId : "";
    }

}
