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.jfplugin.mail.MailKit;
import com.sys.bus.hr.model.Person;
import com.sys.bus.hr.service.HrService;
import com.sys.bus.model.Email;
import com.sys.bus.model.WxPerson;
import com.sys.bus.sys.wx.WxUtil;
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.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class WxPersonTask 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() {//////参考飞书同步，逻辑有待完善  之前写完未测试，换成取shr的同步信息了
		if(!flag){
			log.info("进入 WxPersonTask 。。。。");
			flag = true;
			try{
				List<Person> personList = hrService.getAllEnablePerson();
				List<WxPerson> wxPersonList = WxPerson.dao.find("select * from ct_jx_wxperson");
				String wxcorpid = sysCodeService.getSysCodeName("wxcorpid").getSyscodeValue();
				String wxsecret = sysCodeService.getSysCodeName("wxsecret").getSyscodeValue();
				if(StringUtils.isBlank(wxcorpid) ||StringUtils.isBlank(wxsecret)){
					log.error("微信配置不完整！退出微信人员同步任务！");
					return;
				}

				String token = WxUtil.getToken(wxcorpid, wxsecret);
				LocalDateTime now = LocalDateTime.now();
				DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
				String currTime = dtf.format(now);
				JSONArray persons = WxUtil.getPerson(WxUtil.getDeptId(token), token);
				Map<String, WxPerson> wxPersonId2PersonMap = wxPersonList.stream().collect(Collectors.toMap(WxPerson::getWxPersonId, person -> person));
				Map<String, Person> personNumber2Person = personList.stream().collect(Collectors.toMap(person ->person.getNumber(),person -> person));
				for (Object person : persons) {
					JSONObject jsonPerson = JSONObject.parseObject(person.toString());
					String userid = jsonPerson.getString("userid");
					String name = jsonPerson.getString("name");
					//String position = jsonPerson.getString("position");
					//String mobile = jsonPerson.getString("mobile");
					boolean newPerson = true;
					if(wxPersonId2PersonMap.containsKey(userid)){//已经同步过的wx用户
						newPerson = false;
					}
					WxPerson wxPerson = null;
					if(newPerson){
						wxPerson = new WxPerson();
						wxPerson.setWxPersonCreatetime(currTime);
					}else{
						wxPerson = wxPersonId2PersonMap.get(userid);
					}
					wxPerson.setWxPersonName(name);
					//wxPerson.setWxPersonPosition(position);
					//wxPerson.setWxPersonMobile(mobile);
					wxPerson.setWxPersonId(userid);

					String number = wxPerson.getWxPersonMatchData();
					if(StringUtils.isBlank(number)){
						number = userid;
					}

					Person p = personNumber2Person.get(number);
					if(p != null && !p.getId().equals(wxPerson.getWxPersonPid())){
						wxPerson.setWxPersonUpdatetime(currTime);
						wxPerson.setWxPersonPid(p.getId());
						wxPerson.setWxPersonPname(p.getName());
					}
					wxPerson.setWxPersonMatchData(number);
					if(newPerson){
						wxPerson.save();
					}else{
						wxPerson.update();
					}
				}

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

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

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

}
