package com.yihu.wlyy.statistics.job.check;

import com.yihu.wlyy.statistics.etl.mycache.CachePool;
import com.yihu.wlyy.statistics.job.business.Constant;
import com.yihu.wlyy.statistics.util.DateUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.mail.Multipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by Administrator on 2016.10.31.
 * 每天的报表任务
 */
@Component
@Scope("prototype")
public class ReportAllLogJob implements Job {
    public static String jobKey="Report_All_LOG_JOB";
    public static String cron="0 55 0 * * ?";

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.from}")
    private String from;
    @Value("${spring.mail.to}")
    private String to;
    @Autowired
    private CachePool cachePool;

    @Transactional
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try{
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            String timeKey=redisTemplate.opsForValue().get("quota:timeKey");
            long produceTime=  redisTemplate.getExpire("quota:16:4:350200:"+timeKey);
            String date=getYesterday();
            //当前试试统计的key

            StringBuffer sb=new StringBuffer("<html><head><meta charset=\"UTF-8\"></head><body>");
            sb.append("<table width=\"100%\" border=\"blue solid 1px\" cellpadding=\"0\" cellspacing=\"0\" bgcolor=\"#FF9933\"  id=\"size\">\n");
            //报表时间
            sb.append("<tr><td>报表数据时间</td><td>"+date+"</td></tr>");//添加当前实时统计信息报表
            sb.append("<tr><td>报表生成时间</td><td>"+DateUtil.dateToStrLong(new Date())+"</td></tr>");//添加当前实时统计信息报表
            //今天签约信息
            String sqlCount="select count(id) from wlyy_sign_family a  where  status in(1,2) and a.type =2 and expenses_status=1 and a.expenses_time< '"+getYesterday(-1)+ Constant.quota_date_last+"' and a.expenses_time>= '"+getYesterday(-2)+ Constant.quota_date_last+"'";
            Integer count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>"+date+" 新增签约数</td><td>"+count+"个</td></tr>");
            //今天解约信息
            sqlCount=" select count(id) from wlyy_sign_family a where  a.type =2 and a.status in(-3,-4) and a.apply_unsign_date< '"+getYesterday(-1)+ Constant.quota_date_last+"' and a.apply_unsign_date>= '"+getYesterday(-2)+ Constant.quota_date_last+"'";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>"+date+" 新增解约数</td><td>"+count+"个</td></tr>");
            //今天待签约信息
            sqlCount=" select count(id) from wlyy_sign_family a where  a.type =2  and a.status=0 and  a.patient_apply_date< '"+getYesterday(-1)+ Constant.quota_date_last+"'  and  a.patient_apply_date >= '"+getYesterday(-2)+ Constant.quota_date_last+"'  ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>"+date+" 新增待签约数</td><td>"+count+"个</td></tr>");
            //今天改签信息
            sqlCount=" select count(id) from wlyy_sign_family a where  a.type =2 and a.status =100 and  a.patient_apply_date< '"+getYesterday(-1)+ Constant.quota_date_last+"' and a.expenses_status=1 ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>"+date+" 新增改签数</td><td>"+count+"个</td></tr>");
            //今天未交费数目
            sqlCount= " select count(id) from wlyy_sign_family a where  a.type =2 and status in (1,2) and  a.apply_date< '"+getYesterday(-1)+ Constant.quota_date_last+"' and  a.apply_date>= '"+getYesterday(-2)+ Constant.quota_date_last+"'and (expenses_status !=1 or expenses_status is null)  ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>"+date+" 新增未缴费数</td><td>"+count+"个</td></tr>");
            //截止到今天的签约信息
            sb.append("<tr><td>截止到"+date+" 的签约数</td><td>"+cachePool.getSignFamilysWithExpenseStatus1ByDate(date).getSignFamilies().size()+"个</td></tr>");
            //截止到今天未交费数目
            sqlCount= " select count(id) from wlyy_sign_family a where  a.type =2 and status in (1,2) and  a.apply_date< '"+getYesterday(-1)+ Constant.quota_date_last+"'and (expenses_status !=1 or expenses_status is null)  ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>截止到"+date+" 的未缴费数</td><td>"+count+"个</td></tr>");
            //系统共有患者多少个
            sqlCount= " select count(id) from wlyy_patient  ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>截止到"+date+" 的患者用户数</td><td>"+count+"个</td></tr>");
            //系统共有多少个患者有签约
            sb.append("<tr><td>截止到"+date+" 签约患者数</td><td>"+cachePool.getSignFamilysWithExpenseStatus1ByDate(date).getSignFamilies().size()+"个</td></tr>");
            //系统共有多少个健康管理师
            sqlCount= " select count(id) from wlyy_doctor where level=3  ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>截止到"+date+" 系统中存在的健康管理师数</td><td>"+count+"个</td></tr>");
            //系统共有多少个全科医生
            sqlCount= " select count(id) from wlyy_doctor where level=2 ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>截止到"+date+" 系统中存在的全科医生数</td><td>"+count+"个</td></tr>");
            //系统共有多少个专科医生
            sqlCount= " select count(id) from wlyy_doctor where level=1 ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>截止到"+date+" 系统中存在的专科医生数</td><td>"+count+"个</td></tr>");
            //系统共有多少个医生行政团队
            sqlCount= " select count(id) from wlyy_admin_team where available=1 ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>截止到"+date+" 系统中存在的行政团队数</td><td>"+count+"个</td></tr>");

            //系统患者总共登录成功的次数
            sqlCount= " select count(id) from wlyy_login_log where type=1 and user_type=1 ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>截止到"+date+" 患者总共登录成功次数</td><td>"+count+"次</td></tr>");
            //系统患者总共登录失败的次数
            sqlCount= " select count(id) from wlyy_login_log where type=2 and user_type=1 ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>截止到"+date+" 患者总共登录失败次数</td><td>"+count+"次</td></tr>");
            //系统医生总共登录成功的次数
            sqlCount= " select count(id) from wlyy_login_log where type=1 and user_type=2 ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>截止到"+date+" 医生总共登录成功次数</td><td>"+count+"次</td></tr>");
            //系统医生总共登录失败的次数
            sqlCount= " select count(id) from wlyy_login_log where type=2 and user_type=2 ";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>截止到"+date+" 医生总共登录失败次数</td><td>"+count+"次</td></tr>");
            //系统患者昨天登录成功的次数
            sqlCount= " select count(id) from wlyy_login_log where type=1 and user_type=1 and  create_time<= '"+getYesterday(-1)+" 23:59:59 ' and  create_time>= '"+getYesterday(-1)+" 00:00:00 '";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>"+date+" 患者登录成功次数</td><td>"+count+"次</td></tr>");
            //系统患者昨天登录失败的次数
            sqlCount= " select count(id) from wlyy_login_log where type=2 and user_type=1 and  create_time<= '"+getYesterday(-1)+" 23:59:59 ' and  create_time>= '"+getYesterday(-1)+" 00:00:00 '";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>"+date+" 患者登录失败次数</td><td>"+count+"次</td></tr>");
            //系统医生昨天登录成功的次数
            sqlCount= " select count(id) from wlyy_login_log where type=1 and user_type=2 and  create_time<= '"+getYesterday(-1)+" 23:59:59 ' and  create_time>= '"+getYesterday(-1)+" 00:00:00 '";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>"+date+" 医生登录成功次数</td><td>"+count+"次</td></tr>");
            //系统医生昨天登录失败的次数
            sqlCount= " select count(id) from wlyy_login_log where type=2 and user_type=2 and  create_time<= '"+getYesterday(-1)+" 23:59:59 ' and  create_time>= '"+getYesterday(-1)+" 00:00:00 '";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>"+date+" 医生登录失败次数</td><td>"+count+"次</td></tr>");

            //今天实时统计执行的次数
            sqlCount= " select count(a.id) from wlyy_job_log a where a.job_id=11 and a.job_start_time>= '"+getYesterday(-1)+ " 00:00:00'and a.job_start_time<=  '"+getYesterday(-1)+" 23:59:59 '";
            count=jdbcTemplate.queryForObject(sqlCount,Integer.class);
            sb.append("<tr><td>"+date+" 实时统计执行的次数</td><td>"+count+"次</td></tr>");
            sb.append("<tr><td>最近执行的实时统计的时间:</td><td>"+DateUtil.dateToStrLong(new Date(Long.valueOf(timeKey)))+"</td></tr>");
            //最新的实时统计信息
            String current="最新的redis数据生成时间時間:"+ DateUtil.dateToStrLong(new Date(Long.valueOf(timeKey)))+"，当前系统时间:"+ DateUtil.dateToStrLong(new Date())+"，最新的key剩下多少时间:"+ (produceTime/3600)+"小时"+(produceTime%3600/60)+"分钟"+(produceTime%3600%60)+"秒";
            sb.append("<tr><td>当前实时统计信息</td><td>"+current+"</td></tr>");//添加当前实时统计信息报表


            sb.append("</table></body></html>");
            sendEmail(sb.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void sendEmail(String text) throws Exception {
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setContent(text, "text/html;charset=utf-8");
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        String[] tos=to.split(",");
        MimeMessage mimeMessage= javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        messageHelper.setSubject("实时统计报表");
        messageHelper.setFrom(from);
        mimeMessage.setContent(mp);
        messageHelper.setTo(tos);
        javaMailSender.send(mimeMessage);
    }

    public String getYesterday() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return yesterday;
    }
    public String getYesterday(int count) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, count);
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return yesterday;
    }
}
