package thyyxxk.webserver.scheduled;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import thyyxxk.webserver.dao.his.reports.ClockinDao;
import thyyxxk.webserver.entity.clockin.Clockin;
import thyyxxk.webserver.utils.DateUtil;
import thyyxxk.webserver.utils.TokenUtil;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Slf4j
@Component
public class FetchClockinDataTask {
    private final ClockinDao dao;
    private static final String GET_CLOCKIN_URL = "https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckindata?access_token=ACCESS_TOKEN";
    @Value("${execute-scheduled}")
    private Boolean executeScheduled;

    @Autowired
    public FetchClockinDataTask(ClockinDao dao) {
        this.dao = dao;
    }

    @Scheduled(cron = "0 0 8 ? * *")
    public void queryClockInData() {
        if ((executeScheduled)) {
            final String yesterday = getYesterdayDate();
            Clockin param = new Clockin();
            param.setTimes(yesterday, yesterday);
            try {
                List<String> codeRsList = dao.getAllEmployeeExceptItDept();
                for (int i = 0; i < codeRsList.size(); i += 30) {
                    int index = Math.min(i + 30, codeRsList.size());
                    List<String> useridlist = codeRsList.subList(i, index);
                    param.setUseridlist(useridlist);
                    log.info("getting... " + yesterday + " - " + useridlist);
                    getSignInfo(param);
                }
                codeRsList.clear();
                codeRsList = dao.getAllEmployeeInItDept();
                param.setFlag(true);
                param.setUseridlist(codeRsList);
                log.info("getting... " + yesterday + " - " + codeRsList.toString());
                getSignInfo(param);
                log.info("over.");
            } catch (Exception e) {
                log.error("获取clock-in数据出错", e);
            }
        }
    }

    private String getYesterdayDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR,-1);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return df.format(calendar.getTime());
    }

    private void getSignInfo(Clockin param) throws ParseException {
        String requestUrl= GET_CLOCKIN_URL.replace("ACCESS_TOKEN", TokenUtil.getWeComClockInToken());
        JSONObject postStr = new JSONObject();
        postStr.put("opencheckindatatype", 3);
        postStr.put("starttime", DateUtil.getTimestamp(param.getStarttime() + " 00:01:00") / 1000);
        postStr.put("endtime", DateUtil.getTimestamp(param.getEndtime() + " 23:59:00") / 1000);
        postStr.put("useridlist", param.getUseridlist());

        RestTemplate restTemplate = new RestTemplate();
        String httpRes = restTemplate.postForObject(requestUrl, postStr, String.class);
        JSONObject res = JSONObject.parseObject(httpRes);

        if (res.getIntValue("errcode") == 0) {
            JSONArray data = res.getJSONArray("checkindata");
            if (null != data && !data.isEmpty()) {
                if (param.isFlag()) {
                    analyzeItDeptData(data, param.getStarttime());
                } else {
                    analyzeElseDeptData(data);
                }
            }
        }
    }

    private void analyzeElseDeptData(JSONArray data) {
        List<Clockin> list = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            Clockin item = new Clockin();
            item.setAllInfo(data.getJSONObject(i));
            list.add(item);
        }
        dao.insertIntoTable(list);
    }

    private void analyzeItDeptData(JSONArray data, String starttime) {
        List<Clockin> list = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            Clockin item = new Clockin();
            item.setAllInfoForItDept(data.getJSONObject(i), starttime);
            list.add(item);
        }
        dao.insertIntoTable(list);
    }

}
