package net.tccn.user;

import net.tccn.base.BaseService;
import net.tccn.base.JBean;
import org.redkale.net.http.RestMapping;
import org.redkale.net.http.RestService;
import org.redkale.net.http.RestSessionid;
import org.redkale.source.FilterNode;

/**
 * @author: liangxianyou at 2018/11/22 17:16.
 */
@RestService(name = "user", automapping = true, comment = "用户服务")
public class UserService extends BaseService {

    @RestMapping(name = "login", auth = false, comment = "登陆验证")
    public JBean login(@RestSessionid String sessionid,
                       String username,
                       String pwd) {
        MUser bean = new MUser();
        bean.setUsername(username);

        //MUser user = MetaKit.findFirst(bean);
        MUser user = metaSource.find(MUser.class, FilterNode.create("username", username));
        if (user == null) {
            return JBean.by(-1, "登陆失败:账号无效");
        }

        JBean jBean = user.checkLogin(pwd);
        if (jBean.getCode() == 0) {
            cacheSource.set(30 * 60 * 2, sessionid, MUser.class, user);

            user.setSessionid(sessionid);
            user.setLogintime(System.currentTimeMillis());
            // MetaKit.save(user);
            metaSource.updateColumn(user, "sessionid", "logintime");
        }

        return jBean;
    }

    @RestMapping(name = "current")
    public MUser current(@RestSessionid String sessionid) {
        // T
        //return getT("user_" + sessionid, MUser.class, () -> MetaKit.findFirst(new MetaUser(sessionid)));
        MUser user = metaSource.find(MUser.class, FilterNode.create("sessionid", sessionid));
        return user;
    }

    @RestMapping(name = "logout", comment = "退出登陆")
    public JBean logout(@RestSessionid String sessionid) {
        MUser user = metaSource.find(MUser.class, FilterNode.create("sessionid", sessionid));
        if (user != null) {
            user.setSessionid("");
            metaSource.updateColumn(user, "sessionid");
        }
        // cacheSource.removeAsync("user_" + sessionid);

        return JBean.OK;
    }

}
