package system

import (
	"github.com/gin-gonic/gin"
	"miniapp/model/common"
	"miniapp/model/common/request"
	r "miniapp/model/common/response"
	"strconv"
)

type HospitalApi struct {
}

// GetHospitalList 获取医院列表
func (h HospitalApi) GetHospitalList(ctx *gin.Context) {
	var p request.PageInfo
	if err := ctx.ShouldBind(&p); err != nil {
		r.FailWithMessage("参数错误"+err.Error(), ctx)
		return
	}

	list, total, err := hospitalService.GetHospitalList(p)
	if err != nil {
		r.FailWithMessage("获取医院列表失败", ctx)
		return
	}

	r.OkWithDetailed(r.PageResult{List: list, Total: total, Page: p.Page, PageSize: p.PageSize}, "获取成功", ctx)
}

// CreateHospital 创建医院
func (h HospitalApi) CreateHospital(ctx *gin.Context) {
	var hospital common.Hospital
	if err := ctx.ShouldBindJSON(&hospital); err != nil {
		r.FailWithMessage("参数错误"+err.Error(), ctx)
		return
	}

	err := hospitalService.CreateHospital(&hospital)
	if err != nil {
		r.FailWithMessage("创建失败"+err.Error(), ctx)
		return
	}

	r.OkWithMessage("创建成功", ctx)
}

// UpdateHospital 更新医院
func (h HospitalApi) UpdateHospital(ctx *gin.Context) {
	var hospital common.Hospital
	if err := ctx.ShouldBindJSON(&hospital); err != nil {
		r.FailWithMessage("参数错误"+err.Error(), ctx)
		return
	}

	err := hospitalService.UpdateHospital(&hospital)
	if err != nil {
		r.FailWithMessage("更新失败"+err.Error(), ctx)
		return
	}

	r.OkWithMessage("更新成功", ctx)
}

// DeleteHospital 删除医院
func (h HospitalApi) DeleteHospital(ctx *gin.Context) {
	var hospital common.Hospital
	if err := ctx.ShouldBind(&hospital); err != nil {
		r.FailWithMessage("参数错误"+err.Error(), ctx)
		return
	}

	err := hospitalService.DeleteHospital(&hospital)
	if err != nil {
		r.FailWithMessage("删除失败"+err.Error(), ctx)
		return
	}

	r.OkWithMessage("删除成功", ctx)
}

// GetHospitalById 根据id获取医院
func (h HospitalApi) GetHospitalById(ctx *gin.Context) {
	Id := ctx.Param("id")
	if Id == "" {
		r.FailWithMessage("参数错误", ctx)
		return
	}

	// 参数转换 string -> int
	id, _ := strconv.Atoi(Id)
	hospitalResult, err := hospitalService.GetHospitalById(uint(id))
	if err != nil {
		r.FailWithMessage("获取失败"+err.Error(), ctx)
		return
	}

	r.OkWithDetailed(hospitalResult, "获取成功", ctx)
}
