package com.greenorange.promotion.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.greenorange.promotion.annotation.RequiresPermission;
import com.greenorange.promotion.common.ErrorCode;
import com.greenorange.promotion.constant.CommonConstant;
import com.greenorange.promotion.exception.ThrowUtils;
import com.greenorange.promotion.mapper.UserInfoMapper;
import com.greenorange.promotion.model.dto.user.UserInfoQueryRequest;
import com.greenorange.promotion.model.entity.UserInfo;
import com.greenorange.promotion.service.user.UserInfoService;
import com.greenorange.promotion.utils.JWTUtils;
import com.greenorange.promotion.utils.SqlUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
* @author 35880
* @description 针对表【user_info(用户基本信息表)】的数据库操作Service实现
* @createDate 2025-04-24 11:47:37
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{

    @Resource
    private JWTUtils jwtUtils;


    /**
     * 获取查询条件
     */
    @Override
    public QueryWrapper<UserInfo> getQueryWrapper(UserInfoQueryRequest userInfoQueryRequest) {
        Long id = userInfoQueryRequest.getId();
        String phoneNumber = userInfoQueryRequest.getPhoneNumber();
        String sortField = userInfoQueryRequest.getSortField();
        String sortOrder = userInfoQueryRequest.getSortOrder();
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(phoneNumber), "phoneNumber", phoneNumber);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }


    /**
     * web端用户登录
     */
    @Override
    public String userInfoLogin(String userAccount, String userPassword, HttpServletRequest request) {
        ThrowUtils.throwIf(userAccount.length() < 6 || userPassword.length() < 6, ErrorCode.PARAMS_ERROR);
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserInfo::getUserAccount, userAccount).eq(UserInfo::getUserPassword, userPassword);
        UserInfo userInfo = this.getOne(lambdaQueryWrapper);
        ThrowUtils.throwIf(userInfo == null, ErrorCode.OPERATION_ERROR, "用户不存在");
        Map<String, String> payload = new HashMap<>();
        payload.put("userAccount", userAccount);
        payload.put("userPassword", userPassword);
        return jwtUtils.generateToken(payload);
    }
}




