package app

import (
	"errors"
	"github.com/duke-git/lancet/v2/datetime"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"miniapp/global"
	"miniapp/model/app"
	"miniapp/model/app/request"
	"miniapp/model/app/response"
	"miniapp/model/common"
	"miniapp/model/types"
	"time"
)

type UserService struct{}

func (UserService) GetUser(user *app.User) (err error) {
	return global.GVA_DB.Take(&user, user).Error
}

func (UserService) GetOrCreate(user *app.User) (err error) {
	//err = global.GVA_DB.Take(&user, user).Error
	err = global.GVA_DB.Model(&user).Where("phone = ?", user.Phone).First(&user).Error
	if err == nil {
		return
	}
	// 如果是没查询到记录，则创建用户
	if err == gorm.ErrRecordNotFound {
		// 用户不存在，创建用户
		if err = global.GVA_DB.Create(&user).Error; err != nil {
			global.GVA_LOG.Error("账号创建失败: %v", zap.Error(err))
			err = errors.New("登录失败")
			return
		}
	}
	return
}

// CheckUnionIdIsExist 检查UnionId和OpenId是否存在
func (UserService) CheckUnionIdIsExist(unionId, openId string) bool {
	var count int64
	err := global.GVA_DB.Model(&app.User{}).Where("wechat_union_id = ? and wechat_open_id = ?", unionId, openId).Count(&count).Error
	if err != nil {
		return false
	}
	return count > 0
}

// UpdateUserInfo 更新普通用户信息
func (UserService) UpdateUserInfo(e *app.User) (err error) {
	return global.GVA_DB.Updates(&e).Error
}

// GetAverageUserList 查询普通用户列表
func (UserService) GetAverageUserList(p request.GetUserList) (records []response.UserItem, count int64, err error) {
	tx := global.GVA_DB.Scopes(Page(p.Page, p.PageSize)).
		Table("`t_user` AS tu").
		Select("tu.id AS id,tu.avatar AS avatar,tu.phone AS phone,tu.nickname AS nickname,tu.sex AS sex,tu.created_at AS created_at,tu.last_login_at AS last_login_at,tu.`status` AS `status`").
		Order("tu.last_login_at DESC")

	if p.Phone != "" {
		tx = tx.Where("tu.phone LIKE ?", "%"+p.Phone+"%")
	}
	//加一个姓名的模糊查询
	if p.Name != "" {
		tx = tx.Where("tu.nickname LIKE ?", "&"+p.Name+"%")
	}
	if p.Status != "" {
		tx = tx.Where("tu.`status` = ?", p.Status)
	}

	if p.StartAt != "" || p.EndAt != "" {
		start := time.Date(2021, 1, 1, 0, 0, 0, 0, time.Local)
		end := time.Now()
		// 处理数据
		if p.StartAt != "" {
			st, err := datetime.FormatStrToTime(p.StartAt, "yyyy-mm-dd")
			if err != nil {
				global.GVA_LOG.Error("解析开始时间异常")
				return nil, 0, errors.New("解析开始时间异常")
			}
			start = datetime.BeginOfDay(st)
		}
		if p.EndAt != "" {
			et, err := datetime.FormatStrToTime(p.EndAt, "yyyy-mm-dd")
			if err != nil {
				global.GVA_LOG.Error("解析结束时间异常")
				return nil, 0, errors.New("解析结束时间异常")
			}
			end = datetime.EndOfDay(et)
		}
		// 处理查询条件
		tx.Where("tor.pay_at BETWEEN ? AND ?", start, end)
	}

	err = tx.Offset(-1).Limit(-1).Count(&count).Find(&records).Error
	return
}

func (UserService) UpdateLastLoginInfo(username int) {
	now := time.Now().Local()

	global.GVA_DB.Model(&app.User{}).
		Where("id = ?", username).
		Updates(app.User{LastLoginAt: (*types.DateTime)(&now)})

}

// UpdateUserHospital 更新用户医院信息
func (UserService) UpdateUserHospital(r *request.ChangeUserHospital) (err error) {

	err = global.GVA_DB.Delete(&common.UserTodo{}, "user_id = ?", r.UserId).Error
	if err != nil {
		global.GVA_LOG.Error("清除用户Todo列表失败", zap.Error(err))
		return
	}

	var hospital common.Hospital
	err = global.GVA_DB.Where("id = ?", r.HospitalId).Preload("Todos").First(&hospital).Error
	if err != nil {
		global.GVA_LOG.Error("获取医院信息失败", zap.Error(err))
		return
	}

	if hospital.Todos != nil {
		var userTodos []common.UserTodo
		for _, todo := range hospital.Todos {
			userTodos = append(userTodos, common.UserTodo{
				Content:  todo.Content,
				UserId:   r.UserId,
				IsFinish: 0,
			})
		}
		err = global.GVA_DB.Create(&userTodos).Error
		if err != nil {
			global.GVA_LOG.Error("创建用户Todo列表失败", zap.Error(err))
			return
		}
	}
	return
}

func (s UserService) GetUserInfo(id string) (user response.UserVO, err error) {
	var u app.User
	err = global.GVA_DB.Where("id = ?", id).First(&u).Error
	user.ParseOrdinary(u)

	if u.IsSurgery == 1 {
		user.TimeNote = "距离下次复查时间还剩："
	} else {
		user.TimeNote = "距离手术时间还剩："
	}
	return
}
