package com.hzs.retail.login.controller;

import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.security.auth.AuthMemberUtil;
import com.hzs.common.security.service.MemberTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.member.base.dto.LoginMember;
import com.hzs.retail.login.param.RetailAutoLoginParam;
import com.hzs.retail.login.param.RetailLoginParam;
import com.hzs.retail.login.service.IRetailMemberLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @Description:
 * @Author: jiang chao
 * @Time: 2024/12/11 14:03
 * @Classname: RetailMemberTokenController
 * @PackageName: com.hzs.retail.login.controller
 */
@RequestMapping("/api/retail-auth")
@RestController
public class RetailMemberTokenController {

    @Autowired
    private MemberTokenService memberTokenService;
    @Autowired
    private IRetailMemberLoginService iRetailMemberLoginService;

    @Autowired
    private RedisService redisService;

    /**
     * 新零售会员登录
     *
     * @param param 登录参数
     * @return
     */
    @PostMapping("/login")
    public AjaxResult login(@Valid @RequestBody RetailLoginParam param) {
        // 用户登录
        LoginMember loginMember = iRetailMemberLoginService.login(param.getUsername(), param.getPassword());
        // 获取登录token
        return AjaxResult.success(memberTokenService.createToken(loginMember));
    }

    /**
     * 新零售会员自动登录
     *
     * @param param 自助登录参数
     * @return
     */
    @PostMapping("/auto-login")
    public AjaxResult autoLogin(@Valid @RequestBody RetailAutoLoginParam param) {
        String tmpUuid = redisService.getCacheObject(CacheConstants.AUTO_LOGIN + param.getUsername());
        if (!param.getUuid().equals(tmpUuid)) {
            // 没有自动登录标记 或者 标记不对，则不能自动登录
            return AjaxResult.error("当前会员已不能快递登录");
        }

        // 用户登录
        LoginMember loginMember = iRetailMemberLoginService.login(param.getUsername(), param.getPassword());
        // 获取登录token
        return AjaxResult.success(memberTokenService.createToken(loginMember));
    }

    /**
     * 会员登出
     *
     * @param request
     * @return
     */
    @DeleteMapping("/logout")
    public AjaxResult logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            // 删除用户缓存记录
            AuthMemberUtil.logoutByToken(token);
        }
        return AjaxResult.success();
    }

}
