package com.bonus.boot.manager.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bonus.boot.manager.basic.controller.AESCBCUtils;
import com.bonus.boot.manager.manager.controller.HttpClientUtils;
import com.bonus.boot.manager.manager.controller.UserController;
import com.bonus.boot.manager.manager.dao.UserDao;
import com.bonus.boot.manager.manager.entity.AddressConfiguration;
import com.bonus.boot.manager.manager.entity.UnifyBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
 * @author 19814
 */
@Configuration
@EnableScheduling
@Slf4j

public class UnifyTask {

    @Resource
    private UserDao userDao;

//    @Scheduled(fixedRate = 1000*60*60*24)  //每隔24小时// 执行一次

    @Scheduled(fixedRate = 1000*60*60)
    @Async
    public void sendUnifyMsg() throws Exception {
        log.info("--------定时统一登录日志数据扫描器启动------");
        SimpleDateFormat df = new SimpleDateFormat("HH");
        String curhour = df.format(new Date());
        //获取当前日期的前一天
        LocalDate localDate = LocalDate.now().minusDays(1);
        //查询某日登录日志数据
        List<UnifyBean> list = userDao.getLogininfor(localDate.toString());
        if (list.size() > 0) {
            //获取登录的token
            String token = UserController.login();
            // 每组的大小
            int groupSize = 20;
            // 总的分组数
            int totalGroups = (int) Math.ceil((double) list.size() / groupSize);
            // 遍历分组
            for (int i = 0; i < totalGroups; i++) {
                // 计算当前分组元素的起始索引
                int fromIndex = i * groupSize;
                // 计算当前分组元素的结束索引，确保不超过总元素数
                int toIndex = Math.min((i + 1) * groupSize, list.size());
                // 根据索引范围获取当前分组的元素，并调用接口处理分组数据
                List<UnifyBean> group = list.subList(fromIndex, toIndex);
                putLoginLog(group,token);
            }
        } else {
            log.info(localDate.toString() + "日无登录日志数据");
        }
    }

    private void putLoginLog(List<UnifyBean> list, String token) throws Exception {
        String s = JSON.toJSONString(list);
        String encrypt = AESCBCUtils.encrypt(s, AESCBCUtils.sKey);
        String params = "{'params':'" + encrypt + "'}";
        JSONObject object = JSON.parseObject(params);
        String result = HttpClientUtils.doHttpPost(AddressConfiguration.UNIFICATION_URL + "/ynuw/sys/api/putLoginLog", object, token);
        log.info("登录日志数据="+result);
    }


    @Scheduled(fixedRate = 1000*60*60)
    @Async
    public void sendUnifyMsgs() throws Exception {
        log.info("--------定时统一操作日志数据扫描器启动------");
        //获取当前日期的前一天
//        LocalDate localDate = LocalDate.now().minusDays(1);
        LocalDate localDate = LocalDate.now();
        //查询某日登录日志数据
        List<UnifyBean> list = userDao.getLogs(localDate.toString());
        if (list.size() > 0) {
            //获取登录的token
            String token = UserController.login();
            // 每组的大小
            int groupSize = 20;
            // 总的分组数
            int totalGroups = (int) Math.ceil((double) list.size() / groupSize);
            // 遍历分组
            for (int i = 0; i < totalGroups; i++) {
                // 计算当前分组元素的起始索引
                int fromIndex = i * groupSize;
                // 计算当前分组元素的结束索引，确保不超过总元素数
                int toIndex = Math.min((i + 1) * groupSize, list.size());
                // 根据索引范围获取当前分组的元素，并调用接口处理分组数据
                List<UnifyBean> group = list.subList(fromIndex, toIndex);

                putOperaLog(group,token);
            }
        } else {
            log.info(localDate.toString() + "日无操作日志数据");
        }
    }

    private void putOperaLog(List<UnifyBean> list, String token) throws Exception {
        String s = JSON.toJSONString(list);
        String encrypt = AESCBCUtils.encrypt(s, AESCBCUtils.sKey);
        String params = "{'params':'" + encrypt + "'}";
        JSONObject object = JSON.parseObject(params);
        String result = HttpClientUtils.doHttpPost(AddressConfiguration.UNIFICATION_URL + "/ynuw/sys/api/putOperaLog", object, token);
        log.info("操作日志数据="+result);
    }

