package net.wicp.tams.duckula.ops.pages;

import java.util.List;

import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.http.services.Request;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.slf4j.Logger;

import cn.hutool.crypto.digest.BCrypt;
import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.app.duckula.controller.bean.models.SysUser;
import net.wicp.tams.app.duckula.controller.dao.SqlMapper;
import net.wicp.tams.app.duckula.controller.dao.SysUserMapper;
import net.wicp.tams.common.apiext.CollectionUtil;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.constant.dic.YesOrNo;
import net.wicp.tams.duckula.ops.WebTools;
import net.wicp.tams.duckula.ops.beans.SessionBean;

@Import(stack = "easyuistack")
@Slf4j
public class Login {
	@Inject
	private Logger logger;

	@Inject
	protected Request request;

	@SessionState
	private SessionBean sessionBean;

	@Inject
	private SysUserMapper sysUserMapper;

	@Inject
	private SqlMapper sqlMapper;

	@SuppressWarnings("unchecked")
	Object onSuccess() {
		String userName = request.getParameter("userName");
		String pwd = request.getParameter("pwd");
		if (StringUtil.isNull(userName) || StringUtil.isNull(pwd)) {
			return Login.class;
		}
		WebTools.skipSQLInterceptor(false);
		List<SysUser> selUsers = sysUserMapper.selectByMap(CollectionUtil.newMap("user_name", userName));
		if (selUsers.size() != 1) {
			log.error("用户不惟一,数量：{}", selUsers.size());
			return Login.class;
		}
		SysUser sysUser = selUsers.get(0);
		List<Long> roles = sqlMapper.selectRoleByStaff(sysUser.getId());
		boolean checkpw = BCrypt.checkpw(pwd, sysUser.getPassword());
		if (!checkpw) {
			log.error("用户{}密码有误", userName);
			return Login.class;
		}
		sessionBean = new SessionBean();
		sessionBean.setIsLogin(YesOrNo.yes);
		sessionBean.setSysUser(selUsers.get(0));
		sessionBean.setRoles(roles);
		return Index.class;
	}

}
