package com.lovenav.service.serviceImpl;


import com.lovenav.dao.UserDao;
import com.lovenav.utils.EmailUtils;
import com.lovenav.entity.User;
import com.lovenav.service.UserService;
import com.lovenav.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.regex.Pattern;


@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    UserDao userDao;
    @Override
    public User userLogin(User user) {
        boolean result;
        User user1;
        result= Pattern.matches("^(\\w+([-.][A-Za-z0-9]+)*){3,18}@\\w+([-.][A-Za-z0-9]+)*\\.\\w+([-.][A-Za-z0-9]+)*$", user.getUserLogin());
        user.setUserPassword(MD5Utils.md5(user.getUserPassword()));
        if (result == true) {
            user1= userDao.selectByEmail(user.getUserLogin());
            if (user1==null){
                return null;
            }
            else if (user1.getUserPassword().equals(user.getUserPassword())){

                return user1;
            }else {
                return null;
            }
        }else {
            user1=userDao.selectByUserLogin(user.getUserLogin());

            if (user1==null ){
                return null;
            }
            else if (user1.getUserPassword().equals(user.getUserPassword())){
                return user1;
            }else {
                return null;
            }

        }
    }

    @Override
    public int updatePassword(User user) {
        user.setUserPassword(MD5Utils.md5(user.getUserPassword()));
        return userDao.updateByEmail(user);
    }

    @Override
    public HashMap<Integer, Object> getAllUsers() {
        HashMap<Integer, Object> map=new HashMap<>();
        map=userDao.selectAllUsers();
        return map;
    }

    @Override
    public String sendEmailActivecode(User user, HashMap<String,String>configMap) {
        return EmailUtils.sendEmail(user,configMap);
    }

    @Override
    public int UserRegister(User user) {

        user.setRoleId(Byte.valueOf("1"));
        user.setUserStatus(Byte.valueOf("1"));
        user.setUserPassword(MD5Utils.md5(user.getUserPassword()));
        Date date=new Date();
        user.setUserRegistered(date);


        return  userDao.insert(user);
    }


    @Override
    public User selectUserAlreadyExist(User user) {
        System.out.println(user.getUserEmail());

        User user1=userDao.selectByEmail(user.getUserEmail());
        return user1;
    }


}
