package com.engine.kq.cmd.schedulesignimport;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.kq.biz.KQFormatBiz;
import com.engine.kq.timer.KQQueue;
import com.engine.kq.timer.KQTaskBean;
import com.engine.kq.wfset.util.SplitActionUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import weaver.common.DateUtil;
import weaver.conn.BatchRecordSet;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.common.Tools;
import weaver.systeminfo.SystemEnv;

public class UpLoadDataCmd extends AbstractCommonCommand<Map<String, Object>> {
  private static DateFormat df = new SimpleDateFormat("HH:mm:ss");

  public UpLoadDataCmd(Map<String, Object> params, User user) {
    this.params = params;
  }

	@Override
	public Map<String, Object> execute(CommandContext commandContext) {
		Map<String, Object> retmap = new HashMap<String, Object>();
    String sql = "";
    RecordSet rs = new RecordSet();
    BatchRecordSet bRs = new BatchRecordSet();
    List<List<Object>> lsParams = new ArrayList<>();
    List<Object> params = null;

    List<String> lsFormatData = new ArrayList<>();
    List<List<Object>> lsFormatParams = new ArrayList<>();
    List<Object> formatParams = null;

    List<List<Object>> lsDelParams = new ArrayList<>();
    List<Object> delParams = null;

    JSONObject jsonObj = JSON.parseObject(Util.null2String(this.params.get("data")));
    JSONArray scheduleInfo = jsonObj.getJSONArray("scheduleInfo");
      writeLog("jsonObj.toJSONString()"+jsonObj.toJSONString());
    try {
      for (int i = 0; i < scheduleInfo.size(); i++) {
        JSONObject obj = (JSONObject)scheduleInfo.get(i);

        String machineCode = Util.null2String(obj.get("machineCode")).trim();
        String userCode = Util.null2String(obj.get("userCode")).trim();
        String signdate = Util.null2String(obj.get("checkDate")).trim();
        String signtime = Util.null2String(obj.get("checkTime")).trim();
        String clientaddress = Util.null2String(obj.get("clientAddress")).trim();
        String longitude = Util.null2String(obj.get("longitude")).trim();
        String latitude = Util.null2String(obj.get("latitude")).trim();
        String addr = Util.null2String(obj.get("addr")).trim();
        String memo = Util.null2String(obj.get("memo")).trim();

        //判断tmpSigntime格式 08:21:11 如果为长格式需要格式化
        if (signtime.length() > 8) {
          signtime = df.format(Timestamp.valueOf(signtime));
        } else if (signtime.length() < 8) {
          //不带秒的情况  自动补齐
          signtime += ":00";
        }

        if (signdate.length() > 10) {
          //如果时间为长格式，从signdate字段中格式化时间
          if (signdate.length() == 16) {
            //不带秒的情况  自动补齐
            signdate += ":00";
          }
          if (signtime.length() == 0) {//以signtime字段为有限
            signtime = df.format(Timestamp.valueOf(signdate));
            ;
          }
          signdate = Tools.formatDate(signdate, "yyyy-MM-dd");
        }

        //如果时间格式不带秒补齐
        if (signtime.length() <= 5) {
          signtime += ":00";
        }
        int userid = 0;
        if (Util.null2String(userCode).length() > 0) {
          //machineCode、userCode转userid
          userid = getUserId(userCode,machineCode);
        }

        if(userid<=0||signdate.length()<=0||signtime.length()<=0)continue;
        params = new ArrayList<>();
        params.add(userid);
        params.add(1);
        params.add(signdate);
        params.add(signtime);
        params.add(clientaddress);
        params.add(1);
        params.add(1);
        params.add("OutDataSourceSyn");
        params.add(longitude);
        params.add(latitude);
        params.add(addr);
        params.add(memo);
        lsParams.add(params);

        String formatData = userid+"|"+signdate+"|"+signtime;
        if(!lsFormatData.contains(formatData)){
          lsFormatData.add(formatData);
        }
      }

      Map<String,List<String>> overtimeMap = Maps.newHashMap();
      List<String> overtimeList = Lists.newArrayList();
      //刷新报表数据
      for(int i=0;lsFormatData!=null&&i<lsFormatData.size();i++){
        formatParams = new ArrayList<>();
        String[] formatData = Util.splitString(lsFormatData.get(i),"|");
        String date_1 = DateUtil.addDate(formatData[1], -1);
        formatParams.add(formatData[0]);
        formatParams.add(date_1);
        lsFormatParams.add(formatParams);

        formatParams = new ArrayList<>();
        formatParams.add(formatData[0]);
        formatParams.add(formatData[1]);
        lsFormatParams.add(formatParams);

        delParams = new ArrayList<>();
        delParams.add(formatData[0]);
        delParams.add(formatData[1]);
        delParams.add(formatData[2]);
        lsDelParams.add(delParams);

        String resourceId = formatData[0];
        String kqdate = formatData[1];
        if(overtimeMap.containsKey(resourceId)){
          List<String> tmp_overtimeList = overtimeMap.get(resourceId);
          if(!tmp_overtimeList.contains(kqdate)){
            tmp_overtimeList.add(kqdate);
          }
        }else{
          if(!overtimeList.contains(kqdate)){
            overtimeList.add(kqdate);
          }
          overtimeMap.put(resourceId, overtimeList);
        }
      }

      //删除本次同步数据
      sql = " delete from hrmschedulesign where signfrom='OutDataSourceSyn' and userid =? and signdate = ? and signtime = ? ";
      bRs.executeBatchSql(sql, lsDelParams);

      sql = " insert into HrmScheduleSign (userid, usertype, signdate, signtime, clientaddress, isincom, isimport, signfrom, longitude, latitude, addr,memo) "
              + " values(?,?,?,?,?,?,?,?,?,?,?,?)";
      bRs.executeBatchSql(sql,lsParams);

      new KQFormatBiz().format(lsFormatParams);

      //处理加班生成
      List<KQTaskBean> tasks = new ArrayList<>();
      for(Map.Entry<String, List<String>> mme: overtimeMap.entrySet()){
        String resid = mme.getKey();
        List<String> overList = mme.getValue();
        for(String date : overList){
          SplitActionUtil.pushOverTimeTasks(date,date,resid,tasks);
        }
      }
      if(!tasks.isEmpty()){
        KQQueue.writeTasks(tasks);
      }

			retmap.put("status", "1");
			retmap.put("message", SystemEnv.getHtmlLabelName(	83885,7));
		} catch (Exception e) {
			writeLog("上传考勤数据：" + e);
			retmap.put("status", "-1");
		}
		return retmap;
	}

  public static int getUserId(String userCode, String machineCode) {
    int userid = 0;
    RecordSet rs = new RecordSet();
    String sql = "";
    sql = "select resourceid from kq_schedule_code where schedulecode='" + userCode + "'";
    if(machineCode.length()>0){
      sql+=" and deviceid = (select id from kq_schedule_device where devicecode='"+machineCode+"')";
    }
    rs.execute(sql);
    if (rs.next()) {
      userid = rs.getInt("resourceid");
    }
    return userid;
  }

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