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

import com.yihu.wlyy.statistics.dao.MessageDao;
import com.yihu.wlyy.statistics.etl.extract.DBExtract;
import com.yihu.wlyy.statistics.etl.storage.DBStorage;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.signfamily.Message;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.util.JsonUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2016.10.25.
 */
@Component
@Scope("prototype")
public class HealthMessageJob implements Job {
    public static String jobKey="Health_Message_JOB";
    public static String cron="0 0 17 * * ?";


    @Autowired
    private DBExtract dbExtract;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DBStorage dbStorage;

    @Transactional
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try{
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(jobKey);
            quartzJobLog.setJobName(jobKey);
            String yesterday=jobExecutionContext.getMergedJobDataMap().getString("yesterday");
            String now=jobExecutionContext.getMergedJobDataMap().getString("now");
            if(StringUtils.isEmpty(yesterday)){
                yesterday=getYesterday(-1,new Date());
            }
            if(StringUtils.isEmpty(now)){
                now=getYesterday(0,new Date());
            }
            //删除原来的数据
            String deleteSql="delete from wlyy_message where type=3 and czrq >= '"+yesterday+" 17:00:00'and czrq <= '"+now+" 17:00:00'";
            jdbcTemplate.execute(deleteSql);
            //生成新的数据
            String sql="select doctor,doctor_name from wlyy_sign_family " +
                    " where  status >0 and type='2' and expenses_status='1'  " +
                    " and expenses_time >='"+yesterday+" 17:00:00' and expenses_time<'"+now+" 17:00:00' and  (doctor_health is null or doctor_health = '')" ;
            String countSql="select count(id) from wlyy_sign_family " +
                    " where  status >0 and type='2' and expenses_status='1'  " +
                    " and expenses_time >='"+yesterday+" 17:00:00' and expenses_time<'"+now+" 17:00:00' and  (doctor_health is null or doctor_health = '')" ;
            List<SignFamily> signFamilyList=dbExtract.extractByPage(SignFamily.class,sql,countSql,true);
            Map<String,List<SignFamily>> signFamilyMap=new HashMap<String,List<SignFamily>>();
            for(int i=0;i<signFamilyList.size();i++){
                SignFamily signFamilyTemp=signFamilyList.get(i);
                if (signFamilyMap.containsKey(signFamilyTemp.getDoctor())){
                    signFamilyMap.get(signFamilyTemp.getDoctor()).add(signFamilyTemp);
                }else{
                    List<SignFamily> signFamilies=new ArrayList<>();
                    signFamilies.add(signFamilyTemp);
                    signFamilyMap.put(signFamilyTemp.getDoctor(),signFamilies);
                }
            }
            for(Map.Entry<String,List<SignFamily>> entry:signFamilyMap.entrySet()){
                 countSql="select count(id) from wlyy_sign_family " +
                        " where  status >0 and type='2' and expenses_status='1'  " +
                        "  and expenses_time<'"+now+" 17:00:00' and  (doctor_health is null or doctor_health = '') and doctor='"+entry.getKey()+"'" ;

                Integer allCount=jdbcTemplate.queryForObject(countSql,Integer.class);
                Message message=new Message();
                message.setType(3);
                message.setRead(0);
                message.setOver("0");
                message.setDel("1");
                message.setSender("system");
                message.setCzrq(new SimpleDateFormat("yyyy-MM-dd").parse(now));
                message.setState(1);
                message.setTitle("新增系统消息");
                SimpleDateFormat dateFormat=new SimpleDateFormat("MM月dd日");
                String date=  dateFormat.format(new Date());
                message.setContent(date+"新增"+entry.getValue().size()+"个签约居民待分配健管师，目前共"+allCount+"人待处理");
                message.setCode(UUID.randomUUID().toString());
                message.setReceiver(entry.getKey());
                messageDao.save(message);
            }
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent("生成"+now+"的健康管理师消息成功");
            quartzJobLog.setJobType("1");
            dbStorage.saveLog(quartzJobLog);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static String getYesterday(Integer day,Date startDate) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(startDate);
        cal.add(Calendar.DAY_OF_MONTH, day);
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return yesterday;
    }

    public static void main(String[] args) {

    }
}