    @Scheduled(cron = "0 0 2 * * ?")
    @PostConstruct
    @Async
    public void physicalExaminationPersonnel() throws Exception {
        log.info("--------定时统一体检人员数据扫描器启动------");
        //查询某日登录日志数据
        List<UnifyBean> list = userDao.getPhysicalExamination();
        if (!list.isEmpty()) {
            //获取登录的token
            String token = UserController.login();
            // 每组的大小
            int groupSize = 20;
            // 总的分组数
            int totalGroups = (int) Math.ceil((double) list.size() / groupSize);
            // 遍历分组
            for (int i = 0; i < totalGroups; i++) {
                // 计算当前分组元素的起始索引
                int fromIndex = i * groupSize;
                // 计算当前分组元素的结束索引，确保不超过总元素数
                int toIndex = Math.min((i + 1) * groupSize, list.size());
                // 根据索引范围获取当前分组的元素，并调用接口处理分组数据
                List<UnifyBean> group = list.subList(fromIndex, toIndex);

                physicalExaminationPush(group,token, "1");
            }
        } else {
            log.info("无体检人员数据");
        }
    }

    @Scheduled(cron = "0 0 1 * * ?")
    @PostConstruct
    @Async
    public void pushByBackOfficePersonnel() throws Exception {
        log.info("--------定时统一后台人员数据扫描器启动------");
        //查询某日登录日志数据
        List<UnifyBean> list = userDao.getPushByBackOfficePersonnel();
        if (!list.isEmpty()) {
            //获取登录的token
            String token = UserController.login();
            // 每组的大小
            int groupSize = 20;
            // 总的分组数
            int totalGroups = (int) Math.ceil((double) list.size() / groupSize);
            // 遍历分组
            for (int i = 0; i < totalGroups; i++) {
                // 计算当前分组元素的起始索引
                int fromIndex = i * groupSize;
                // 计算当前分组元素的结束索引，确保不超过总元素数
                int toIndex = Math.min((i + 1) * groupSize, list.size());
                // 根据索引范围获取当前分组的元素，并调用接口处理分组数据
                List<UnifyBean> group = list.subList(fromIndex, toIndex);

                physicalExaminationPush(group,token, "2");
            }
        } else {
            log.info("无体检人员数据");
        }
    }

    private void physicalExaminationPush(List<UnifyBean> list, String token,String auth) throws Exception {
        String s = JSON.toJSONString(list);
        String encrypt = AESCBCUtils.encrypt(s, AESCBCUtils.sKey);
        String params = "{'params':'" + encrypt + "'}";
        JSONObject object = JSON.parseObject(params);
        String result = HttpClientUtils.doHttpPost(AddressConfiguration.UNIFICATION_URL + "/ynuw/sys/api/putUser", object, token);
//        String result = HttpClientUtils.doHttpPost("http://112.29.103.165:1616/ynuw/sys/api/putUser", object, token);
//        String result = HttpClientUtils.doHttpPost("http://192.168.0.14:27018/ynuw/sys/api/putUser", object, token);
        //推送成功改推送状态
        JSONObject jsonObject = JSONObject.parseObject(result);

        String code = jsonObject.getString("code");
        System.err.println("新增code="+code);
        if(code.equals("200")){
            JSONArray data = jsonObject.getJSONArray("data");
            System.err.println("新增data="+data);
            for (int i = 0; i < data.size(); i++) {
                String phone = data.getString(i);
                for (int j = 0; j < list.size(); j++) {
                    if (phone.equals(list.get(j).getPhone())) {
                        list.get(j).setStatus(0);
                        break;
                    }
                }
            }
            if (auth.equals("1")) {
                int i = userDao.updateUserPushStatus(list);
            } else {
                int i = userDao.updateUserBackstagePushStatus(list);
            }
        }
    }

}
