package controllers

import (
	"Xcx_New/enums"
	"Xcx_New/models"
	"Xcx_New/service"
	"Xcx_New/utils"
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/astaxie/beego"
)

func PatientDataConfigAPIControllerRegistRouters() {
	beego.Router("/api/patient/courses", &PatientDataConfigAPIController{}, "get:Courses")
	beego.Router("/api/patient/course/create", &PatientDataConfigAPIController{}, "get:CreateCourse")
	beego.Router("/api/patient/course/delete", &PatientDataConfigAPIController{}, "post:DeleteCourse")
	beego.Router("/api/patient/course/modify", &PatientDataConfigAPIController{}, "get:ModifyCourse")

	beego.Router("/api/patient/rescues", &PatientDataConfigAPIController{}, "get:Rescues")
	beego.Router("/api/patient/rescue/create", &PatientDataConfigAPIController{}, "post:CreateRescue")
	beego.Router("/api/patient/rescue/delete", &PatientDataConfigAPIController{}, "post:DeleteRescue")
}

type PatientDataConfigAPIController struct {
	BaseAuthAPIController
}

// /api/patient/courses [get]
// @param patient_id:int
// @param start_time:string (yyyy-MM-dd)
// @param end_time:string (yyyy-MM-dd)
func (this *PatientDataConfigAPIController) Courses() {
	patientID, _ := this.GetInt64("patient_id")
	startTimeYMDStr := this.GetString("start_time")
	endTimeYMDStr := this.GetString("end_time")
	if patientID <= 0 || len(startTimeYMDStr) == 0 || len(endTimeYMDStr) == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	endTimeYMDHmsStr := endTimeYMDStr + " 23:59:59"
	startTime, parseStartTimeErr := utils.ParseTimeStringToTime("2006-01-02", startTimeYMDStr)
	endTime, parseEndTimeErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", endTimeYMDHmsStr)
	if parseStartTimeErr != nil || parseEndTimeErr != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamFormatWrong)
		return
	}

	adminUserInfo := this.GetAdminUserInfo()
	patient, getPatientErr := service.GetPatientByID(adminUserInfo.CurrentOrgId, patientID)
	if getPatientErr != nil {
		this.ErrorLog("获取患者信息失败:%v", getPatientErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	} else if patient == nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
		return
	}

	records, getRecordsErr := service.GetPatientCourseOfDisease(adminUserInfo.CurrentOrgId, patientID, startTime.Unix(), endTime.Unix())
	if getRecordsErr != nil {
		this.ErrorLog("获取患者病程记录失败:%v", getRecordsErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}

	admins, getAllAdminsErr := service.GetAllAdminUsers(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId)
	if getAllAdminsErr != nil {
		this.ErrorLog("获取所有管理员失败:%v", getAllAdminsErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}

	this.ServeSuccessJSON(map[string]interface{}{
		"records": records,
		"doctors": admins,
	})
}

// /api/patient/course/create [post]
// @param patient_id:int
// @param content:string
func (this *PatientDataConfigAPIController) CreateCourse() {
	patientID, _ := this.GetInt64("patient_id")
	fmt.Println(patientID)
	content := this.GetString("content")
	fmt.Println("content22222222222222222222", content)
	record_time_str := this.GetString("record_time")
	title := this.GetString("title")

	if patientID <= 0 || len(content) == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	if len(record_time_str) == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	checkDate, _ := utils.ParseTimeStringToTime("2006-01-02 15:04", record_time_str)

	adminUserInfo := this.GetAdminUserInfo()
	patient, getPatientErr := service.GetPatientByID(adminUserInfo.CurrentOrgId, patientID)
	if getPatientErr != nil {
		this.ErrorLog("获取患者信息失败:%v", getPatientErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	} else if patient == nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
		return
	}

	now := time.Now().Unix()
	record := models.PatientDiseaseCourse{
		OrgID:      adminUserInfo.CurrentOrgId,
		PatientID:  patientID,
		Recorder:   adminUserInfo.AdminUser.Id,
		RecordTime: checkDate.Unix(),
		Content:    content,
		Status:     1,
		CreateTime: now,
		ModifyTime: now,
		Title:      title,
	}

	createErr := service.CreatePatientCourseOfDisease(&record)
	if createErr != nil {
		this.ErrorLog("创建患者病程记录失败:%v", createErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}

	this.ServeSuccessJSON(map[string]interface{}{
		"record": record,
	})
}

// /api/patient/course/delete
// @param patient_id:int
// @param ids:string 一个或多个record_id以逗号相隔 ("1,3,7")
func (this *PatientDataConfigAPIController) DeleteCourse() {
	patientID, _ := this.GetInt64("patient_id")
	idsStr := this.GetString("ids")
	if patientID <= 0 || len(idsStr) == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	adminUserInfo := this.GetAdminUserInfo()
	patient, getPatientErr := service.GetPatientByID(adminUserInfo.CurrentOrgId, patientID)
	if getPatientErr != nil {
		this.ErrorLog("获取患者信息失败:%v", getPatientErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	} else if patient == nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
		return
	}

	recordIDStrs := strings.Split(idsStr, ",")
	recordIDs := make([]int64, 0, len(recordIDStrs))
	for _, idStr := range recordIDStrs {
		id, parseErr := strconv.Atoi(idStr)
		if parseErr != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		recordIDs = append(recordIDs, int64(id))
	}

	deleteErr := service.DeletePatientCoursesInBatch(adminUserInfo.CurrentOrgId, patientID, recordIDs)
	if deleteErr != nil {
		this.ErrorLog("删除患者病程记录失败:%v", deleteErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	this.ServeSuccessJSON(nil)
}

// /api/patient/rescues [get]
// @param patient_id:int
// @param start_time:string (yyyy-MM-dd)
// @param end_time:string (yyyy-MM-dd)
func (this *PatientDataConfigAPIController) Rescues() {
	patientID, _ := this.GetInt64("patient_id")
	startTimeYMDStr := this.GetString("start_time")
	endTimeYMDStr := this.GetString("end_time")
	if patientID <= 0 || len(startTimeYMDStr) == 0 || len(endTimeYMDStr) == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	endTimeYMDHmsStr := endTimeYMDStr + " 23:59:59"
	startTime, parseStartTimeErr := utils.ParseTimeStringToTime("2006-01-02", startTimeYMDStr)
	endTime, parseEndTimeErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", endTimeYMDHmsStr)
	if parseStartTimeErr != nil || parseEndTimeErr != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamFormatWrong)
		return
	}

	adminUserInfo := this.GetAdminUserInfo()
	patient, getPatientErr := service.GetPatientByID(adminUserInfo.CurrentOrgId, patientID)
	if getPatientErr != nil {
		this.ErrorLog("获取患者信息失败:%v", getPatientErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	} else if patient == nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
		return
	}

	records, getRecordsErr := service.GetPatientRescueRecords(adminUserInfo.CurrentOrgId, patientID, startTime.Unix(), endTime.Unix())
	if getRecordsErr != nil {
		this.ErrorLog("获取患者抢救记录失败:%v", getRecordsErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}

	admins, getAllAdminsErr := service.GetAllAdminUsers(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId)
	if getAllAdminsErr != nil {
		this.ErrorLog("获取所有管理员失败:%v", getAllAdminsErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}

	this.ServeSuccessJSON(map[string]interface{}{
		"records": records,
		"doctors": admins,
	})
}

// /api/patient/rescue/create [post]
// @param patient_id:int
// @param content:string
func (this *PatientDataConfigAPIController) CreateRescue() {
	patientID, _ := this.GetInt64("patient_id")
	content := this.GetString("content")
	if patientID <= 0 || len(content) == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	adminUserInfo := this.GetAdminUserInfo()
	patient, getPatientErr := service.GetPatientByID(adminUserInfo.CurrentOrgId, patientID)
	if getPatientErr != nil {
		this.ErrorLog("获取患者信息失败:%v", getPatientErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	} else if patient == nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
		return
	}

	now := time.Now().Unix()
	record := models.PatientRescueRecord{
		OrgID:      adminUserInfo.CurrentOrgId,
		PatientID:  patientID,
		Recorder:   adminUserInfo.AdminUser.Id,
		RecordTime: now,
		Content:    content,
		Status:     1,
		CreateTime: now,
		ModifyTime: now,
	}

	createErr := service.CreatePatientRescueRecord(&record)
	if createErr != nil {
		this.ErrorLog("创建患者抢救记录失败:%v", createErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}

	this.ServeSuccessJSON(map[string]interface{}{
		"record": record,
	})
}

// /api/patient/rescue/delete
// @param patient_id:int
// @param ids:string 一个或多个record_id以逗号相隔 ("1,3,7")
func (this *PatientDataConfigAPIController) DeleteRescue() {
	patientID, _ := this.GetInt64("patient_id")
	idsStr := this.GetString("ids")
	if patientID <= 0 || len(idsStr) == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	adminUserInfo := this.GetAdminUserInfo()
	patient, getPatientErr := service.GetPatientByID(adminUserInfo.CurrentOrgId, patientID)
	if getPatientErr != nil {
		this.ErrorLog("获取患者信息失败:%v", getPatientErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	} else if patient == nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
		return
	}

	recordIDStrs := strings.Split(idsStr, ",")
	recordIDs := make([]int64, 0, len(recordIDStrs))
	for _, idStr := range recordIDStrs {
		id, parseErr := strconv.Atoi(idStr)
		if parseErr != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		recordIDs = append(recordIDs, int64(id))
	}

	deleteErr := service.DeletePatientResuceRecordsInBatch(adminUserInfo.CurrentOrgId, patientID, recordIDs)
	if deleteErr != nil {
		this.ErrorLog("删除患者抢救记录失败:%v", deleteErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	this.ServeSuccessJSON(nil)
}

func (this *PatientDataConfigAPIController) ModifyCourse() {
	patientID, _ := this.GetInt64("patient_id")
	content := this.GetString("content")
	id, _ := this.GetInt64("id", 0)
	record_time_str := this.GetString("record_time")
	title := this.GetString("title")

	if patientID <= 0 || len(content) == 0 || id == 0 || len(record_time_str) == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	checkDate, _ := utils.ParseTimeStringToTime("2006-01-02 15:04", record_time_str)

	adminUserInfo := this.GetAdminUserInfo()
	patient, getPatientErr := service.GetPatientByID(adminUserInfo.CurrentOrgId, patientID)
	if getPatientErr != nil {
		this.ErrorLog("获取患者信息失败:%v", getPatientErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	} else if patient == nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
		return
	}

	now := time.Now().Unix()

	record := models.PatientDiseaseCourse{
		ID:         id,
		OrgID:      adminUserInfo.CurrentOrgId,
		PatientID:  patientID,
		Recorder:   adminUserInfo.AdminUser.Id,
		Content:    content,
		Status:     1,
		CreateTime: now,
		ModifyTime: now,
		Title:      title,
		RecordTime: checkDate.Unix(),
	}

	createErr := service.ModifyPatientCourses(&record)
	if createErr != nil {
		this.ErrorLog("创建患者抢救记录失败:%v", createErr)
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}

	this.ServeSuccessJSON(map[string]interface{}{
		"record": record,
	})
}
