package test

import (
	"encoding/json"
	"fmt"
	"strings"
	"sws_xcx/models"
	"sws_xcx/service"
	"testing"
	"time"

	"github.com/jinzhu/gorm"
)

func init() {
	service.ConnectDB()
}

func TestGenDb(t *testing.T) {
	db := service.ReadDB()
	err := db.DB().Ping()
	if err != nil {
		t.Error(err)
	}
}

func TestUpdate(t *testing.T) {

	s := service.NewXcxUserService()

	u := &models.XcxUser{Id: 1, UnionId: "123"}

	err := s.UpdateUser(u)
	if err != nil {
		t.Error(err)
	}

}

func TestDBGet(t *testing.T) {
	wdb := service.WriteDB()
	p := &models.UserHealthProfile{}
	err := wdb.Model(p).First(p, "user_id = ?", 2).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		t.Error(err)
	}

	t.Log(p)
}

func TestHealthProfileService_SavePatientInfo(t *testing.T) {

	userId := uint64(1)
	realName := "John Doe"
	idCard := "1234567890"
	regPhone := "123-456-7890"

	s := service.NewUserHealthProfileService()

	// 调用待测试的函数
	err := s.SavePatientInfo(userId, realName, idCard, regPhone)

	if err != nil {
		t.Error(err)
	}
}

func TestHealthProfileService_SaveHealthProfile(t *testing.T) {
	s := service.NewUserHealthProfileService()
	userId := uint64(1)
	req := models.SaveHealthProfileReq{
		Birthday: "2023-01-01 10:00:00",
	}
	err := s.SaveHealthProfile(userId, req)
	if err != nil {
		t.Error(err)
		return
	}

	m, err := s.GetUserHealthProfileByUserId(userId)

	if err != nil {
		t.Error(err)
		return
	}
	t.Log(models.Time(m.Birthday))

}

func TestGetMobilePatientInfo(t *testing.T) {

	s := service.NewXcxUserService()
	mobile := "13414858017"
	name := "邹土贵"
	idcard := "440804195502141115"

	p, err := s.GetMobilePatientInfo(mobile, name, idcard)
	if err != nil {
		t.Error(err)
		return
	}
	t.Logf("id: %d orgid: %d", p.ID, p.UserOrgId)
}

func TestLoginRedis(t *testing.T) {

	s := service.NewXcxUserService()
	u, err := s.GetUser(1)
	if err != nil {
		t.Error(err)
		return

	}
	key := "47ca0e8d-fad7-4ef4-8dfc-5a36dd0d0993"
	uJson, _ := json.Marshal(u)
	redisCli := service.RedisClient()
	defer redisCli.Close()
	redisCli.Set(fmt.Sprintf("session:%v", key), uJson, time.Hour*time.Duration(7200))

}

func TestStr(t *testing.T) {
	str := "1234567"

	strArr := strings.Split(str, "")
	t.Log(strArr)
}
