package com.foc.service;

import com.foc.dao.SoundsMaxIdDao;
import com.foc.entity.SoundInfo;
import com.foc.entity.SoundsMaxId;
import com.foc.util.StringUtils;
import lombok.extern.log4j.Log4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;
import java.util.Date;
import java.util.List;

/**
 * @Author: lisu
 * @Date: 2019/4/29 16:35
 * @Description: 安库录音服务监控任务
 */
@Log4j
public class SoundMonitorService {

    private static Reader reader;

    private static SqlSessionFactory sqlSessionFactory;

    private static SqlSession session;

    public static void init() {
        try {
            reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            session = sqlSessionFactory.openSession();
        } catch (IOException e) {
            log.error("连接数据库异常");
            e.printStackTrace();
        }
//        finally {
//            //session.close();
//        }
    }

    public static Integer test() {
        SoundsMaxIdDao soundsMaxIdDao = session.getMapper(SoundsMaxIdDao.class);
        SoundsMaxId maxId = soundsMaxIdDao.getMaxId();
        String updateTime = maxId.getUpdateDate();
        log.info("当前系统时间：" + new Date());
        //比较时间，如果相差20分钟没有执行

        List<SoundInfo> list = soundsMaxIdDao.getInfo(updateTime);
        for (SoundInfo soundInfo : list){
            //成功且没有url的
            if(soundInfo.getResult().equals("SUCCESS") && StringUtils.isEmpty(soundInfo.getDownloadUrl() )  ){
                log.info("{}" + soundInfo.toString());
                return 1;
            }
        }
            log.info("全部成功" );
            return 2;

    }

}
