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

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.entity.SelectorItemInfo;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.framework.CoreBaseCollection;
import com.kingdee.eas.hr.ats.*;
import com.kingdee.shr.ats.web.util.HRTimeWebUtils;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.ui.ModelMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @Description TODO
 * @Date 2024/10/29 17:51
 * @Created by 30489
 */
public class PunchCardRecordEx extends PunchCardRecord {

    public void syncZKPunchCardData(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap){
        String url = "jdbc:sqlserver://10.0.3.23:1433;databaseName=kaoqin";
        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();
            // 执行查询语句
            String query = "SELECT * as name FROM USERINFO ";
            ResultSet resultSet = statement.executeQuery(query);
            Context ctx = SHRContext.getInstance().getContext();
            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();
            // 处理查询结果
            while (resultSet.next()) {
                String personNumber = resultSet.getString("personNumber");//员工编码
                String punchCardDate = resultSet.getString("name"); //打卡时间
                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);

                Timestamp punchCardTime = HRTimeWebUtils.stringToTimestamp(punchCardDate, true);
                // 处理数据
                if (punchCardDate != null && punchCardTime != null) {
                    PunchCardRecordInfo cardInfo = new PunchCardRecordInfo();
                    // 考勤机编码
                    cardInfo.setEquipmentNum(EquNo);
                    //考勤编码
                    cardInfo.setAttendanceNum(personNumber);
                    //打卡日期
                    cardInfo.setPunchCardDate(punchDate);
                    //打卡时间
                    cardInfo.setPunchCardTime(punchCardTime);
                    // 打卡来源
                    cardInfo.setPunchCardSource(PunchCardSourceEnum.mobileRegistration);
                    // 打卡位置
                    cardInfo.setPunchCardPlace(locationDetail);
                    // 有效
                    cardInfo.setPunchCardState(PunchCardStateEnum.normal);
                    cardInfo.setSimpleName(exceptionType);
                    cardInfo.setDescription(exceptionType);

                    EquNoSet.add(EquNo);
                    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);
            //相同的数据
            PunchCardRecordCollection existColl = this.getExistedPunchCardRecordCollection(ctx, minDateTime, maxDateTime, EquNoSet, setCardId);

            for(int i = 0; i < cardColl.size(); ++i) {
                // 原始 打卡记录实体
                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", HRTimeWebUtils.dateShortToString(cardInfo.getPunchCardDate())); //checkin_time --RecDate
                jsObject.put("RecTime", HRTimeWebUtils.timestampToString(cardInfo.getPunchCardTime()).substring(11)); //checkin_time --RecDate
                //员工是否有考勤档案
                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);
                    }
                }else {
                    notExistRecords.add(jsObject);
                }
            }

            PunchCardRecordFactory.getLocalInstance(ctx).saveBatchData(cardCollFinally);
            // 关闭连接
            resultSet.close();
            statement.close();
            connection.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private PunchCardRecordCollection getExistedPunchCardRecordCollection(Context ctx, Timestamp minDateTime, Timestamp maxDateTime, Set<String> EquNoSet, 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("equipmentNum", EquNoSet, CompareType.INCLUDE));
        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;
    }

}
