package com.yeejoin.amos.avic.config;


import com.yeejoin.amos.avic.face.service.EMailSenderService;
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 com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import lombok.Data;
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 javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;

@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;
	/*用于加载邮箱信息*/
	@Autowired
	private EMailSenderService eMailSenderService;

	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();

		//配置发送方邮箱信息
		configureEmail();
	}

	private void configureEmail()  {
		FeignClientResult<List<DictionarieValueModel>> emailbox = Systemctl.dictionarieClient.dictValues("EMAIL_BOX");
		List<DictionarieValueModel> result = emailbox.getResult();
		try {
			eMailSenderService.start(result);
		}catch (java.lang.Exception e) {
			e.printStackTrace();
		}

	}
}
