package com.engine.kq.cmd.schedulesignimport;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.KQFormatBiz;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import weaver.common.StringUtil;
import weaver.conn.BatchRecordSet;
import weaver.conn.RecordSet;
import weaver.file.Prop;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiAttendanceListRequest;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiAttendanceListResponse;
import com.dingtalk.api.response.OapiGettokenResponse;
import weaver.general.Util;

public class SynDingTalkDataCmd extends AbstractCommonCommand<Map<String, Object>> {
	private SimpleBizLogger logger;
	public SynDingTalkDataCmd(Map<String, Object> params) {
		this.params = params;
	}

	@Override
	public Map<String, Object> execute(CommandContext commandContext) {
		Map<String, Object> retmap = new HashMap<String, Object>();
		try{
			String fromDate = Util.null2String(params.get("fromDate"));
			String toDate = Util.null2String(params.get("toDate"));
			String sql = "";
			RecordSet rs = new RecordSet();
			BatchRecordSet bRs = new BatchRecordSet();
			RecordSet rs1 = new RecordSet();
			List<String> lsFormatData = new ArrayList<>();
			List<List<Object>> lsFormatParams = new ArrayList<>();
			List<Object> formatParams = null;

			rs.executeUpdate("delete HrmScheduleSign where isimport=1 and signdate>='"+fromDate+"' and signdate<='"+toDate+"'");

			Map<String, String> resourceIdMap = new HashMap<String, String>();
			rs.executeQuery("select id,workcode from hrmresource where workcode is not null and workcode<>''");
			while(rs.next()){
				resourceIdMap.put(Util.formatMultiLang(rs.getString("workcode")), StringUtil.vString(rs.getString("id")));
			}

			String corpId = StringUtil.vString(Prop.getInstance().getPropValue("HrmSynDDInfo", "corpId"));
			String corpSecret = StringUtil.vString(Prop.getInstance().getPropValue("HrmSynDDInfo", "corpSecret"));
			if(corpId.length()==0||corpSecret.length()==0){
				writeLog("获取钉钉考勤数据失败：corpId=="+corpId+" corpSecret=="+corpSecret);
				retmap.put("status", "-1");
				retmap.put("message", ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005341,weaver.general.ThreadVarLanguage.getLang())+"corpId=="+corpId+" corpSecret=="+corpSecret);
				return retmap;
			}
			DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
			OapiGettokenRequest request1 = new OapiGettokenRequest();
			request1.setAppkey(corpId);
			request1.setAppsecret(corpSecret);
			request1.setHttpMethod("GET");
			OapiGettokenResponse response1 = client.execute(request1);
			String accessToken = response1.getAccessToken();

			client = new DefaultDingTalkClient("https://oapi.dingtalk.com/attendance/list");
			OapiAttendanceListRequest request = new OapiAttendanceListRequest();
			request.setWorkDateFrom(fromDate+" 00:00:00");
			request.setWorkDateTo(toDate+" 23:59:59");
			request.setOffset(0L);
			request.setLimit(50L);
			List<String> resourceList = new ArrayList<String>();
			int ni = 0;
			rs.executeQuery("select workcode from hrmresource where workcode is not null and workcode<>''");
			while(rs.next()){
				ni++;
				resourceList.add(Util.formatMultiLang(rs.getString("workcode")));
				if(ni%10==0 || ni==rs.getCounts()){
					try {
						request.setUserIdList(resourceList);
						OapiAttendanceListResponse response = client.execute(request, accessToken);
						JSONObject jsonData = JSONObject.fromObject(response);
						if(!"0".equals(StringUtil.vString(jsonData.get("errcode")))){
							writeLog("获取钉钉考勤数据失败："+jsonData.get("errmsg"));
							retmap.put("status", "-1");
							retmap.put("message", ""+weaver.systeminfo.SystemEnv.getHtmlLabelName(10005341,weaver.general.ThreadVarLanguage.getLang())+""+jsonData.get("errmsg"));
							return retmap;
						}
						Calendar calendar = Calendar.getInstance();
						DateFormat formatterDate = new SimpleDateFormat("yyyy-MM-dd");
						DateFormat formatterTime = new SimpleDateFormat("HH:mm:ss");
						JSONArray jsonList = JSONArray.fromObject(jsonData.get("recordresult"));
						for(int i=0;i<jsonList.size();i++){
							JSONObject data = jsonList.getJSONObject(i);
							String locationResult = StringUtil.vString(data.get("locationResult"));
							if("NotSigned".equals(locationResult)){
								continue;
							}
							String userId = StringUtil.vString(data.get("userId"));
							String oaUserId = StringUtil.vString(resourceIdMap.get(userId));
							if("".equals(oaUserId)){
								writeLog("通过工号（"+userId+"）无法在OA找到对应人员，请维护人员信息！");
								continue;
							}
							JSONObject jsonCheckTime = JSONObject.fromObject(data.get("userCheckTime"));
							if("".equals(StringUtil.vString(jsonCheckTime.get("time")))){
								writeLog("获取实际打卡时间失败：userId="+userId);
								continue;
							}
							long userCheckTime = StringUtil.parseToLong(jsonCheckTime.get("time"));
							calendar.setTimeInMillis(userCheckTime);
							String signDate = formatterDate.format(calendar.getTime());
							String signTime = formatterTime.format(calendar.getTime());
							String checkType = StringUtil.vString(data.get("checkType"));
							String signType = "";
							if("OnDuty".equals(checkType)){
								signType = "1";
							}else if("OffDuty".equals(checkType)){
								signType = "2";
							}else{
								writeLog("获取考勤类型失败：userId="+userId);
								continue;
							}
							writeLog("获取考勤数据：oaUserId="+oaUserId+",userId="+userId+",userCheckTime="+userCheckTime+",locationResult="+locationResult+",checkType="+checkType+",signDate="+signDate+",signTime="+signTime);
							rs1.executeUpdate("insert into hrmScheduleSign(userid,userType,signType,signDate,signTime,isInCom,isImport,signFrom) values("+oaUserId+",'1','"+signType+"','"+signDate+"','"+signTime+"','1',1,'DingTalk')");
							String formatData = oaUserId+"|"+signDate;
							if(!lsFormatData.contains(formatData)){
								lsFormatData.add(formatData);
							}
						}
						resourceList = new ArrayList<String>();
					} catch (Exception e) {
						writeLog(this.getClass().getName(),e);
					}
				}
			}

			//刷新报表数据
			for(int i=0;lsFormatData!=null&&i<lsFormatData.size();i++){
				formatParams = new ArrayList<>();
				String[] formatData = Util.splitString(lsFormatData.get(i),"|");
				formatParams.add(formatData[0]);
				formatParams.add(formatData[1]);
				lsFormatParams.add(formatParams);
			}
			new KQFormatBiz().format(lsFormatParams);
		} catch (Exception e) {
			writeLog("同步钉钉考勤数据：" + e);
			retmap.put("status", "-1");
		}
		return retmap;
	}

	@Override
	public BizLogContext getLogContext() {
		return null;
	}

	@Override
	public List<BizLogContext> getLogContexts() {
		return logger.getBizLogContexts();
	}

}
