package com.xjrsoft.module.job;

import cn.hutool.db.Db;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.utils.DatasourceUtil;
import com.xjrsoft.common.utils.DateUtils;
import com.xjrsoft.module.evaluate.entity.EvaluateManage;
import com.xjrsoft.module.evaluate.mapper.EvaluateManageMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.Date;
import java.util.List;

/**
 * 自动生成评价提交记录
 */
@Component
@Slf4j
public class EvaluateTask {

    /**
     * 需要重复评价的，每天凌晨1点自动生成新的评价提交记录
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void addSubmitRecord() {
        System.out.printf("定时新增评价提交记录：%s", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
        DataSource datasource = DatasourceUtil.getDataSource(GlobalConstant.DEFAULT_DATASOURCE_KEY);
        try {
            Db use = Db.use(datasource);
            //先查出所有进行中的需要重复评价的评价管理
            String listEvaluateManageSql = "select t.id, t.create_frequency from evaluate_manage t where t.is_auto_create = 1 and t.status = 1";
            List<EvaluateManage> evaluateManageList = use.query(listEvaluateManageSql, EvaluateManage.class);
            for(EvaluateManage evaluateManage : evaluateManageList){
                //TODO 根据评价的频率进行新增

                //默认每天新增根据评价管理id
                String insertSubmitScoreSql = "insert into evaluate_submit_record (id, evaluate_manage_id, evaluate_executer_id, create_date, evaluated_object, evaluated_object_id, status)" +
                        "            (SELECT" +
                        "                 UUID()," +
                        "                 t.evaluate_manage_id," +
                        "                 t.id," +
                        "                 NOW()," +
                        "                 if(t2.evaluate_type='dm_evaluate_class', 'class', 'teacher')," +
                        "                 t.evaluate_object_id," +
                        "                 0" +
                        "             FROM evaluate_executer t" +
                        "                      LEFT JOIN evaluate_manage t1 ON (t1.id = t.evaluate_manage_id)" +
                        "                      LEFT JOIN evaluate_template t2 ON (t2.id = t1.evaluate_template_id)" +
                        "             WHERE t.delete_mark = 0" +
                        "          AND t.evaluate_manage_id = " + evaluateManage.getId() + ")";
                use.execute(insertSubmitScoreSql);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), "定时新增评价提交记录");
        }
    }
}
