package com.yihu.figure.service.health;

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.service.BaseService;
import com.yihu.figure.util.DateUtil;
import com.yihu.figure.util.ETLConstantData;
import com.yihu.figure.util.IdCardUtil;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

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

/**
 * 居民体征
 *
 * @author ysj add 2017-03-06
 */
@Component
@Transactional(rollbackOn = Exception.class)
public class HealthIndexService extends BaseService {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private HealthIndexDao healthIndexDao;
    @Autowired
    private HealthIndexStatisticsDao healthIndexStatisticsDao;

    private DecimalFormat df = new DecimalFormat("#.0");

    /**
     * 统计居民体征数据
     * @param patient
     */
    public void statistics(String patient){
        statisticsXT(patient);
        statisticsXY(patient);
    }

    /**
     * 获取居民体征数据
     * @param patient
     * @param type
     * @return
     */
    public JSONObject healthIndex(String patient, String type, String bloodType, String timeType) throws Exception{
        JSONObject json = new JSONObject();
        int limit = 1;
        if("1".equals(timeType)){
            limit = 30;
        }else if("2".equals(timeType)){
            limit = 182;
        }else if("3".equals(timeType)){
            limit = 365;
        }
        String sql1 = "select date_format(record_date,'%Y-%c-%d %H:%i:%s') recordDate, ";
        if("1".equals(type)){
            //血糖
            sql1 += "value1 value  " +
                   "from wlyy_health_index " +
                   "where user = '"+patient+"' " +
                   "and type="+type+" " +
                   "and value2='"+bloodType+"' " +
                   "order by record_date desc " +
                   "limit "+limit;
        }else{
            //血压
            if("8".equals(bloodType)){
                sql1 +=" value1 value ";
            }else if("9".equals(bloodType)){
                sql1 +=" value2 value ";
            }else if("10".equals(bloodType)){
                sql1 +=" value3 value ";
            }
            sql1 += "from wlyy_health_index " +
                    "where user = '"+patient+"' " +
                    "and type="+type+" " +
                    "order by record_date desc " +
                    "limit "+limit;
        }
        List<Map<String,Object>> list1 = jdbcTemplate.queryForList(sql1);

        //
        String sql2 = "select high,normal,low  " +
                "from wlyy_health_index_statistics " +
                "where user = '"+patient+"' " +
                "and time_type="+timeType+" " +
                "and blood_type='"+bloodType+"' " +
                "order by czrq desc limit 1";
        List<Map<String,Object>> list2 = jdbcTemplate.queryForList(sql2);
        Map<String,Object> map = null;
        if(list2.size()>0){
            map = list2.get(0);
        }else{
            map = new HashMap<>();
            map.put("high",0);
            map.put("normal",0);
            map.put("low",0);
        }
        json.put("healths",list1);
        json.put("statistics",map);

        return json;
    }

    /**
     * 自动生成居民一年的体征数据
     * @param patient
     */
    public void autoHealthIndex(String patient,String type) throws Exception{
        String sql = "select code,idcard,ssc  from wlyy_patient_info where code = '"+patient+"'";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        if(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未知

            // 健康指标类型（1血糖，2血压，3体重，4腰围）
            List<HealthIndex> patientHealthIndexList = new ArrayList<>();
            if(StringUtils.isEmpty(type)){
                xuetang(patient,null,idcard,patientHealthIndexList);
                xueya(patient,null,idcard,age,sex,patientHealthIndexList);
                weight(patient,null,idcard,age,sex,patientHealthIndexList);
                yaowei(patient,null,idcard,age,sex,patientHealthIndexList);
            }else if("1".equals(type)){
                xuetang(patient,null,idcard,patientHealthIndexList);
            }else if("2".equals(type)){
                xueya(patient,null,idcard,age,sex,patientHealthIndexList);
            }else if("3".equals(type)){
                weight(patient,null,idcard,age,sex,patientHealthIndexList);
            }else if("4".equals(type)){
                yaowei(patient,null,idcard,age,sex,patientHealthIndexList);
            }
            System.out.println(patientHealthIndexList.size());
            healthIndexDao.save(patientHealthIndexList);
        }
    }

