package nckd.jxccl.wtc.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.utils.ObjectUtils;
import kd.bos.exception.ErrorCode;
import kd.bos.exception.KDBizException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.util.StringUtils;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import nckd.jxccl.wtc.wtabm.web.common.constant.WtcConstant;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public class SyncPunchCardHelper {

    private static HRBaseServiceHelper PUNCH_CARD_HELPER = new HRBaseServiceHelper("wtis_punchcarddata");

    /**
     * 保存打卡数据
     * @param resultArr
     */
    public static void savePunchCardData(JSONArray resultArr) {
        //批次编码
        String batchNumber = String.valueOf(System.currentTimeMillis());
        JSONArray actualArr = resultArr.stream().filter(obj -> !ObjectUtils.isEmpty(obj))
                .collect(Collectors.toCollection(JSONArray::new));
        //如果过滤后size == 0直接返回
        if(actualArr.size() == 0) {
            return;
        }
        List<DynamicObject> saveList = resultArr.stream().map((data) -> {
            return dealPunchCardData((JSONObject) data, batchNumber);
        }).collect(Collectors.toList());
        //过滤下为空的
        List<DynamicObject> actualSaveList = saveList.stream().filter(dyo -> !ObjectUtils.isEmpty(dyo)).collect(Collectors.toList());
        if(actualSaveList.size() == 0) {
            return;
        }
        PUNCH_CARD_HELPER.save((DynamicObject[])actualSaveList.toArray(new DynamicObject[0]));
        //syncCardRecord(actualArr,batchNumber);
    }

    /**
     * 处理打卡数据
     * @param data 海康威视接口返回的打卡数据明细
     * @param batchNumber 批次编码
     */
    public static DynamicObject dealPunchCardData(JSONObject data, String batchNumber) {
        DynamicObject dyo = PUNCH_CARD_HELPER.generateEmptyDynamicObject();
        dyo.set("batchnumber", batchNumber);

        String card = data.getString("cardNo");
        String id = data.getString("eventId");
        if (StringUtils.isEmpty(card)) {
            return null;
        }
        //如果存在记录直接返回
        if(checkCardIsExists(card, id)) {
            return null;
        }
        dyo.set("number", card);
        dyo.set("card", card);
        //实际打卡时间
        Long unix = data.getLong("eventTime");
        dyo.set("punchcarddate", unixToDate(unix));
        dyo.set("punchcardtime", unixToTimeStamp(unix));
        //打卡地点
        dyo.set("place", data.getString("devName"));
        //进出卡
        Integer checkType = data.getInteger("inAndOutType");
        if(1 == checkType) {
            dyo.set("accesstag", "on");
        }
        else if(0 == checkType) {
            dyo.set("accesstag", "off");
        }
        //时区
        dyo.set("timezone", 320881823238577152L);
        //打卡来源
        dyo.set("signsourcename", "海康威视");
        //打卡设备 设备编码
        dyo.set("equipment", "海康威视");
        dyo.set("equipnumber", "1020_S");
        // dataId
        dyo.set("dataid", id);

        //默认值
        dyo.set("times", 0);
        dyo.set("status", 0);

        return dyo;
    }

    /**
     * 同步打卡记录
     * @JSONArray resultArr
     * @param batchNumber
     */
    private static void syncCardRecord(JSONArray resultArr, String batchNumber) {
        try {
            long l1 = System.currentTimeMillis();
            DynamicObject[] date = getDataByBatchNumber(batchNumber);
            OperationServiceHelper.executeOperate("autosysn", "wtis_punchcarddata", date, OperateOption.create());
            long l2 = System.currentTimeMillis();
        } catch (Exception e) {
            throw new KDBizException(e, new ErrorCode("", e.getMessage()), new Object[0]);
        } catch (Throwable e1) {
            throw new KDBizException(e1, new ErrorCode("", e1.getMessage()), new Object[0]);
        }
    }

    public static DynamicObject[] getDataByBatchNumber(String batchNumber) {
        return WtcConstant.PUNCHCARDDATA_HELPER.loadDynamicObjectArray(new QFilter[]{new QFilter("batchnumber", "=", batchNumber)});
    }


    /**
     * 根据考勤卡号和海康威视返回ID判断是否存在记录
     * @param card
     * @param id
     */
    public static boolean checkCardIsExists(String card, String id) {
        QFilter filter = new QFilter("card", QCP.equals, card);
        filter.and("dataid", QCP.equals, id);
        return QueryServiceHelper.exists("wtis_punchcarddata", new QFilter[]{filter});
    }



    /**
     * 时间戳转yyyy-MM-dd
     * @param unix
     * @return
     */
    public static Date unixToDate (Long unix) {
        Date date = new Date(unix);
        return date;
    }


    /**
     * 时间戳转HH:mm:ss
     * @param unix
     * @return
     */
    public static String unixToTimeStamp (Long unix) {
        Date date = new Date(unix);
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        return sdf.format(date);
    }
}