package service

import (
	"errors"
	"sws_xcx/models"
	"time"

	"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
	if err == gorm.ErrRecordNotFound {
		err = nil
	}
	return p, err
}

func (s *HealthProfileService) Get(id uint64) (models.UserHealthProfile, error) {
	p := &models.UserHealthProfile{}
	err := s.rdb.First(p, id).Error
	if err == gorm.ErrRecordNotFound {
		err = nil
	}
	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
	p.IdCard = idCard

	if p.Id == 0 {
		return s.wdb.Create(p).Error
	}
	return s.wdb.Model(p).Update(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

	t := &models.Time{}
	var n time.Time

	if req.Birthday != "" {

		n, err = t.Parse(req.Birthday)
		if err != nil {
			return errors.New("Birthday参数格式不正确")
		}
		p.Birthday = n

	}

	p.BloodType = req.BloodType
	if req.CreatineTime != "" {
		n, err = t.Parse(req.CreatineTime)
		if err != nil {
			return errors.New("CreatineTime参数格式不正确")
		}
		p.CreatineTime = n

	}

	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
	if req.UrineProtein24hTime != "" {
		n, err = t.Parse(req.UrineProtein24hTime)
		if err != nil {
			return errors.New("UrineProtein24hTime参数格式不正确")
		}
		p.UrineProtein24hTime = n

	}
	p.UrineProtein24hUnit = req.UrineProtein24hUnit
	if req.UrineProteinTime != "" {
		n, err = t.Parse(req.UrineProteinTime)
		if err != nil {
			return errors.New("UrineProteinTime参数格式不正确")
		}
		p.UrineProteinTime = n
	}

	p.UrineProteinUnit = req.UrineProteinUnit
	p.Weight = req.Weight

	if p.Id == 0 {
		return s.wdb.Create(p).Error
	}
	return s.wdb.Model(p).Update(p).Error
}

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