系统健康报告

# -*- coding: utf-8 -*-
from __future__ import absolute_import
import time
import datetime
import calendar

from comm.db import db
from bson import ObjectId


class ServiceHealthReport(object):
    def __init__(self, watch_id):
        self.rpt_date = ''
        self.start_time, self.end_time = self.get_time()
        self.watch_id = watch_id
        self.standard = self.standard_data()
        self.data = {}
        self.standard = {}

    def standard_data(self):
        """
        该方法获取运动标准数据与吸烟喝酒标准数据, 暂时写固定
        """
        self.standard= {'step_standard': 280000, 'calorie_standard': 39000,
                'sleep_time': 8*60, 'smoke_standard': 5, 'drink_standard': 200}
        return self.standard

    def get_time(self):
        year = datetime.date.today().year
        month = datetime.date.today().month
        firstDayWeekDay, monthRange = calendar.monthrange(year, month)
        start = str(datetime.date(year= year, month=month, day=1))
        end = str(datetime.date(year=year, month=month, day=monthRange))
        self.rpt_date = start[0:7]
        return time.mktime(time.strptime(str(start),'%Y-%m-%d')), time.mktime(time.strptime(str(end),'%Y-%m-%d'))

    def alert_type(self, value):
        """
        根据异常次数,返回相应风险水平
        """
        if value <= 3:
            return '正常'
        elif 3 < value <= 6:
            return '警惕'
        else:
            return '风险'

    def get_advise(self):
        """
        根据用户数据与标准值对比,获取建议
        """
        standard_data = self.standard_data()
        step_gap = self.data['step_total'] - standard_data['step_standard']
        calorie_gap = self.data['calorie_total'] - standard_data['calorie_standard']
        sleep_gap = self.data['sleep_time'] - standard_data['sleep_time']
        smoke_gap = self.data['smoke_total'] - standard_data['smoke_standard']
        drink_gap = self.data['drink_amount'] - standard_data['drink_standard']
        if step_gap > 20000 and calorie_gap > 0:
            sport_advise = '运动过量,合理安排运动时间可以强身健体,过度运动会增加身体负担.'
        elif -20000 <= step_gap <= 20000:
            sport_advise = '运动适量,继续保持,合理安排运动时间.'
        else:
            sport_advise = '缺乏运动,建议适当增加运动时间.'
        if sleep_gap > 60:
            sleep_advise = '睡眠时长充足,更需要注意睡眠质量.'
        elif -60 <= sleep_gap <= 60:
            sleep_advise = '睡眠时长一般,注意入睡时间以及起床时间的安排.'
        else:
            sleep_advise = '睡眠时长较短,充足的睡眠时间可以促进身体新陈代谢.'
        if smoke_gap > 2:
            smoke_advise = '吸烟过量,需要立即改善.'
        elif -2 <= smoke_gap <=2:
            smoke_advise = '吸烟适量,建议减少吸烟次数.'
        else:
            smoke_advise = '吸烟状况良好,继续保持.'
        if drink_gap > 50:
            drink_advise = '饮酒过量,需要立即改善.'
        elif 30 <= drink_gap <= 50:
            drink_advise = '饮酒量适中,切勿贪杯.'
        else:
            drink_advise = '饮酒量较少,继续保持.'
        self.data['sport_advise'] = sport_advise
        self.data['sleep_advise'] = sleep_advise
        self.data['habit_advise'] = smoke_advise + drink_advise

    def create_health_report(self):
        """
        创建健康报告主程序
        """
        out_bpms = self.heart_rate_data()
        bpms_alert_type = self.alert_type(out_bpms)
        out_bsug = self.blood_sugar_data()
        bsug_alert_type = self.alert_type(out_bsug)
        out_bpre = self.blood_pre_data()
        bpre_alert_type = self.alert_type(out_bpre)
        step_total, calorie_total = self.step_calorie_total()
        smoke_total, drink_total, drink_amount = self.smoke_and_drink_data()
        sleep_time = self.get_sleep_time()
        self.data ={'out_bpms': out_bpms, 'out_bpms_type': bpms_alert_type, 'out_bsug': out_bsug,
                'out_bsug_type': bsug_alert_type, 'out_bpre': out_bpre, 'out_bpre_type': bpre_alert_type,
                'step_total': step_total, 'smoke_total': smoke_total, 'calorie_total': calorie_total,
                'drink_total': drink_total, 'drink_amount': drink_amount, 'sleep_time': sleep_time}
        self.get_advise()
        print self.rpt_date
        return self.data

    def heart_rate_data(self):
        """
        心率数据
        """
        watch = db.watch.find_one({"_id": self.watch_id})
        bpm_max = watch.get('bpm_max',70)
        bpm_min = watch.get('bpm_min',60)
        out_bpmsets = db.heart_rate.find({
            "$or":[{"bpm":{"$gt":bpm_max}},{"bpm":{"$lt":bpm_min}}],
            "watch_id": self.watch_id
        }).sort([("maketime", -1)])
        return out_bpmsets.count()

    def blood_sugar_data(self):
        """
        血糖数据
        """
        watch = db.watch.find_one({"_id": self.watch_id})
        gi_max = watch.get('gi_max',75)
        gi_min = watch.get('gi_min',50)
        out_gisets = db.blood_sugar.find({
            "$or":[{"gi":{"$gt":gi_max}},{"gi":{"$lt":gi_min}}],
            "watch_id": self.watch_id
        }).sort([("maketime", -1)])
        return out_gisets.count()

    def blood_pre_data(self):
        """
        血压数据
        """
        watch = db.watch.find_one({"_id": self.watch_id})
        dbp_max = watch.get('dbp_max',90)
        dbp_min = watch.get('dbp_min',60)
        sbp_max = watch.get('sbp_max',99)
        sbp_min = watch.get('sbp_min',60)
        out_presets = db.blood_pressure.find({
            "$or":[{
                "dbp":{"$gt":dbp_max}},{"sbp":{"$gt":sbp_max}},
                {"sbp_min":{"$lt":sbp_min}},{"dbp_min":{"$lt":dbp_min}}],
            "watch_id": self.watch_id,
        }).sort([("maketime", -1)])
        return out_presets.count()

    def get_sleep_time(self):
        """
        睡眠时间
        """
        query = {'maketime': {'$gte': self.start_time, '$lte': self.end_time}, 'watch_id': self.watch_id}
        cursor = db.sleep.find(query)
        total = 0
        avg = 0
        for i in cursor:
            total += i.get('duration', 0)
            avg += 1
        if total == 0:
            return total
        else:
            avg = int(float(total)/avg)
        return avg

    def step_calorie_total(self):
        """
        计步与卡路里统计
        """
        query = {'maketime': {'$gte': self.start_time, '$lte': self.end_time}, 'watch_id': self.watch_id}
        cursor = db.step.aggregate([
                            {'$match': query},
                            {'$project': {
                                'c': '$calorie',
                                'n': '$step',
                            }},
                            {'$group': {
                                '_id': 'watch_id',
                                'n': {'$sum': '$n'},
                                'c': {'$sum': '$c'}
                            }}
                        ])
        step_total = 0
        calorie_total = 0
        for i in cursor:
            step_total = int(i.get('n', 0))
            calorie_total = int(i.get('c', 0))
        return step_total, calorie_total

    def smoke_and_drink_data(self):
        """
        抽烟与喝酒统计
        """
        sd_list = []
        query = {'maketime': {'$gte': self.start_time, '$lte': self.end_time}, 'watch_id': self.watch_id}
        cursor = db.habit.find(query)
        for i in cursor:
            sd_list.append(i)
        smoke_total = 0
        drink = {}
        ml = 0
        for i in sd_list:
            smoke_total += int(i['cigarette'])
            for d in i['alcoholic']:
                ml += int(i['alcoholic'][d])
                if drink.has_key(d):
                    drink[d] += i['alcoholic'][d]
                else:
                    drink[d] = i['alcoholic'][d]
        return smoke_total, drink, ml

    def save_to_mongo(self):
        data = self.create_health_report()
        db.service_rpt.insert_one({
            'watch_id': watch_id,
            'date': self.rpt_date,
            'out_bpms': data['out_bpms'],
            'out_bpms_type': data['out_bpms_type'],
            'out_bpre': data['out_bpre'],
            'out_bpre_type': data['out_bpre_type'],
            'out_bsug': data['out_bsug'],
            'out_bsug_type': data['out_bsug_type'],
            'step_total': data['step_total'],
            'calorie_total': data['calorie_total'],
            'sleep_time_avg': data['sleep_time'],
            'habit_smoke': data['smoke_total'],
            'habit_drink': data['drink_total'],
            'step_standard': self.standard['step_total'],
            'calorie_standard': self.standard['calorie_total'],
            'sleep_standard': self.standard['sleep_time'],
            'smoke_standard': self.standard['smoke_standard'],
            'drink_standard': self.standard['drink_standard'],
            'sport_advise': data['sport_advise'],
            'sleep_advise': data['sleep_advise'],
            'habit_advise': data['habit_advise'],
        })


if __name__ == '__main__':
    watch_id = ObjectId('589545425f1d6569e76622af')
    RS = ServiceHealthReport(watch_id)
    resu = RS.create_health_report()
    for i,v in resu.items():
        print i,v

你可能感兴趣的:(系统健康报告)