package service

import (
	"sws_xcx/models"
	"time"

	"github.com/jinzhu/gorm"
)

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

func NewXcxUserService() *XcxUserService {
	u := &models.XcxUser{}
	return &XcxUserService{rdb: readDb.Model(u), wdb: writeDb.Model(u)}
}

func (s *XcxUserService) GetUser(id uint64) (*models.XcxUser, error) {

	user := &models.XcxUser{}
	db := readDb.Where("id=?", id).First(user)

	return user, db.Error

}

func (s *XcxUserService) GetOrCreate(openId string, unionId string) (*models.XcxUser, error) {

	user := &models.XcxUser{OpenId: openId, UnionId: unionId}
	db := writeDb.Where("open_id = ?", openId)
	if unionId != "" {
		db = db.Or("union_id = ?", unionId)
	}
	db.FirstOrCreate(user)

	return user, db.Error

}

func (s *XcxUserService) UpdateUser(user *models.XcxUser) error {

	user.Mtime = time.Now()
	db := writeDb.Model(user).Update(user)

	return db.Error

}

func (s *XcxUserService) GetMobilePatientInfo(mobile, name, idCard string) (models.XcxPatients, error) {

	patients := models.XcxPatients{}
	err := ReadXtDB().Model(&patients).Where("(phone = ? or home_telephone = ? ) and name=? and id_card_no=? and status = 1", mobile, mobile, name, idCard).Find(&patients).Error
	if err == gorm.ErrRecordNotFound {
		err = nil
	}
	return patients, err
}

func (s *XcxUserService) GetPatientInfo(id int64) (models.XcxPatients, error) {

	patients := models.XcxPatients{}
	err := ReadXtDB().Model(&patients).Find(&patients, id).Error
	if err == gorm.ErrRecordNotFound {
		err = nil
	}
	return patients, err
}
