package cn.edu.hactcm.cotroller;

import cn.edu.hactcm.common.R;
import cn.edu.hactcm.entity.User;
import cn.edu.hactcm.service.UserService;
import cn.edu.hactcm.utils.ValidateCodeUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 发送手机短信验证码
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> getMsg(@RequestBody User user, HttpSession session){
        if (user.getPhone() != null) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info(code);
            //模拟发送短信
            //SMSUtils.sendMessage("汉马外卖","","1111111111",code);
            session.setAttribute(user.getPhone(),code);
            return R.success("发送成功");
        }
        return R.error("发送失败");
    }


    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        String code = (String) map.get("code");
        String phone = (String) map.get("phone");
        if (code != null && code.equals(session.getAttribute(phone))) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            return R.success(user);
        }
        return R.error("登陆失败");
    }
}
