package service

import (
	"sws_xcx/models"

	"github.com/jinzhu/gorm"
)

type HealthProfileService struct {
	rdb *gorm.DB
	wdb *gorm.DB
}

func NewUserHealthProfileService() *HealthProfileService {

	p := &models.UserHealthProfile{}
	return &HealthProfileService{
		rdb: readDb.Model(p),
		wdb: writeDb.Model(p),
	}
}

func (s *HealthProfileService) GetUserHealthProfileByUserId(userId uint64) (*models.UserHealthProfile, error) {
	p := &models.UserHealthProfile{}
	err := s.rdb.Find(p, "user_id = ?", userId).Error
	return p, err
}

func (s *HealthProfileService) Get(id uint64) (models.UserHealthProfile, error) {
	p := &models.UserHealthProfile{}
	err := s.rdb.First(p, id).Error
	return *p, err
}

func (s *HealthProfileService) SavePatientInfo(userId uint64, realName string, idCard string, regPhone string) error {
	p, err := s.GetUserHealthProfileByUserId(userId)
	if err != nil {
		return err
	}

	if p == nil {
		p = &models.UserHealthProfile{}
	}

	p.UserId = userId
	p.RealName = realName
	p.InpatientRegPhone = regPhone
	return s.wdb.Save(p).Error
}

func (s *HealthProfileService) SaveHealthProfile(userId uint64, req models.SaveHealthProfileReq) error {
	p, err := s.GetUserHealthProfileByUserId(userId)
	if err != nil {
		return err
	}

	if p == nil {
		p = &models.UserHealthProfile{}
	}

	p.UserId = userId
	p.Birthday = req.Birthday
	p.BloodType = req.BloodType
	p.CreatineTime = req.CreatineTime
	p.Creatinine = req.Creatinine
	p.CreatinineUnit = req.CreatinineUnit
	p.Gender = req.Gender
	p.Height = req.Height
	p.IllnessState = req.IllnessState
	p.RenalFunctionStatus = req.RenalFunctionStatus
	p.UrineProtein = req.UrineProtein
	p.UrineProtein24h = req.UrineProtein24h
	p.UrineProtein24hTime = req.UrineProtein24hTime
	p.UrineProtein24hUnit = req.UrineProtein24hUnit
	p.UrineProteinTime = req.UrineProteinTime
	p.UrineProteinUnit = req.UrineProteinUnit
	p.Weight = req.Weight

	return s.wdb.Save(p).Error
}

func (s *HealthProfileService) Save(p *models.UserHealthProfile) error {
	return s.wdb.Save(p).Error
}