    /**
     * 血糖
     * @param patient
     * @param deviceSn
     * @param idcard
     */
    public List<HealthIndex> xuetang(String patient, String deviceSn, String idcard, List<HealthIndex> list){
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR,-1);
        String startTime = DateUtil.dateToStrShort(cal.getTime())+" 00:00:00";
        String endTime = DateUtil.dateToStrShort(cal.getTime())+" 23:59:59";
        HealthIndex healthIndex = healthIndexDao.findByPatientAndType(patient,"1",startTime,endTime);
        if(healthIndex!=null){//判断是否已经生成过数据
            return list;
        }

        String fasting = "07:00:00";
        String afterBreakfast = "09:00:00";
        String beforeLunch = "11:00:00";
        String afterLunch = "13:00:00";
        String beforeDinner = "17:00:00";
        String afterDinner = "19:00:00";
        String beforeSleep = "23:00:00";
        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;

        int month = 30;//一个月取30天
        int halfYear = 182;//半年取182天
        double high = 11.1,normal=7.0,low = 4.0;//(空腹4.0-7.0为正常，餐后7.0-11.0为正常)
        int high11=0,normal11=0,low11=0,high12=0,normal12=0,low12=0,high13=0,normal13=0,low13=0;//1为近一个月，2为近半年，3为近一年
        int high21=0,normal21=0,low21=0,high22=0,normal22=0,low22=0,high23=0,normal23=0,low23=0;//1为近一个月，2为近半年，3为近一年
        int high31=0,normal31=0,low31=0,high32=0,normal32=0,low32=0,high33=0,normal33=0,low33=0;//1为近一个月，2为近半年，3为近一年
        int high41=0,normal41=0,low41=0,high42=0,normal42=0,low42=0,high43=0,normal43=0,low43=0;//1为近一个月，2为近半年，3为近一年
        int high51=0,normal51=0,low51=0,high52=0,normal52=0,low52=0,high53=0,normal53=0,low53=0;//1为近一个月，2为近半年，3为近一年
        int high61=0,normal61=0,low61=0,high62=0,normal62=0,low62=0,high63=0,normal63=0,low63=0;//1为近一个月，2为近半年，3为近一年
        int high71=0,normal71=0,low71=0,high72=0,normal72=0,low72=0,high73=0,normal73=0,low73=0;//1为近一个月，2为近半年，3为近一年
        Random random = new Random();
        List<HealthIndexStatistics> statisticsList = new ArrayList<>();
        for (int i = 0;i<365;i++){
            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 = cal.getTime();

            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");

            //统计数据
            int flag1 = ETLConstantData.xueTangBefore(value1);
            int flag2 = ETLConstantData.xueTangAfter(value2);
            int flag3 = ETLConstantData.xueTangBefore(value3);
            int flag4 = ETLConstantData.xueTangAfter(value4);
            int flag5 = ETLConstantData.xueTangBefore(value5);
            int flag6 = ETLConstantData.xueTangAfter(value6);
            int flag7 = ETLConstantData.xueTangBefore(value7);
            if(flag1>0){
                high11 += i<month?1:0;
                high12 += i<halfYear?1:0;
                high13 ++;
            }else if(flag1<0){
                low11 += i<month?1:0;
                low12 += i<halfYear?1:0;
                low13 ++;
            }else {
                //正常
                normal11 += i<month?1:0;
                normal12 += i<halfYear?1:0;
                normal13 ++;
            }
            if(flag2>0){
                high21 += i<month?1:0;
                high22 += i<halfYear?1:0;
                high23 ++;
            }else if(flag2<0){
                low21 += i<month?1:0;
                low22 += i<halfYear?1:0;
                low23 ++;
            }else {
                //正常
                normal21 += i<month?1:0;
                normal22 += i<halfYear?1:0;
                normal23 ++;
            }
            if(flag3>0){
                high31 += i<month?1:0;
                high32 += i<halfYear?1:0;
                high33 ++;
            }else if(flag3<0){
                low31 += i<month?1:0;
                low32 += i<halfYear?1:0;
                low33 ++;
            }else {
                //正常
                normal31 += i<month?1:0;
                normal32 += i<halfYear?1:0;
                normal33 ++;
            }
            if(flag4>0){
                high41 += i<month?1:0;
                high42 += i<halfYear?1:0;
                high43 ++;
            }else if(flag4<0){
                low41 += i<month?1:0;
                low42 += i<halfYear?1:0;
                low43 ++;
            }else {
                //正常
                normal41 += i<month?1:0;
                normal42 += i<halfYear?1:0;
                normal43 ++;
            }
            if(flag5>0){
                high51 += i<month?1:0;
                high52 += i<halfYear?1:0;
                high53 ++;
            }else if(flag5<0){
                low51 += i<month?1:0;
                low52 += i<halfYear?1:0;
                low53 ++;
            }else {
                //正常
                normal51 += i<month?1:0;
                normal52 += i<halfYear?1:0;
                normal53 ++;
            }
            if(flag6>0){
                high61 += i<month?1:0;
                high62 += i<halfYear?1:0;
                high63 ++;
            }else if(flag6<0){
                low61 += i<month?1:0;
                low62 += i<halfYear?1:0;
                low63 ++;
            }else {
                //正常
                normal61 += i<month?1:0;
                normal62 += i<halfYear?1:0;
                normal63 ++;
            }
            if(flag7>0){
                high71 += i<month?1:0;
                high72 += i<halfYear?1:0;
                high73 ++;
            }else if(flag7<0){
                low71 += i<month?1:0;
                low72 += i<halfYear?1:0;
                low73 ++;
            }else {
                //正常
                normal71 += i<month?1:0;
                normal72 += i<halfYear?1:0;
                normal73 ++;
            }
            if(i==29){
                HealthIndexStatistics healthIndexStatistics1 = new HealthIndexStatistics(patient,high11,normal11,low11,1,1,1,new Date());
                HealthIndexStatistics healthIndexStatistics2 = new HealthIndexStatistics(patient,high21,normal21,low21,1,2,1,new Date());
                HealthIndexStatistics healthIndexStatistics3 = new HealthIndexStatistics(patient,high31,normal31,low31,1,3,1,new Date());
                HealthIndexStatistics healthIndexStatistics4 = new HealthIndexStatistics(patient,high41,normal41,low41,1,4,1,new Date());
                HealthIndexStatistics healthIndexStatistics5 = new HealthIndexStatistics(patient,high51,normal51,low51,1,5,1,new Date());
                HealthIndexStatistics healthIndexStatistics6 = new HealthIndexStatistics(patient,high61,normal61,low61,1,6,1,new Date());
                HealthIndexStatistics healthIndexStatistics7 = new HealthIndexStatistics(patient,high71,normal71,low71,1,7,1,new Date());
                statisticsList.add(healthIndexStatistics1);
                statisticsList.add(healthIndexStatistics2);
                statisticsList.add(healthIndexStatistics3);
                statisticsList.add(healthIndexStatistics4);
                statisticsList.add(healthIndexStatistics5);
                statisticsList.add(healthIndexStatistics6);
                statisticsList.add(healthIndexStatistics7);
            }
            if(i==181){
                HealthIndexStatistics healthIndexStatistics1 = new HealthIndexStatistics(patient,high12,normal12,low12,1,1,2,new Date());
                HealthIndexStatistics healthIndexStatistics2 = new HealthIndexStatistics(patient,high22,normal22,low22,1,2,2,new Date());
                HealthIndexStatistics healthIndexStatistics3 = new HealthIndexStatistics(patient,high32,normal32,low32,1,3,2,new Date());
                HealthIndexStatistics healthIndexStatistics4 = new HealthIndexStatistics(patient,high42,normal42,low42,1,4,2,new Date());
                HealthIndexStatistics healthIndexStatistics5 = new HealthIndexStatistics(patient,high52,normal52,low52,1,5,2,new Date());
                HealthIndexStatistics healthIndexStatistics6 = new HealthIndexStatistics(patient,high62,normal62,low62,1,6,2,new Date());
                HealthIndexStatistics healthIndexStatistics7 = new HealthIndexStatistics(patient,high72,normal72,low72,1,7,2,new Date());
                statisticsList.add(healthIndexStatistics1);
                statisticsList.add(healthIndexStatistics2);
                statisticsList.add(healthIndexStatistics3);
                statisticsList.add(healthIndexStatistics4);
                statisticsList.add(healthIndexStatistics5);
                statisticsList.add(healthIndexStatistics6);
                statisticsList.add(healthIndexStatistics7);
            }
            if(i==364){
                HealthIndexStatistics healthIndexStatistics1 = new HealthIndexStatistics(patient,high13,normal13,low13,1,1,3,new Date());
                HealthIndexStatistics healthIndexStatistics2 = new HealthIndexStatistics(patient,high23,normal23,low23,1,2,3,new Date());
                HealthIndexStatistics healthIndexStatistics3 = new HealthIndexStatistics(patient,high33,normal33,low33,1,3,3,new Date());
                HealthIndexStatistics healthIndexStatistics4 = new HealthIndexStatistics(patient,high43,normal43,low43,1,4,3,new Date());
                HealthIndexStatistics healthIndexStatistics5 = new HealthIndexStatistics(patient,high53,normal53,low53,1,5,3,new Date());
                HealthIndexStatistics healthIndexStatistics6 = new HealthIndexStatistics(patient,high63,normal63,low63,1,6,3,new Date());
                HealthIndexStatistics healthIndexStatistics7 = new HealthIndexStatistics(patient,high73,normal73,low73,1,7,3,new Date());
                statisticsList.add(healthIndexStatistics1);
                statisticsList.add(healthIndexStatistics2);
                statisticsList.add(healthIndexStatistics3);
                statisticsList.add(healthIndexStatistics4);
                statisticsList.add(healthIndexStatistics5);
                statisticsList.add(healthIndexStatistics6);
                statisticsList.add(healthIndexStatistics7);
            }

            list.add(healthIndex1);
            list.add(healthIndex2);
            list.add(healthIndex3);
            list.add(healthIndex4);
            list.add(healthIndex5);
            list.add(healthIndex6);
            list.add(healthIndex7);
            cal.add(Calendar.DAY_OF_YEAR,-1);
        }
        healthIndexStatisticsDao.save(statisticsList);
        return list;
    }

    /**
     * 统计血压
     * @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);
    }

    /**
     * 血压
     * @param patient
     * @param deviceSn
     * @param idcard
     */
    public List<HealthIndex> xueya(String patient, String deviceSn, String idcard, int age, String sex, List<HealthIndex> list){
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR,-1);
        String startTime = DateUtil.dateToStrShort(cal.getTime())+" 00:00:00";
        String endTime = DateUtil.dateToStrShort(cal.getTime())+" 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为正常
        int high=140,normal=90,low=60;
        int high11=0,normal11=0,low11=0,high12=0,normal12=0,low12=0,high13=0,normal13=0,low13=0;//1为近一个月，2为近半年，3为近一年
        int high21=0,normal21=0,low21=0,high22=0,normal22=0,low22=0,high23=0,normal23=0,low23=0;//1为近一个月，2为近半年，3为近一年
        int high31=0,normal31=0,low31=0,high32=0,normal32=0,low32=0,high33=0,normal33=0,low33=0;//1为近一个月，2为近半年，3为近一年
        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);
            }
        }

        List<HealthIndexStatistics> statisticsList = new ArrayList<>();
        for (int i = 0;i<365;i++){
            value1 = intValue1;//收缩压
            value2 = intValue2;//舒张压
            healthIndex = new HealthIndex();
            Date recordDate = cal.getTime();

            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;//心率是否不齐

            //统计数据
            int flag1 = ETLConstantData.ssy(value1);
            int flag2 = ETLConstantData.szy(value2);
            int flag3 = ETLConstantData.heartRate(value3);
            if(flag1>0){
                high11 += i<month?1:0;
                high12 += i<halfYear?1:0;
                high13 ++;
            }else if(flag1<0){
                low11 += i<month?1:0;
                low12 += i<halfYear?1:0;
                low13 ++;
            }else{
                normal11 += i<month?1:0;
                normal12 += i<halfYear?1:0;
                normal13 ++;
            }
            if(flag2>0){
                high21 += i<month?1:0;
                high22 += i<halfYear?1:0;
                high23 ++;
            }else if(flag2<0){
                low21 += i<month?1:0;
                low22 += i<halfYear?1:0;
                low23 ++;
            }else{
                normal21 += i<month?1:0;
                normal22 += i<halfYear?1:0;
                normal23 ++;
            }
            if(flag3>0){
                high31 += i<month?1:0;
                high32 += i<halfYear?1:0;
                high33 ++;
            }
            else if(flag3<0){
                low31 += i<month?1:0;
                low31 += i<halfYear?1:0;
                low31 ++;
            }
            else{
                normal31 += i<month?1:0;
                normal32 += i<halfYear?1:0;
                normal33 ++;
            }
            if(i==29){
                HealthIndexStatistics healthIndexStatistics1 = new HealthIndexStatistics(patient,high11,normal11,low11,2,8,1,new Date());
                HealthIndexStatistics healthIndexStatistics2 = new HealthIndexStatistics(patient,high21,normal21,low21,2,9,1,new Date());
                HealthIndexStatistics healthIndexStatistics3 = new HealthIndexStatistics(patient,high31,normal31,low31,2,10,1,new Date());
                statisticsList.add(healthIndexStatistics1);
                statisticsList.add(healthIndexStatistics2);
                statisticsList.add(healthIndexStatistics3);
            }
            if(i==181){
                HealthIndexStatistics healthIndexStatistics1 = new HealthIndexStatistics(patient,high12,normal12,low12,2,8,2,new Date());
                HealthIndexStatistics healthIndexStatistics2 = new HealthIndexStatistics(patient,high22,normal22,low22,2,9,2,new Date());
                HealthIndexStatistics healthIndexStatistics3 = new HealthIndexStatistics(patient,high32,normal32,low32,2,10,2,new Date());
                statisticsList.add(healthIndexStatistics1);
                statisticsList.add(healthIndexStatistics2);
                statisticsList.add(healthIndexStatistics3);
            }
            if(i==364){
                HealthIndexStatistics healthIndexStatistics1 = new HealthIndexStatistics(patient,high13,normal13,low13,2,8,3,new Date());
                HealthIndexStatistics healthIndexStatistics2 = new HealthIndexStatistics(patient,high23,normal23,low23,2,9,3,new Date());
                HealthIndexStatistics healthIndexStatistics3 = new HealthIndexStatistics(patient,high33,normal33,low33,2,10,3,new Date());
                statisticsList.add(healthIndexStatistics1);
                statisticsList.add(healthIndexStatistics2);
                statisticsList.add(healthIndexStatistics3);
            }

            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);
            cal.add(Calendar.DAY_OF_YEAR,-1);
        }
        healthIndexStatisticsDao.save(statisticsList);
        return list;
    }

    /**
     * 体重
     * @param patient
     * @param deviceSn
     * @param idcard
     */
    public List<HealthIndex> weight(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,"3",startTime,endTime);
        if(healthIndex!=null){//判断是否已经生成过数据
            return list;
        }

        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY,0);
        cal.set(Calendar.MINUTE,0);
        cal.set(Calendar.SECOND,0);

        double weiht = 0;
        if(age<=19){
            weiht = "2".equals(sex)?55.4:49.2;
        }else if(age>=20&&age<=24){
            weiht = "2".equals(sex)?57.3:50.8;
        }else if(age>=25&&age<=29){
            weiht = "2".equals(sex)?58.4:52.0;
        }else if(age>=30&&age<=34){
            weiht = "2".equals(sex)?59.8:53.0;
        }else if(age>=35&&age<=39){
            weiht = "2".equals(sex)?61.0:54.1;
        }else if(age>=40&&age<=44){
            weiht = "2".equals(sex)?62.6:55.5;
        }else if(age>=45&&age<=49){
            weiht = "2".equals(sex)?63.1:56.0;
        }else if(age>=50&&age<=60){
            weiht = "2".equals(sex)?63.1:56.0;
        }else{
            weiht = "2".equals(sex)?60.4:55.1;
        }
        double weight = weiht;
        Random random = new Random();
        int top = random.nextInt(4);
        for (int i = 0;i<52;i++){
            healthIndex = new HealthIndex();
            Date recordDate = cal.getTime();
            if(top==0){
                weiht += 0.1;
            }else if(top==1){
                if(i<26){
                    weiht += randomTen(random);
                }else{
                    weiht -= randomTen(random);
                }
            }else if(top==2){
                if(i<13){
                    weiht += randomTen(random);
                }else if(i<26){
                    weiht -= randomTen(random);
                }else if(i<39){
                    weiht += randomTen(random);
                }else{
                    weiht -= randomTen(random);
                }
            }else if(top==3){
                if(i<10){
                    weiht += randomTen(random);
                }else if(i<20){
                    weiht -= randomTen(random);
                }else if(i<32){
                    weiht += randomTen(random);
                }else if(i<44){
                    weiht -= randomTen(random);
                }else{
                    weiht += randomTen(random);
                }
            }

            healthIndex.setCzrq(new Date());
            healthIndex.setDel("1");
            healthIndex.setDeviceSn(deviceSn);
            healthIndex.setIdcard(idcard);
            healthIndex.setRecordDate(recordDate);
            healthIndex.setType(3);
            healthIndex.setUser(patient);
            healthIndex.setValue1(df.format(weiht));
            list.add(healthIndex);
            cal.add(Calendar.DAY_OF_YEAR,-7);
        }

        return list;
    }


    public double randomTen(Random random){
        int i = random.nextInt(5);
        return i==0?0:i/10.0;
    }

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

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

    public static void main(String[] args) {
        Random random = new Random();
        int in = 10;
        for (int i = 0;i<20;i++){
            in += random.nextInt(10);
            System.out.println(in);
        }

    }


    /**
     * 腰围
     * @param patient
     * @param deviceSn
     * @param idcard
     */
    public List<HealthIndex> yaowei(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,"4",startTime,endTime);
        if(healthIndex!=null){//判断是否已经生成过数据
            return list;
        }

        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY,0);
        cal.set(Calendar.MINUTE,0);
        cal.set(Calendar.SECOND,0);

        double yaowei = "2".equals(sex)?86:78;
        Random random = new Random();
        for (int i = 0;i<52;i++){
            healthIndex = new HealthIndex();
            Date recordDate = cal.getTime();

            int j = random.nextInt(7);
            if(j==0){

            }else{
                yaowei = j%2==0?yaowei+0.3:yaowei-0.3;
            }

            healthIndex.setCzrq(new Date());
            healthIndex.setDel("1");
            healthIndex.setDeviceSn(deviceSn);
            healthIndex.setIdcard(idcard);
            healthIndex.setRecordDate(recordDate);
            healthIndex.setType(4);
            healthIndex.setUser(patient);
            healthIndex.setValue1(df.format(yaowei));
            list.add(healthIndex);
            cal.add(Calendar.DAY_OF_YEAR,-7);
        }
        return list;
    }


}
