package com.yihu.figure.job;

import com.yihu.figure.dao.health.HealthIndexDao;
import com.yihu.figure.dao.health.HealthIndexStatisticsDao;
import com.yihu.figure.model.health.HealthIndex;
import com.yihu.figure.model.health.HealthIndexStatistics;
import com.yihu.figure.util.DateUtil;
import com.yihu.figure.util.ETLConstantData;
import com.yihu.figure.util.IdCardUtil;
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.web.context.support.SpringBeanAutowiringSupport;

import javax.transaction.Transactional;
import java.text.DecimalFormat;
import java.util.*;


/**
 * Created by ysj
 */
@Component
@Scope("prototype")
public class HealthJob implements Job {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    private HealthIndexDao healthIndexDao;
    @Autowired
    private HealthIndexStatisticsDao healthIndexStatisticsDao;
    private DecimalFormat df = new DecimalFormat("#.0");

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
        System.out.print("health static start...");

        //生成体征数据并统计(只生成test1 高血压示例和test2 糖尿病示例)
        staticsHealth();

        System.out.print("health static over.");
    }

    /**
     * 生成体征数据并统计(只生成test1 高血压示例和test2 糖尿病示例)
     */
    @Transactional
    public void staticsHealth()
    {
        try{
            String[] patient = {"test1","test2"};
//            String[] patient = {"915d1169-5b1d-11e6-8344-fa163e8aee56"};
            List<HealthIndex> healthIndexList = new ArrayList<>();
            for(int i=0;i<patient.length;i++){
                String user = patient[i];
                String sql = "select code,idcard,ssc  from wlyy_patient_info where code = '"+user+"'";
                List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
                if(list!=null&&list.size()>0){
                    Map<String,Object> map = list.get(0);
                    String idcard = map.get("idcard").toString();

                    int age = IdCardUtil.getAgeForIdcard(idcard);
                    String sex = IdCardUtil.getSexForIdcard(idcard);//1女 2男 3未知
                    xuetang(user,null,idcard,healthIndexList);
                    xueya(user,null,idcard,age,sex,healthIndexList);
                    healthIndexDao.save(healthIndexList);
                    //统计
                    statisticsXT(user);
                    statisticsXY(user);
                }
            }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 统计血压
     * @param patient
     * @param type 健康指标类型（1血糖，2血压）
//     * @param bloodType 测试类型（8舒张压，9收缩压，10心率）
     * @param timeType 时间类型（1近1个月，2近半年，3近1年）
     * @param list
     * @param statisticsList
     */
    private void statisticsXY(String patient,Integer type, Integer timeType,List<HealthIndex> list,List<HealthIndexStatistics> statisticsList){
        int high1=0,low1=0,normal1=0;//舒张压
        int high2=0,low2=0,normal2=0;//收缩压
        int high3=0,low3=0,normal3=0;//心率
        for (HealthIndex healthIndex:list){
            //统计数据
            Double value1 = Double.parseDouble(healthIndex.getValue1());
            Double value2 = Double.parseDouble(healthIndex.getValue2());
            Double value3 = Double.parseDouble(healthIndex.getValue3());
            int flag1 = ETLConstantData.ssy(value1);
            int flag2 = ETLConstantData.szy(value2);
            int flag3 = ETLConstantData.heartRate(value3);
            if(flag1>0){
                high1 ++;
            }else if(flag1<0){
                low1 ++;
            }else {
                //正常
                normal1 ++;
            }
            if(flag2>0){
                high2 ++;
            }else if(flag2<0){
                low2 ++;
            }else {
                //正常
                normal2 ++;
            }
            if(flag3>0){
                high3 ++;
            }else if(flag3<0){
                low3 ++;
            }else {
                //正常
                normal3 ++;
            }
        }
        HealthIndexStatistics healthIndexStatistics1 = new HealthIndexStatistics(patient,high1,normal1,low1,type,8,timeType,new Date());
        HealthIndexStatistics healthIndexStatistics2 = new HealthIndexStatistics(patient,high2,normal2,low2,type,9,timeType,new Date());
        HealthIndexStatistics healthIndexStatistics3 = new HealthIndexStatistics(patient,high3,normal3,low3,type,10,timeType,new Date());
        statisticsList.add(healthIndexStatistics1);
        statisticsList.add(healthIndexStatistics2);
        statisticsList.add(healthIndexStatistics3);
    }

    /**
     * 统计血压
     * @param patient
     * @param timeType  时间类型（1近1个月，2近半年，3近1年）
     * @param startTime
     * @param endTime
     * @param statisticsList
     */
    private void statisticsXY(String patient,Integer timeType,Date startTime,Date endTime,List<HealthIndexStatistics> statisticsList){
        List<HealthIndex> list = healthIndexDao.findByUserAndRecordDate(patient,2,startTime,endTime);
        statisticsXY(patient,2,timeType,list,statisticsList);
    }

    /**
     * 统计血压
     * @param patient
     */
    private void statisticsXY(String patient){
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR,-29);
        String startMonth = DateUtil.dateToStrShort(cal.getTime())+" 00:00:00";
        cal.add(Calendar.DAY_OF_YEAR,-(182-30));
        String startHalfYear = DateUtil.dateToStrShort(cal.getTime())+" 00:00:00";
        cal.add(Calendar.DAY_OF_YEAR,-(365-182));
        String startYear = DateUtil.dateToStrShort(cal.getTime())+" 00:00:00";
        String endTime = DateUtil.getStringDateShort() + " 23:59:59";
        Date start1 = DateUtil.strToDate(startMonth);
        Date start2 = DateUtil.strToDate(startHalfYear);
        Date start3 = DateUtil.strToDate(startYear);
        Date end = DateUtil.strToDate(endTime);

        List<HealthIndexStatistics> statisticsList = new ArrayList<>();
        statisticsXY(patient,1,start1,end,statisticsList);
        statisticsXY(patient,2,start2,end,statisticsList);
        statisticsXY(patient,3,start3,end,statisticsList);
        healthIndexStatisticsDao.save(statisticsList);
    }

    /**
     * 统计血糖
     * @param patient
     * @param type 健康指标类型（1血糖，2血压）
     * @param bloodType 测试类型（1空腹血糖 2早餐后血糖 3午餐前血糖 4午餐后血糖 5晚餐前血糖 6晚餐后血糖 7睡前血糖）
     * @param timeType 时间类型（1近1个月，2近半年，3近1年）
     * @param list
     * @param statisticsList
     */
    private void statisticsXT(String patient,Integer type, Integer bloodType, Integer timeType,List<HealthIndex> list,List<HealthIndexStatistics> statisticsList){
        int high=0,low=0,normal=0;
        for (HealthIndex healthIndex:list){
            //统计数据
            Double value = Double.parseDouble(healthIndex.getValue1());
            int flag = 0;
            if(type%2==1){
                flag = ETLConstantData.xueTangBefore(value);
            }else{
                flag = ETLConstantData.xueTangAfter(value);
            }
            if(flag>0){
                high ++;
            }else if(flag<0){
                low ++;
            }else {
                //正常
                normal ++;
            }
        }
        HealthIndexStatistics healthIndexStatistics = new HealthIndexStatistics(patient,high,normal,low,type,bloodType,timeType,new Date());
        statisticsList.add(healthIndexStatistics);
    }

    /**
     * 统计血糖
     * @param patient
     * @param timeType  时间类型（1近1个月，2近半年，3近1年）
     * @param startTime
     * @param endTime
     * @param statisticsList
     */
    private void statisticsXT(String patient,Integer timeType,Date startTime,Date endTime,List<HealthIndexStatistics> statisticsList){
        List<HealthIndex> list = healthIndexDao.findByUserAndRecordDate(patient,1,startTime,endTime);
        List<HealthIndex> list1 = new ArrayList<>();
        List<HealthIndex> list2 = new ArrayList<>();
        List<HealthIndex> list3 = new ArrayList<>();
        List<HealthIndex> list4 = new ArrayList<>();
        List<HealthIndex> list5 = new ArrayList<>();
        List<HealthIndex> list6 = new ArrayList<>();
        List<HealthIndex> list7 = new ArrayList<>();
        for (HealthIndex healthIndex:list){
            String value2 = healthIndex.getValue2();
            if("1".equals(value2)){
                list1.add(healthIndex);
            }else if("2".equals(value2)){
                list2.add(healthIndex);
            }else if("3".equals(value2)){
                list3.add(healthIndex);
            }else if("4".equals(value2)){
                list4.add(healthIndex);
            }else if("5".equals(value2)){
                list5.add(healthIndex);
            }else if("6".equals(value2)){
                list6.add(healthIndex);
            }else if("7".equals(value2)){
                list7.add(healthIndex);
            }
        }
        statisticsXT(patient,1,1,timeType,list1,statisticsList);
        statisticsXT(patient,1,2,timeType,list2,statisticsList);
        statisticsXT(patient,1,3,timeType,list3,statisticsList);
        statisticsXT(patient,1,4,timeType,list4,statisticsList);
        statisticsXT(patient,1,5,timeType,list5,statisticsList);
        statisticsXT(patient,1,6,timeType,list6,statisticsList);
        statisticsXT(patient,1,7,timeType,list7,statisticsList);
    }

    /**
     * 统计血糖
     * @param patient
     */
    private void statisticsXT(String patient){
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR,-29);
        String startMonth = DateUtil.dateToStrShort(cal.getTime())+" 00:00:00";
        cal.add(Calendar.DAY_OF_YEAR,-(182-30));
        String startHalfYear = DateUtil.dateToStrShort(cal.getTime())+" 00:00:00";
        cal.add(Calendar.DAY_OF_YEAR,-(365-182));
        String startYear = DateUtil.dateToStrShort(cal.getTime())+" 00:00:00";
        String endTime = DateUtil.getStringDateShort() + " 23:59:59";
        Date start1 = DateUtil.strToDate(startMonth);
        Date start2 = DateUtil.strToDate(startHalfYear);
        Date start3 = DateUtil.strToDate(startYear);
        Date end = DateUtil.strToDate(endTime);

        List<HealthIndexStatistics> statisticsList = new ArrayList<>();
        statisticsXT(patient,1,start1,end,statisticsList);
        statisticsXT(patient,2,start2,end,statisticsList);
        statisticsXT(patient,3,start3,end,statisticsList);
        healthIndexStatisticsDao.save(statisticsList);
    }

    private double random2ten(Random random){
        int i = random.nextInt(20);
        return i==0?0:i/10.0;
    }

    private double random3ten(Random random){
        int i = random.nextInt(30);
        return i==0?0:i/10.0;
    }

    /**
     * 血糖
     * @param patient
     * @param deviceSn
     * @param idcard
     */
    private List<HealthIndex> xuetang(String patient, String deviceSn, String idcard, List<HealthIndex> list){
        String startTime = DateUtil.getStringDateShort()+" 00:00:00";
        String endTime = DateUtil.getStringDateShort()+" 23:59:59";
        HealthIndex healthIndex = healthIndexDao.findByPatientAndType(patient,"1",startTime,endTime);
        if(healthIndex!=null){//判断是否已经生成过数据
            return list;
        }
        double value1,value2,value3,value4,value5,value6,value7;

        //value2 1空腹血糖 2早餐后血糖 3午餐前血糖 4午餐后血糖 5晚餐前血糖 6晚餐后血糖 7睡前血糖
        //≥7.0 mmol/l或餐后血糖≥11.1 mmol/l 属于糖尿病
        HealthIndex healthIndex1 = null;
        HealthIndex healthIndex2 = null;
        HealthIndex healthIndex3 = null;
        HealthIndex healthIndex4 = null;
        HealthIndex healthIndex5 = null;
        HealthIndex healthIndex6 = null;
        HealthIndex healthIndex7 = null;

        double high = 11.1,normal=7.0,low = 4.0;//(空腹4.0-7.0为正常，餐后7.0-11.0为正常)
        Random random = new Random();
        value1 = 6.0;
        value2 = 10.0;
        value3 = 6.0;
        value4 = 10.0;
        value5 = 6.0;
        value6 = 10.0;
        value7 = 6.0;
        healthIndex1 = new HealthIndex();
        healthIndex2 = new HealthIndex();
        healthIndex3 = new HealthIndex();
        healthIndex4 = new HealthIndex();
        healthIndex5 = new HealthIndex();
        healthIndex6 = new HealthIndex();
        healthIndex7 = new HealthIndex();
        Date recordDate = new Date();

        if(random.nextInt(2)==1){
            //加
            value1 += random3ten(random);
        }else{
            //减
            value1 -= random2ten(random);
        }
        healthIndex1.setCzrq(new Date());
        healthIndex1.setDel("1");
        healthIndex1.setDeviceSn(deviceSn);
        healthIndex1.setIdcard(idcard);
        healthIndex1.setRecordDate(recordDate);
        healthIndex1.setType(1);
        healthIndex1.setUser(patient);
        healthIndex1.setValue1(df.format(value1));
        healthIndex1.setValue2("1");

        if(random.nextInt(2)==1){
            //加
            value2 += random3ten(random);
        }else{
            //减
            value2 -= random2ten(random);
        }
        healthIndex2.setCzrq(new Date());
        healthIndex2.setDel("1");
        healthIndex2.setDeviceSn(deviceSn);
        healthIndex2.setIdcard(idcard);
        healthIndex2.setRecordDate(recordDate);
        healthIndex2.setType(1);
        healthIndex2.setUser(patient);
        healthIndex2.setValue1(df.format(value2));
        healthIndex2.setValue2("2");

        if(random.nextInt(2)==1){
            //加
            value3 += random3ten(random);
        }else{
            //减
            value3 -= random2ten(random);
        }
        healthIndex3.setCzrq(new Date());
        healthIndex3.setDel("1");
        healthIndex3.setDeviceSn(deviceSn);
        healthIndex3.setIdcard(idcard);
        healthIndex3.setRecordDate(recordDate);
        healthIndex3.setType(1);
        healthIndex3.setUser(patient);
        healthIndex3.setValue1(df.format(value3));
        healthIndex3.setValue2("3");

        if(random.nextInt(2)==1){
            //加
            value4 += random3ten(random);
        }else{
            //减
            value4 -= random2ten(random);
        }
        healthIndex4.setCzrq(new Date());
        healthIndex4.setDel("1");
        healthIndex4.setDeviceSn(deviceSn);
        healthIndex4.setIdcard(idcard);
        healthIndex4.setRecordDate(recordDate);
        healthIndex4.setType(1);
        healthIndex4.setUser(patient);
        healthIndex4.setValue1(df.format(value4));
        healthIndex4.setValue2("4");

        if(random.nextInt(2)==1){
            //加
            value5 += random3ten(random);
        }else{
            //减
            value5 -= random2ten(random);
        }
        healthIndex5.setCzrq(new Date());
        healthIndex5.setDel("1");
        healthIndex5.setDeviceSn(deviceSn);
        healthIndex5.setIdcard(idcard);
        healthIndex5.setRecordDate(recordDate);
        healthIndex5.setType(1);
        healthIndex5.setUser(patient);
        healthIndex5.setValue1(df.format(value5));
        healthIndex5.setValue2("5");

        if(random.nextInt(2)==1){
            //加
            value6 += random3ten(random);
        }else{
            //减
            value6 -= random2ten(random);
        }
        healthIndex6.setCzrq(new Date());
        healthIndex6.setDel("1");
        healthIndex6.setDeviceSn(deviceSn);
        healthIndex6.setIdcard(idcard);
        healthIndex6.setRecordDate(recordDate);
        healthIndex6.setType(1);
        healthIndex6.setUser(patient);
        healthIndex6.setValue1(df.format(value6));
        healthIndex6.setValue2("6");

        if(random.nextInt(2)==1){
            //加
            value7 += random3ten(random);
        }else{
            //减
            value7 -= random2ten(random);
        }
        healthIndex7.setCzrq(new Date());
        healthIndex7.setDel("1");
        healthIndex7.setDeviceSn(deviceSn);
        healthIndex7.setIdcard(idcard);
        healthIndex7.setRecordDate(recordDate);
        healthIndex7.setType(1);
        healthIndex7.setUser(patient);
        healthIndex7.setValue1(df.format(value7));
        healthIndex7.setValue2("7");

        list.add(healthIndex1);
        list.add(healthIndex2);
        list.add(healthIndex3);
        list.add(healthIndex4);
        list.add(healthIndex5);
        list.add(healthIndex6);
        list.add(healthIndex7);
        return list;
    }

    /**
     * 血压
     * @param patient
     * @param deviceSn
     * @param idcard
     */
    private List<HealthIndex> xueya(String patient, String deviceSn, String idcard, int age, String sex, List<HealthIndex> list){
        String startTime = DateUtil.getStringDateShort()+" 00:00:00";
        String endTime = DateUtil.getStringDateShort()+" 23:59:59";
        HealthIndex healthIndex = healthIndexDao.findByPatientAndType(patient,"2",startTime,endTime);
        if(healthIndex!=null){//判断是否已经生成过数据
            return list;
        }

        int value1,value2,value3,value4,intValue1,intValue2;
        //140/90mmHg至160/95mmHg之间，不能确定为高血压
        //成年人收缩压90-139.舒张压60-89为正常
        Random random = new Random();
        int month = 30;//一个月取30天
        int halfYear = 182;//半年取182天
        age = age>65?65:age;
        if("2".equals(sex)){
            intValue1 = 82+age;
            if(random.nextInt(2)==0){
                intValue2 = 84+random.nextInt(3);
            }else{
                intValue2 = 84-random.nextInt(3);
            }
        }else{
            intValue1 = 80+age;
            if(random.nextInt(2)==0){
                intValue2 = 81+random.nextInt(3);
            }else{
                intValue2 = 81-random.nextInt(3);
            }
        }

        value1 = intValue1;//收缩压
        value2 = intValue2;//舒张压
        healthIndex = new HealthIndex();
        Date recordDate = new Date();

        int temp = random.nextInt(10);
        if(temp<5){
            value1 += random.nextInt(21);
            value2 += random.nextInt(6);
        }else if(temp>7){
            value1 += 40+ random.nextInt(10);
            value2 += 15 + random.nextInt(5);
        }else{
            value1 += 20+ random.nextInt(21);
            value2 += 10 + random.nextInt(6);
        }

        value3 = random.nextInt(2)==1?(value2+random.nextInt(9)):(value2-random.nextInt(9));//心率
        value4 = random.nextInt(100)>96?1:0;//心率是否不齐

        healthIndex.setCzrq(new Date());
        healthIndex.setDel("1");
        healthIndex.setDeviceSn(deviceSn);
        healthIndex.setIdcard(idcard);
        healthIndex.setRecordDate(recordDate);
        healthIndex.setType(2);
        healthIndex.setUser(patient);
        healthIndex.setValue1(String.valueOf(value1));
        healthIndex.setValue2(String.valueOf(value2));
        healthIndex.setValue3(String.valueOf(value3));
        healthIndex.setValue4(String.valueOf(value4));
        list.add(healthIndex);

        return list;
    }
}
