package com.sys.bus.sys.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Enhancer;
import com.jfinal.plugin.cron4j.ITask;
import com.sys.bus.hr.model.Person;
import com.sys.bus.hr.service.HrService;
import com.sys.bus.model.LarkPerson;
import com.sys.bus.sys.lark.LarkUtil;
import com.sys.bus.syscode.service.SysCodeService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class LarkPersonTask implements ITask {
	Log log = LogFactory.getLog(this.getClass());
	static boolean flag = false;//防重复调用
	static SysCodeService sysCodeService = new SysCodeService();
	static HrService hrService = Enhancer.enhance(HrService.class);
	public void run() {
		if(!flag){
			log.info("进入 LarkPersonTask 。。。。");
			flag = true;
			try{
				List<Person> personList = hrService.getAllEnablePerson();
				List<LarkPerson> larkPersonList = LarkPerson.dao.find("select * from ct_jx_larkperson");
				String appid = sysCodeService.getSysCodeName("飞书appid").getSyscodeValue();
				String secret = sysCodeService.getSysCodeName("飞书secret").getSyscodeValue();
				if(StringUtils.isBlank(appid) ||StringUtils.isBlank(secret)){
					log.error("飞书配置不完整！退出飞书人员同步任务！");
					return;
				}
				String token = LarkUtil.getToken(appid, secret);
				LocalDateTime now = LocalDateTime.now();
				DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
				String currTime = dtf.format(now);
				JSONArray persons = LarkUtil.getAllPerson(token);
				Map<String, LarkPerson> larkPersonId2PersonMap = larkPersonList.stream().collect(Collectors.toMap(LarkPerson::getLarkPersonId, person -> person));
				Map<String, Person> personNumber2Person = personList.stream().collect(Collectors.toMap(person ->person.getNumber(),person -> person));
				if(persons.size() ==0)return;
				List<String> getLarkIds = new ArrayList<>();
				for (Object person : persons) {
					JSONObject jsonPerson = JSONObject.parseObject(person.toString());
					String employee_no = jsonPerson.getString("employee_no");
					String userid = jsonPerson.getString("user_id");
					String name = jsonPerson.getString("name");
					if(getLarkIds.contains(userid)){
						//log.error("接口获取到相同的飞书userid用户数据："+userid+",name:"+name);
						continue;
					}
					getLarkIds.add(userid);

					//String position = jsonPerson.getString("position");
					//String mobile = jsonPerson.getString("mobile");
					boolean newPerson = true;
					if(larkPersonId2PersonMap.containsKey(userid)){//已经同步过的lark用户
						newPerson = false;
					}
					LarkPerson larkPerson = null;
					if(newPerson){
						larkPerson = new LarkPerson();
						larkPerson.setLarkPersonCreatetime(currTime);
					}else{
						larkPerson = larkPersonId2PersonMap.get(userid);
					}
					larkPerson.setLarkPersonName(name);
					larkPerson.setLarkPersonId(userid);

					larkPerson.setLarkPersonMatchData(employee_no);
					Person p = personNumber2Person.get(employee_no);
					if(p != null && p.getId().equals(larkPerson.getLarkPersonPid())){
						continue;
					}
					if(p != null && !p.getId().equals(larkPerson.getLarkPersonPid())){
						larkPerson.setLarkPersonUpdatetime(currTime);
						larkPerson.setLarkPersonPid(p.getId());
						larkPerson.setLarkPersonPname(p.getName());
					}
					if(p == null){
						larkPerson.setLarkPersonUpdatetime(currTime);
						larkPerson.setLarkPersonPid("");
						larkPerson.setLarkPersonPname("");
					}

					if(newPerson){
						larkPerson.save();
					}else{
						larkPerson.update();
					}
				}
				for(String userId : larkPersonId2PersonMap.keySet()){
					if(!getLarkIds.contains(userId)){// 本次没获取到的飞书id   清理
						LarkPerson larkPerson = larkPersonId2PersonMap.get(userId);
						larkPerson.setLarkPersonUpdatetime(currTime);
						larkPerson.setLarkPersonPid("");
						larkPerson.setLarkPersonPname("");
						larkPerson.update();
					}
				}

			} catch (Exception e) {
				log.error("飞书员工信息同步失败>",e);
			}finally{
				flag = false;
			}

		}else{
			log.error("LarkPersonTask 任务进行中。。。。本次跳出任务");
		}
	}

	public void stop() {
		log.info("------LarkPersonTask stop-------------");
	}

}
