package controllers

import (
	"XT_New/enums"
	"XT_New/models"
	"XT_New/service"
	"github.com/astaxie/beego"
	"strings"
	"time"
)

type HisPrintApiController struct {
	BaseAuthAPIController
}

func HisPrintApiRegistRouters() {
	beego.Router("/api/his/prescription/print", &HisPrintApiController{}, "get:GetBatchHisPrescriptionData")
}

func (c *HisPrintApiController) GetBatchHisPrescriptionData() {
	record_date := c.GetString("record_date")
	patient_ids := c.GetString("patient_ids")
	print_type, _ := c.GetInt64("type")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", record_date+" 00:00:00", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordDateTime := theTime.Unix()
	adminInfo := c.GetAdminUserInfo()
	ids := strings.Split(patient_ids, ",")
	switch print_type {
	case 1:
		patients, _ := service.GetBatchDrugHisPrescription(ids, recordDateTime, adminInfo.CurrentOrgId)
		c.ServeSuccessJSON(map[string]interface{}{
			"patients": patients,
		})
		break
	case 2:
		//var newPatients []*models.PrintPatient

		patients, _ := service.GetBatchProjectHisPrescription(ids, recordDateTime, adminInfo.CurrentOrgId)
		//for _, item := range patients {
		//	for _, subItem := range item.HisPrintPrescription {
		//		for _, subItemTwo := range subItem.HisPrescriptionProject {
		//			if subItemTwo.HisProject.CostClassify != 3 {
		//
		//			}
		//		}
		//	}
		//}
		c.ServeSuccessJSON(map[string]interface{}{
			"patients": patients,
		})
		break
	case 3:
		var newPatients []*models.PrintPatient
		var newPatientsTwo []*models.PrintPatient

		patients, _ := service.GetBatchInspectionProjectHisPrescription(ids, recordDateTime, adminInfo.CurrentOrgId)
		for _, item := range patients {
			var newPatient *models.PrintPatient
			newPatient = item
			for index, subItem := range item.HisPrintPrescription {
				if index > 0 {
					item.HisPrintPrescription[0].HisPrescriptionProject = append(item.HisPrintPrescription[0].HisPrescriptionProject, subItem.HisPrescriptionProject...)
				}
			}
			newPatients = append(newPatients, newPatient)
		}

		for _, item := range patients {
			var newPatient *models.PrintPatient
			newPatient = item
			if len(item.HisPrintPrescription) > 0 {
				newPatient.NewHisPrintPrescription = append(newPatient.NewHisPrintPrescription, item.HisPrintPrescription[0])
				newPatientsTwo = append(newPatientsTwo, newPatient)
			}
		}

		c.ServeSuccessJSON(map[string]interface{}{
			"patients": newPatientsTwo,
		})
		break
	}
}
