package com.kingdee.eas.custom.synctask.handler;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.eas.custom.synctask.SyncTranForMJFacadeFactory;
import com.kingdee.shr.ats.web.handler.PunchCardRecordListHandler;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;


/**
 * @Description TODO
 * @Date 2024/10/29 17:51
 * @Created by 30489
 */
public class PunchCardRecordListHandlerEx extends PunchCardRecordListHandler {
    private Context ctx = SHRContext.getInstance().getContext();
    private Properties propt = new Properties();

    public PunchCardRecordListHandlerEx() throws BOSException {
        String syncOAConfigPath = System.getProperty("EAS_HOME") + "/server/properties/scy/syncMJConfig.properties";
        try {
            propt.load(new FileInputStream(syncOAConfigPath));
        } catch (IOException e) {
            e.printStackTrace();
            String errorMsg = "获取配置文件报错，请检查配置：" + syncOAConfigPath + "   " + e.getMessage();
            throw new BOSException(errorMsg);
        }
    }

    /**
     * 获取数据库打卡记录
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws BOSException
     */
    public void syncZKPunchCardDataAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws BOSException {
        SyncTranForMJFacadeFactory.getLocalInstance(ctx).syncPunchRecordFromMJ(null, null);
        //syncZKPunchCardData(request, response, modelMap);
    }

    /**
     * 获取门禁打卡记录
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws BOSException
     */
    public void syncPunchRecordFromMJAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws BOSException, ShrWebBizException {
        SyncTranForMJFacadeFactory.getLocalInstance(ctx).syncAccessRecord("", "");
        //syncZKPunchCardData(request, response, modelMap);
        //_syncAccessRecord(ctx, null, null);
    }


