package nckd.jxccl.wtc.task;

import com.alibaba.fastjson.JSON;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.param.CustomParam;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.api.JobInfo;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.schedule.executor.JobClient;
import kd.bos.schedule.server.ScheduleService;
import kd.bos.servicehelper.parameter.SystemParamServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.wtc.utils.SyncPunchCardHelper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import nckd.jxccl.wtc.wtabm.web.common.constant.WtcConstant;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * 后台任务插件
 */
public class SyncPunchCardTask extends AbstractTask implements Plugin {
    private static final String ARTEMIS_PATH = "/artemis";
    static final String getCamsApi = ARTEMIS_PATH + "/api/acs/v2/door/events";
    static Map<String, String> path = new HashMap<String, String>(2) {
        {
            put("https://", getCamsApi);
        }
    };
    private static final Log LOGGER = LogFactory.getLog(SyncPunchCardTask.class);
    public void initConfig() {
        CustomParam customParam = new CustomParam();
        customParam.getSearchKeySet().add("PUNCH_CARD_HOST");
        customParam.getSearchKeySet().add("PUNCH_CARD_APP_KEY");
        customParam.getSearchKeySet().add("PUNCH_CARD_APP_SECRET");
        Map<String, String> cusTomMap = SystemParamServiceHelper.loadCustomParameterFromCache(customParam);
        ArtemisConfig.host  = cusTomMap.get("PUNCH_CARD_HOST");
        ArtemisConfig.appKey = cusTomMap.get("PUNCH_CARD_APP_KEY");
        ArtemisConfig.appSecret = cusTomMap.get("PUNCH_CARD_APP_SECRET");
    }

    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        try {
            initConfig();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar date = Calendar.getInstance();
            System.out.println(sdf.format(date.getTime()));
            String endTime = sdf.format(date.getTime()) + "T23:59:59+08:00";
            Integer days = Integer.valueOf(map.get("days").toString());
            date.set(Calendar.DATE, date.get(Calendar.DATE) - days);
            System.out.println(sdf.format(date.getTime()));
            String startTime = sdf.format(date.getTime()) + "T00:00:00+08:00";
            getAllCards(startTime, endTime);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            doSyncJob();
        }
    }

    public void doSyncJob() {
        DynamicObject dynamicJob = WtcConstant.JOB_HELPER.loadOne("id", new QFilter("number", "=", "wtis_syncPunchCardData_SKDJ_S"));
        if (dynamicJob != null) {
            JobInfo jobInfo = ScheduleService.getInstance().getObjectFactory().getJobDao().get(String.valueOf(dynamicJob.getPkValue()));
            if (jobInfo.isEnable()) {
                DynamicObject task = WtcConstant.TASK_HELPER.queryOriginalOne("id", new QFilter[]{new QFilter("job.id", "=", dynamicJob.getPkValue()), new QFilter("status", "=", "SCHEDULED")});
                if (task == null) {
                    try {
                        JobClient.dispatch(jobInfo);
                        if (LOGGER.isDebugEnabled()) {
                            LOGGER.debug("原始卡同步任务启动成功！");
                        }
                    } catch (Exception var6) {
                        LOGGER.warn("原始卡同步任务启动失败！", var6);
                    }
                }
            }
        }
    }

    public static void getAllCards(String startTime, String endTime) {
        JSONObject firstPageJson = getOnePageCard(startTime, endTime, 1);
        JSONArray firstPageListJson = firstPageJson.getJSONArray("list");
        // 保存第一页
        SyncPunchCardHelper.savePunchCardData(firstPageListJson);
        Integer totalPage = firstPageJson.getInteger("totalPage");
        if (totalPage <= 1) {
            return;
        }
        // 从第二页开始保存
        for(int i=2; i<=totalPage; i++) {
            JSONObject pageJson = getOnePageCard(startTime, endTime, i);
            JSONArray pageListJson = pageJson.getJSONArray("list");
            SyncPunchCardHelper.savePunchCardData(pageListJson);
        }
    }

    public static JSONObject getOnePageCard(String startTime, String endTime, int pageNo) {
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("pageNo", pageNo);
        jsonBody.put("pageSize", 1000);
        jsonBody.put("startTime", startTime);
        jsonBody.put("endTime", endTime);
        jsonBody.put("userId", "admin");
        String body = jsonBody.toString();
        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json", null);
        JSONObject jsonData = JSON.parseObject(result).getJSONObject("data");
        return jsonData;
    }

}