package xyz.luxnk.lproject.service;

import org.apache.shiro.crypto.hash.Sha256Hash;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.random.R;
import org.nutz.service.IdNameEntityService;
import xyz.luxnk.lproject.bean.UserInfo;

import java.util.Date;

@IocBean(fields = "dao")
public class UserService extends IdNameEntityService<UserInfo> {

    /**
     * 添加新用户
     * @param username
     * @param password
     * @return
     */
    public UserInfo add(String username, String password) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(username.trim());
        userInfo.setSalt(R.UU16());
        userInfo.setPassword(new Sha256Hash(password, userInfo.getSalt()).toHex());
        userInfo.setCreateTime(new Date());
        userInfo.setUpdateTime(new Date());
        return dao().insert(userInfo);
    }

    /**
     * 根据用户名密码验证用户登录信息
     * @param username
     * @param password
     * @return
     */
    public String fetch(String username, String password) {
        UserInfo userInfo = dao().fetch(UserInfo.class, Cnd.where("username", "=", username));
        if (userInfo == null) {
            return "";
        }
        String _pass = new Sha256Hash(password, userInfo.getSalt()).toHex();
        if (_pass.equalsIgnoreCase(userInfo.getPassword())) {
            return userInfo.getId();
        }
        return "";
    }

    /**
     * 更新用户密码
     * @param userId
     * @param password
     */
    public void updatePassword(String userId, String password) {
        UserInfo userInfo = fetch(userId);
        if (userInfo == null) {
            return;
        }
        userInfo.setSalt(R.UU16());
        userInfo.setPassword(new Sha256Hash(password, userInfo.getSalt()).toHex());
        userInfo.setUpdateTime(new Date());
        dao().update(userInfo, "^(password|salt|updateTime)$");
    }

}