    //public void syncZKPunchCardData(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
    //    //String url = "jdbc:sqlserver://10.0.3.23:1433;databaseName=kaoqin";
    //    String url = "jdbc:sqlserver://10.0.3.23:1433;databaseName=kaoqin;encrypt=true;trustServerCertificate=true;";
    //    String username = "zhongkong";
    //    String password = "6554+oijhh@";
    //    try {
    //        // 加载SQL Server JDBC驱动程序
    //        //Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    //        // 建立连接
    //        Connection connection = DriverManager.getConnection(url, username, password);
    //        // 创建Statement对象
    //        Statement statement = connection.createStatement();
    //        //获取当前时间以及一个月前的时间
    //        // 获取当前日期
    //        Date now = new Date();
    //        Calendar calendar = Calendar.getInstance();
    //        calendar.setTime(now);
    //        // 将月份减1（这里只是简单的月份减1，没有考虑日期边界等复杂情况）
    //        calendar.add(Calendar.MONTH, -1);
    //        Date one_month_ago = calendar.getTime();
    //        // 获取当前日期
    //        Date currentDate = new Date();
    //        // 使用Calendar类来操作日期
    //        Calendar calendarNewDate = Calendar.getInstance();
    //        calendarNewDate.setTime(currentDate);
    //        // 在当前日期基础上加1天
    //        calendarNewDate.add(Calendar.DAY_OF_MONTH, 1);
    //        Date newDate = calendarNewDate.getTime();
    //        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    //        String oneMOnthDate = sdf.format(one_month_ago);
    //        String nowDate = sdf.format(newDate);
    //        logger.error("PunchCardRecordEx----oneMOnthDate--" + oneMOnthDate);
    //        logger.error("PunchCardRecordEx----nowDate--" + nowDate);
    //        int success = 0;
    //        int error = 0;
    //        // 执行查询语句
    //        //String query = "select \n" +
    //        //        "userinfo.SSN as personNumber ,\n" +
    //        //        "checkin.CHECKTIME as checkTime\n" +
    //        //        "from  checkinout as checkin\n" +
    //        //        "left join USERINFO as userinfo on userinfo.USERID = checkin.USERID\n" +
    //        //        "where checkin.CHECKTIME >='" + oneMOnthDate + "' and checkin.CHECKTIME <='" + nowDate + "'\n";
    //        String query = "\n" +
    //                " \n" +
    //                "select \n" +
    //                "userinfo.SSN as personNumber ,\n" +
    //                "checkin.CHECKTIME as checkTime\n" +
    //                "from  checkinout as checkin\n" +
    //                "left join USERINFO as userinfo on userinfo.USERID = checkin.USERID\n" +
    //                "where checkin.CHECKTIME >='2024-10-30' and checkin.CHECKTIME <='2024-10-31'\n" +
    //                " ";
    //        ResultSet resultSet = statement.executeQuery(query);
    //        Set<String> setCardId = new HashSet();
    //        Set<String> EquNoSet = new HashSet();
    //        Timestamp minDateTime = null;
    //        Timestamp maxDateTime = null;
    //        CoreBaseCollection cardCollFinally = new CoreBaseCollection();
    //        CoreBaseCollection cardColl = new CoreBaseCollection();
    //        JSONArray formatErrorRecords = new JSONArray();
    //        //存储相同的数据
    //        JSONArray duplicateRecords = new JSONArray();
    //        //存储考勤日期为空的数据
    //        JSONArray notExistRecords = new JSONArray();
    //
    //        JSONArray seccussArray = new JSONArray();
    //
    //        // 处理查询结果
    //        while (resultSet.next()) {
    //            ++success;
    //            String personNumber = resultSet.getString("personNumber");//员工编码
    //            String punchCardDate = resultSet.getString("checkTime"); //打卡时间
    //            String RecDate = punchCardDate.substring(0, 10);// 考勤日期
    //            String RecTime = punchCardDate.substring(11, 19);// 考勤时间
    //            //String locationDetail = resultSet.getString("name"); //打卡地点
    //            //String EquNo = resultSet.getString("EquNo"); //考勤机编码
    //            //String exceptionType = resultSet.getString("EquNo"); // 打卡/异常类型
    //            //Date punchDate = HRTimeWebUtils.stringToShortDate(RecDate, true);
    //            Date punchDate = com.kingdee.eas.custom.synctask.utils.HRTimeWebUtils.stringToShortDate(RecDate, true);
    //            Timestamp punchCardTime = com.kingdee.eas.custom.synctask.utils.HRTimeWebUtils.stringToTimestamp(punchCardDate, true);
    //            // 处理数据
    //            if (punchCardDate != null && punchCardTime != null) {
    //                PunchCardRecordInfo cardInfo = new PunchCardRecordInfo();
    //                //考勤机编码
    //                cardInfo.setEquipmentNum("001");
    //                //考勤编码
    //                cardInfo.setAttendanceNum(personNumber);
    //                //打卡日期
    //                cardInfo.setPunchCardDate(punchDate);
    //                //打卡时间
    //                cardInfo.setPunchCardTime(punchCardTime);
    //                // 打卡来源
    //                cardInfo.setPunchCardSource(PunchCardSourceEnum.mobileRegistration);
    //                // 打卡位置
    //                cardInfo.setPunchCardPlace("考勤机打卡");
    //                // 有效
    //                cardInfo.setPunchCardState(PunchCardStateEnum.normal);
    //                ////简称
    //                //cardInfo.setSimpleName(exceptionType);
    //                //描述
    //                //cardInfo.setDescription(exceptionType);
    //
    //                EquNoSet.add("001");
    //                if (!StringUtils.isEmpty(personNumber)) {
    //                    setCardId.add(personNumber);
    //                    cardColl.add(cardInfo);
    //                }
    //
    //                if (minDateTime != null && maxDateTime != null) {
    //                    if (punchCardTime.getTime() < minDateTime.getTime()) {
    //                        minDateTime = punchCardTime;
    //                    } else if (punchCardTime.getTime() > maxDateTime.getTime()) {
    //                        maxDateTime = punchCardTime;
    //                    }
    //                } else {
    //                    minDateTime = punchCardTime;
    //                    maxDateTime = punchCardTime;
    //                }
    //
    //            } else {
    //                formatErrorRecords.add(resultSet);
    //            }
    //        }
    //        // 考勤档案
    //        Map<String, AttendanceFileInfo> attendanceFileMap = AttendanceFileFactory.getLocalInstance(ctx).getPersonByAttendanceNum(setCardId);
    //        logger.error("attendanceFileMap-----" + attendanceFileMap);
    //        //相同的数据
    //        PunchCardRecordCollection existColl = this.getExistedPunchCardRecordCollection(ctx, minDateTime, maxDateTime, setCardId);
    //        logger.error("existColl-----" + existColl.size());
    //        for (int i = 0; i < cardColl.size(); ++i) {
    //            Map map = new HashMap();
    //            // 原始打卡记录实体
    //            PunchCardRecordInfo cardInfo = (PunchCardRecordInfo) cardColl.get(i);
    //            JSONObject jsObject = new JSONObject();
    //            jsObject.put("deviceid", cardInfo.getEquipmentNum()); // deviceid --EquNo
    //            jsObject.put("userid", cardInfo.getAttendanceNum()); // userid --CardId
    //            jsObject.put("RecDate", com.kingdee.eas.custom.synctask.utils.HRTimeWebUtils.dateShortToString(cardInfo.getPunchCardDate())); //checkin_time --RecDate
    //            jsObject.put("RecTime", com.kingdee.eas.custom.synctask.utils.HRTimeWebUtils.timestampToString(cardInfo.getPunchCardTime()).substring(11)); //checkin_time --RecDate
    //            map.put("userid", cardInfo.getAttendanceNum());
    //            map.put("RecDate", com.kingdee.eas.custom.synctask.utils.HRTimeWebUtils.dateShortToString(cardInfo.getPunchCardDate()));
    //            map.put("RecTime", HRTimeWebUtils.timestampToString(cardInfo.getPunchCardTime()).substring(11));
    //            //员工是否有考勤档案
    //            if (attendanceFileMap.containsKey(cardInfo.getAttendanceNum())) {
    //                if (existColl.contains(cardInfo)) {
    //                    duplicateRecords.add(jsObject);
    //                } else {
    //                    // 打卡位置 ，考勤机 的地址
    //                    cardInfo.setPunchCardPlace(cardInfo.getPunchCardPlace());
    //                    //打卡来源
    //                    cardInfo.setPunchCardSource(PunchCardSourceEnum.mobileRegistration);
    //                    // 考勤实体
    //                    AttendanceFileInfo attendanceFileInfo = (AttendanceFileInfo) attendanceFileMap.get(cardInfo.getAttendanceNum());
    //                    // 姓名
    //                    cardInfo.setProposer(attendanceFileInfo.getProposer());
    //                    // HR 组织
    //                    cardInfo.setHrOrgUnit(attendanceFileInfo.getHrOrgUnit());
    //                    //行政组织
    //                    cardInfo.setAdminOrgUnit(attendanceFileInfo.getAdminOrgUnit());
    //                    cardInfo.setCreator((UserInfo) ctx.get("UserInfo"));
    //                    cardInfo.setLastUpdateUser((UserInfo) ctx.get("UserInfo"));
    //                    cardInfo.setCreateTime(new Timestamp((new Date()).getTime()));
    //                    cardInfo.setLastUpdateTime(new Timestamp((new Date()).getTime()));
    //                    cardCollFinally.add(cardInfo);
    //                }
    //                seccussArray.add(map);
    //            } else {
    //                ++error;
    //                notExistRecords.add(jsObject);
    //            }
    //        }
    //        logger.error("cardCollFinally-----" + cardCollFinally.size());
    //        logger.error("success-----" + success);
    //        logger.error("error-----" + error);
    //        logger.error("notExistRecords--list---" + notExistRecords);
    //        logger.error("notExistRecords-----" + notExistRecords.size());
    //        logger.error("seccussArray--Size-----" + seccussArray.size());
    //        logger.error("seccussArray-----" + seccussArray);
    //        IObjectPK[] iObjectPKS = PunchCardRecordFactory.getLocalInstance(ctx).saveBatchData(cardCollFinally);
    //        logger.error("iObjectPKS----" + iObjectPKS.length);
    //        JSONUtils.SUCCESS(iObjectPKS);
    //        // 关闭连接
    //        resultSet.close();
    //        statement.close();
    //        connection.close();
    //
    //    } catch (Exception e) {
    //        e.printStackTrace();
    //    }
    //}
    //
    //private PunchCardRecordCollection getExistedPunchCardRecordCollection(Context ctx, Timestamp minDateTime, Timestamp maxDateTime, Set<String> setCardId) throws BOSException {
    //    EntityViewInfo evi = new EntityViewInfo();
    //    FilterInfo fi = new FilterInfo();
    //    evi.setFilter(fi);
    //    evi.getSelector().add(new SelectorItemInfo("punchCardDate"));
    //    evi.getSelector().add(new SelectorItemInfo("punchCardTime"));
    //    evi.getSelector().add(new SelectorItemInfo("punchCardSource"));
    //    evi.getSelector().add(new SelectorItemInfo("equipmentNum"));
    //    evi.getSelector().add(new SelectorItemInfo("attendanceNum"));
    //    fi.getFilterItems().add(new FilterItemInfo("attendanceNum", setCardId, CompareType.INCLUDE));
    //    fi.getFilterItems().add(new FilterItemInfo("punchCardTime", maxDateTime, CompareType.LESS_EQUALS));
    //    fi.getFilterItems().add(new FilterItemInfo("punchCardTime", minDateTime, CompareType.GREATER_EQUALS));
    //    PunchCardRecordCollection existColl = PunchCardRecordFactory.getLocalInstance(ctx).getPunchCardRecordCollection(evi);
    //    return existColl;
    //
    //}

}
