package cn.ibizlab.util.service;

import cn.ibizlab.util.security.AuthenticationUser;
import cn.ibizlab.util.client.uaa.UAAFeignClient;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

/**
 * 实体[IBZUSER] 服务对象接口实现
 */
@Primary
@Service("SimpleUserService")
public class SimpleUserService implements AuthenticationUserService{



	@Override
	public AuthenticationUser loadUserByUsername(String username) {
		AuthenticationUser user = new AuthenticationUser();
		String[] data=username.split("[|]");
		String loginname=username;
		String domains="";
		String password="";

		if(data.length==3) {
			loginname=data[0].trim();
			domains=data[1].trim();
			password=data[2].trim();
		}
		else if(data.length==2) {
			loginname=data[0].trim();
			password=data[1].trim();
		}

		user.setUserid(DigestUtils.md5DigestAsHex(username.getBytes()));
		user.setUsercode(loginname);
		user.setUsername(username);
		user.setLoginname(loginname);
		user.setPersonname(loginname);
		user.setDomain(domains);
		user.setPassword(password);
		user.setOrgid(domains);
		user.setOrgcode(domains);
		user.setOrgname(domains);

		setUserPermission(user);

		return user;
	}

	@Override
	public AuthenticationUser loadUserByLogin(String username, String password) {
		password = DigestUtils.md5DigestAsHex(String.format("%1$s||%2$s", username, password).getBytes());
		AuthenticationUser authuserdetail = loadUserByUsername(username+"|"+password);
		return authuserdetail;
	}

	@Override
	public AuthenticationUser loadUserByLogin(String domain, String username, String password) {
		if(!StringUtils.isEmpty(domain))
			username = username+"|"+domain;
		return loadUserByLogin(username,password);
	}

	@Override
	public void resetByUsername(String username) {

	}

	@Value("${ibiz.enablePermissionValid:false}")
	boolean enablePermissionValid;  //是否开启权限校验

    @Value("${ibiz.systemid:2C40DFCD-0DF5-47BF-91A5-C45F810B0001}")
    private String systemid;

	@Autowired
	private UAAFeignClient client;

	/**
	 * 设置用户权限
	 */
	private void setUserPermission(AuthenticationUser curUser) {
		if(enablePermissionValid){
            String userid=curUser.getUserid();
			//String userid="4fb71d8997d4505d2748ad2bdc471969";
			//String systemid="2C40DFCD-0DF5-47BF-91A5-C45F810B0001";
			JSONObject permission= client.getUserPermissionData(userid,systemid);
			curUser.setPermisionList(permission);
		}
	}
}
