package shop.alien.gateway.controller;

import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.vo.LifeUserVo;
import shop.alien.gateway.config.BaseRedisService;
import shop.alien.gateway.service.ActivityInviteConfigService;
import shop.alien.gateway.service.LifeUserService;

/**
 * 用户
 */
@Api(tags = {"一期-用户"})
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class LifeUserController {

    private final LifeUserService lifeUserService;

    private final BaseRedisService baseRedisService;

    private final ActivityInviteConfigService activityInviteConfigService;

    @ApiOperation("用户登录")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phoneNum", value = "手机号", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "code", value = "验证码", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "inviteCode", value = "邀请码", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "inviteCode", value = "邀请码", dataType = "String", paramType = "query", required = false)
    })
    @GetMapping("/userLogin")
    public R<LifeUserVo> userLogin(@RequestParam("phoneNum") String phoneNum,
                                   @RequestParam("code") String code,
                                   @RequestParam(value = "macIp", required = false) String macIp,
                                   @RequestParam(value = "inviteCode", required = false) String inviteCode) {
        log.info("LifeUserController.userLogin?phoneNum={}&code={}", phoneNum, code);
        LifeUserVo userVo = lifeUserService.userLogin(phoneNum, inviteCode, macIp);
        if (null == userVo) {
            return R.fail("登录失败");
        }

        if (1 == userVo.getIsBanned()) {
            return R.fail("账号已被封禁, 无法登录");
        }

        // 2025-11-04 验证码-用户端登录
        String cacheCode = baseRedisService.getString("verification_user_login_" + phoneNum);
        if (null == cacheCode) {
            return R.fail("当前验证码过期或未发送");
        }
        if (!cacheCode.trim().equals(code.trim())) {
            return R.fail("验证码错误");
        }

        if(StringUtils.isNotBlank(inviteCode)){
           String bindResult =  activityInviteConfigService.bindInviteCode(userVo.getId(), inviteCode);
           if(StringUtils.isNotBlank(bindResult) && !bindResult.equals("绑定成功")){
               return R.fail(bindResult);
           }
        }
        return R.data(userVo);
    }

}
