package com.xjrsoft.module.job;

import cn.hutool.db.Db;
import cn.hutool.extra.spring.SpringUtil;
import com.google.gson.JsonArray;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.utils.DatasourceUtil;
import com.xjrsoft.module.schedule.entity.CourseReceiveMsg;
import com.xjrsoft.module.schedule.entity.JianyueData;
import com.xjrsoft.module.schedule.util.DataUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author dzx
 * @date 2024/1/25
 */
@Component
@Slf4j
public class JianyuekbScheduleTask {
    @Scheduled(cron = "0 */10 * * * ?")
    public void RefreshConnectionPool() throws SQLException, InterruptedException {
        String active = SpringUtil.getActiveProfile();
        if(!"prod".equals(active)){
            log.info("非正式环境，无法执行获取课表数据");
            return;
        }
        DataSource datasource = DatasourceUtil.getDataSource(GlobalConstant.DEFAULT_DATASOURCE_KEY);
        Db use = Db.use(datasource);
        String sql = "SELECT * FROM course_receive_msg WHERE delete_mark = 0 AND is_callback IS NULL";
        List<CourseReceiveMsg> receiveMsgs = use.query(sql, CourseReceiveMsg.class);
        for (CourseReceiveMsg receiveMsg : receiveMsgs) {
            String updSql = "update course_receive_msg set is_callback = 0 where id = " + receiveMsg.getId();
            use.execute(updSql, new HashMap<>());

            doExecute(use, receiveMsg.getEduYearSerialNo(), receiveMsg.getStartDate(), receiveMsg.getEndDate());

            updSql = "update course_receive_msg set is_callback = 1 where id = " + receiveMsg.getId();
            use.execute(updSql, new HashMap<>());
        }
    }

    void doExecute(Db use, String eduYearSerialNo, String startDate, String endDate){
        log.info("开始获取课表数据");
        try {
            String sql = "SELECT distinct table_name FROM jianyue_data WHERE 1 = 1";
            List<JianyueData> query = use.query(sql, JianyueData.class);
            Set<String> tables = new HashSet<>();
            for (JianyueData jianyueData : query) {
                tables.add(jianyueData.getTableName());
            }
            sql = "SELECT * FROM jianyue_data WHERE 0 = 0";
            List<JianyueData> list = use.query(sql, JianyueData.class);
            Map<String, Map<String, Long>> dataMap = new HashMap<>();
            for (String table : tables) {
                Map<String, Long> tableData = new HashMap<>();
                for (JianyueData jianyueData : list) {
                    if(!table.equals(jianyueData.getTableName())){
                        continue;
                    }
                    tableData.put(jianyueData.getJianyueId(), jianyueData.getSourceId());
                }
                dataMap.put(table, tableData);
            }
            DataUtil dataUtil = new DataUtil();
            //获取年级
            String tableName = "base_grade";
//            Map<String, Long> gradeMap = dataMap.get(tableName);
            //获取学期
            tableName = "base_semester";
            Map<String, Long> semesterMap = dataMap.get(tableName);
            //获取课程
            tableName = "base_course_subject";
            Map<String, Long> courseMap = dataMap.get(tableName);
            //获取教职工
            tableName = "base_teacher";
            Map<String, Long> teacherMap = dataMap.get(tableName);
            //获取行政班
            tableName = "base_class";
            Map<String, Long> classMap = dataMap.get(tableName);

            tableName = "base_classroom";
            Map<String, Long> classroomMap = dataMap.get(tableName);

            //获取课表并存到数据库
            JsonArray scheduleInfo = dataUtil.getScheduleInfoByGrade(eduYearSerialNo, startDate, endDate);
            dataUtil.insertCourseTable(use, scheduleInfo, classroomMap, courseMap, semesterMap, teacherMap, classMap);
            dataUtil.insertClassTime(use, scheduleInfo);
            log.info("课表数据获取完成");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}
