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.task.PushMsgTask;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
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.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 8 * * ?";

    @Value("${systemConfig.msg_push_server}")
    private String url;
    @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+" 00:00:00'and czrq <= '"+now+" 00:00:00'";
            jdbcTemplate.execute(deleteSql);
            //生成新的数据
            String sql="select admin_team_code  from wlyy_sign_family " +
                    " where  status >0 and type='2' " +
                    " and apply_date >='"+yesterday+" 00:00:00' and apply_date<'"+now+" 00: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 apply_date >='"+yesterday+" 00:00:00' and apply_date<'"+now+" 00:00:00' and  (doctor_health is null or doctor_health = '')" ;
            List<SignFamily> signFamilyList=dbExtract.extractByPage(SignFamily.class,sql,countSql,true);
            Map<Long,List<SignFamily>> signFamilyMap=new HashMap<Long,List<SignFamily>>();
            for(int i=0;i<signFamilyList.size();i++){
                SignFamily signFamilyTemp=signFamilyList.get(i);
                if (signFamilyMap.containsKey(signFamilyTemp.getAdminTeamCode())){
                    signFamilyMap.get(signFamilyTemp.getAdminTeamCode()).add(signFamilyTemp);
                }else{
                    List<SignFamily> signFamilies=new ArrayList<>();
                    signFamilies.add(signFamilyTemp);
                    signFamilyMap.put(signFamilyTemp.getAdminTeamCode(),signFamilies);
                }
            }
            JSONArray jsonArray=new JSONArray();
            for(Map.Entry<Long,List<SignFamily>> entry:signFamilyMap.entrySet()){
                //得到未分配的所有数目
                 countSql="select count(id) from wlyy_sign_family " +
                        " where  status >0 and type='2'  " +
                        "  and apply_date<'"+now+" 00:00:00' and  (doctor_health is null or doctor_health = '') and admin_team_code="+entry.getKey()+"" ;
                Integer allCount=jdbcTemplate.queryForObject(countSql,Integer.class);
                //得到团队的leader
               sql="select leader_code from wlyy_admin_team m where m.id= ?";
                String teamLeader=jdbcTemplate.queryForObject(sql,String.class,entry.getKey());
                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 HH:mm:ss").parse(yesterday+" 23:59:00"));
                message.setState(1);
                String title="新增系统消息";
                message.setTitle(title);
                SimpleDateFormat dateFormat1=new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat dateFormat2=new SimpleDateFormat("MM月dd日");
                String content=dateFormat2.format(dateFormat1.parse(yesterday))+"新增"+entry.getValue().size()+"个签约居民待分配健管师，目前共"+allCount+"人待处理";
                message.setContent(content);
                message.setCode(UUID.randomUUID().toString());
                message.setReceiver(teamLeader);
                messageDao.save(message);


                // 异常通知
                JSONObject json = new JSONObject();
                json.put("receiver", teamLeader);
                json.put("type", "D_NH_01");
                json.put("title", title);
                json.put("msg", content);
                json.put("data", "");
                jsonArray.add(json);
            }
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent("生成"+yesterday+"的健康管理师消息成功");
            quartzJobLog.setJobType("1");
            dbStorage.saveLog(quartzJobLog);

            // 推送消息给医生
            PushMsgTask.url=url+"api/v1/chats/sm";
            // 推送消息给医生
            PushMsgTask.getInstance().put(jsonArray);
        }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) {

    }
}
