package com.yeejoin.amos.avic.config;



import java.util.HashMap;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.core.foundation.context.RequestContext;

import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.IdPasswordAuthModel;
import com.yeejoin.amos.feign.privilege.util.DesUtil;

import lombok.Data;

@Component
@ConfigurationProperties(prefix = "amos.auth")
@EnableScheduling
@Data
public class AmosAuth {
	private String userName;
	private String password;
	private String appKey;
	private String product;

	@Autowired
	Privilege privilege;

	HashMap<String, Object> model = null;

	@PostConstruct
	public void login() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				boolean flag = false;
				do {
					try {
						IdPasswordAuthModel arg0 = new IdPasswordAuthModel();
						arg0.setLoginId(userName);
						arg0.setPassword(DesUtil.encode(password, "qaz"));
						RequestContext.setProduct(product);
						RequestContext.setAppKey(appKey);
						FeignClientResult o = privilege.authClient.idpassword(arg0);
						model = (HashMap<String, Object>) o.getResult();
						flag = false;
					} catch (Exception e) {
						if (!flag) {
							e.printStackTrace();
						}
						flag = true;
						try {
							Thread.sleep(5000);
						} catch (InterruptedException e1) {
							e1.printStackTrace();
						}
					}
				} while (flag);
				configureTasks();
			}
		}).start();

	}

	public String getToken() {
		return model.get("token").toString();
	}

	public String getUserId() {
		return model.get("userId").toString();
	}

	// 或直接指定时间间隔，例如：5秒
	@Scheduled(fixedRate = 3600000)
	private void configureTasks() {
		RequestContext.setToken(getToken());
		RequestContext.setProduct(product);
		RequestContext.setAppKey(appKey);
		Privilege.agencyUserClient.getme();
	}
}
