package com.mobvista.apptag.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.mobvista.apptag.entity.User;
import com.mobvista.apptag.mapper.UserDao;
import com.mobvista.apptag.service.UserService;
import com.mobvista.apptag.utils.MD5Util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author wangjf
 */

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

    @Autowired
    private UserDao userDao;

    @Override
    public boolean createUser(Map<String, Object> uMap, String userId) {
        User user = new User();
        user.setUserId(uMap.get("username").toString());
        user.setUserName(uMap.get("username").toString());
        try {
            user.setPassword(MD5Util.getMD5Str(uMap.get("password").toString()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        user.setState(Integer.parseInt(uMap.get("state").toString()));
        user.setRole(Integer.parseInt(uMap.get("role").toString()));
        user.setUpdateTime(new Date());

        return this.userDao.save(user);
    }

    @Override
    public void updateUser(User user) {
        user.setUpdateTime(new Date());
        this.userDao.update(user);
    }

    @Override
    public Map<String, Object> find(String userId) {
        Map<String, Object> attributes = new HashMap<>();
        User user = this.userDao.find(userId);
        attributes.put("user", user);
        return attributes;
    }

    @Override
    public Map<String, Object> list() {
        Map<String, Object> attributes = new HashMap<>();
        List<User> users = this.userDao.list();
        attributes.put("users", users);
        attributes.put("userDto", new User());
        return attributes;
    }

    @Override
    public Boolean validate(String user_id, String password) {
        User user = userDao.find(user_id);
        try {
            if (user != null && user.getPassword().equals(MD5Util.getMD5Str(password))) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean exit(String userName) {
        boolean exit;
        exit = userDao.find(userName) != null;
        return exit;
    }

}