package controllers

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

type IntegrationConfigApiController struct {
	BaseAuthAPIController
}

func IntegrationConfigRegistRouters() {

	beego.Router("/api/integration/patients", &IntegrationConfigApiController{}, "get:GetPatientsList")
	beego.Router("/api/patienthis/edit", &IntegrationConfigApiController{}, "post:EditPatientHis")
	beego.Router("/api/patienthis/create", &IntegrationConfigApiController{}, "post:CreatePatientHis")

	beego.Router("/api/integration/admin", &IntegrationConfigApiController{}, "get:GetAdminsList")
	beego.Router("/api/adminhis/edit", &IntegrationConfigApiController{}, "post:EditAdminHis")
	beego.Router("/api/adminhis/create", &IntegrationConfigApiController{}, "post:CreateAdminHis")

	beego.Router("/api/patienthis/getinterface", &IntegrationConfigApiController{}, "post:GetInterface")
	beego.Router("/api/patienthis/saveinterface", &IntegrationConfigApiController{}, "post:SaveInterface")
	beego.Router("/api/integration/synclist", &IntegrationConfigApiController{}, "get:GetSyncList")
	beego.Router("/api/integration/sysinspectionlist", &IntegrationConfigApiController{}, "get:GetSysInspectionList")
	beego.Router("/api/patienthis/saveinspectionsysitemid", &IntegrationConfigApiController{}, "post:SaveInspectionSysItemId")
}

func (c *IntegrationConfigApiController) SaveInspectionSysItemId() {
	adminUserInfo := c.GetAdminUserInfo()
	org_id,_ := c.GetInt64("org_id",0)
	sys_item_id,_ := c.GetInt64("sys_item_id",0)
	id,_ := c.GetInt64("id",0)
	if org_id != adminUserInfo.CurrentOrgId || sys_item_id<= 0 || id <= 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
	}

	inspection_reference := &models.InspectionReference{
		ID : id,
		SysItemId : sys_item_id,
		UpdatedTime : time.Now().Unix(),
	}
	err := service.UpdateSysItemIdByID(inspection_reference)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
	}
	c.ServeSuccessJSON(map[string]interface{}{
		"inspection_reference":  inspection_reference,
	})
	return
}

func (c *IntegrationConfigApiController) GetSysInspectionList() {
	adminUserInfo := c.GetAdminUserInfo()
	sysInspection,ownerInspection,err := service.GetSysInspectionList(adminUserInfo.CurrentOrgId)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
	}

	type InspectionStruce struct {
		ProjectName string  `gorm:"-" json:"project_name" form:"project_name"`
		ProjectId int64 `gorm:"-" json:"project_id" form:"project_id"`
		InspectionReference []*models.InspectionReference  `gorm:"-" json:"inspection_reference" form:"inspection_reference"`
	}

	sysInspec := make(map[int64]*InspectionStruce, 0)
	ownerInspec := make(map[int64]*InspectionStruce, 0)

	

	for _, item := range sysInspection {
		result := sysInspec[item.ProjectId]
		if result == nil {
			result = new(InspectionStruce)
			result.ProjectName = item.ProjectName
			result.ProjectId = item.ProjectId
		}
		result.InspectionReference = append(result.InspectionReference, item)
		sysInspec[item.ProjectId] = result
	}

	for _, oitem := range ownerInspection {
		oresult := ownerInspec[oitem.ProjectId]
		if oresult == nil {
			oresult = new(InspectionStruce)
			oresult.ProjectName = oitem.ProjectName
			oresult.ProjectId = oitem.ProjectId
		}
		oresult.InspectionReference = append(oresult.InspectionReference, oitem)
		ownerInspec[oitem.ProjectId] = oresult
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"sysInspec":  sysInspec,
		"ownerInspec": ownerInspec,
	})
	return
}

func (c *IntegrationConfigApiController) GetSyncList() {
	page, _ := c.GetInt64("page", 1)
	limit, _ := c.GetInt64("limit", 10)

	if page <= 0 {
		page = 1
	}
	if limit <= 0 {
		limit = 10
	}

	adminUserInfo := c.GetAdminUserInfo()
	patients, total, _ := service.GetSyncList(adminUserInfo.CurrentOrgId, page, limit)

	c.ServeSuccessJSON(map[string]interface{}{
		"list":  patients,
		"total": total,
	})
	return
}

func (c *IntegrationConfigApiController) SaveInterface() {
	adminUserInfo := c.GetAdminUserInfo()
	ID,_ := c.GetInt64("id",0)
	OrgId := adminUserInfo.CurrentOrgId
	Creater := adminUserInfo.AdminUser.Id 
	Pattern,_ := c.GetInt("pattern",0)		
	Dbhost := c.GetString("dbhost") 
	Dbuser := c.GetString("dbuser")
	Dbpassword := c.GetString("dbpassword") 
	Dbname := c.GetString("dbname")
	InterfaceUrl := c.GetString("interface_url") 
	InterFaceToken := c.GetString("interface_token")
	AllowIp := c.GetString("allow_ip")
	AllowToken := c.GetString("allow_token")		
	SyncFrequency,_ := c.GetInt("sync_frequency")
	Status := 1
	UpdatedTime :=  time.Now().Unix()
	interfaceinfo := &models.MiddleInterface{
		ID  		: ID,
	OrgId   		: OrgId	,
	Creater   		: Creater	,
	Pattern 		: Pattern	,
	Dbhost 			: Dbhost	,
	Dbuser 			: Dbuser	,
	Dbpassword 		: Dbpassword	,
	Dbname 			: Dbname	,
	InterfaceUrl 	: InterfaceUrl	,
	InterFaceToken 	: InterFaceToken	,
	AllowIp 		: AllowIp	,
	AllowToken 		: AllowToken	,
	SyncFrequency 	: SyncFrequency	,
	Status			: Status	,
	UpdatedTime     : UpdatedTime	,
	}
	if ID <= 0 {
		interfaceinfo.CreatedTime =  time.Now().Unix()
	}
	err:= service.SaveInterface(interfaceinfo)

	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"interfaceinfo":  interfaceinfo,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
	}
	return
}

func (c *IntegrationConfigApiController) GetInterface() {
	adminUserInfo := c.GetAdminUserInfo()
	interfaceinfo, _ := service.GetInterface(adminUserInfo.CurrentOrgId)
	c.ServeSuccessJSON(map[string]interface{}{
		"interfaceinfo":  interfaceinfo,
	})
	return

}

func (c *IntegrationConfigApiController) GetPatientsList() {
	page, _ := c.GetInt64("page", 1)
	limit, _ := c.GetInt64("limit", 10)

	if page <= 0 {
		page = 1
	}
	if limit <= 0 {
		limit = 10
	}

	adminUserInfo := c.GetAdminUserInfo()
	patients, total, _ := service.GetIntegrationPatientList(adminUserInfo.CurrentOrgId, page, limit)

	c.ServeSuccessJSON(map[string]interface{}{
		"list":  patients,
		"total": total,
	})
	return
}

func (c *IntegrationConfigApiController) EditPatientHis() {
	his_user_id := c.GetString("his_user_id")
	id, _ := c.GetInt64("id", 0)

	adminUserInfo := c.GetAdminUserInfo()

	total, _ := service.FindHisPatientByHisId(adminUserInfo.CurrentOrgId, his_user_id)

	if total > 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeHisIdExist)
		return

	}

	err := service.UpdatePatientsHis(adminUserInfo.CurrentOrgId, his_user_id, id)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"his_user_id": his_user_id,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)

	}
	return

}

func (c *IntegrationConfigApiController) CreatePatientHis() {
	his_user_id := c.GetString("his_user_id")
	id, _ := c.GetInt64("id", 0)

	adminUserInfo := c.GetAdminUserInfo()
	patient, _ := service.FindVMPatientById(adminUserInfo.CurrentOrgId, id)

	total, _ := service.FindHisPatientByHisId(adminUserInfo.CurrentOrgId, his_user_id)

	if total > 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeHisIdExist)
		return

	}

	hisPatient := &models.HisPatients{
		UserOrgId:          adminUserInfo.CurrentOrgId,
		UserId:             patient.UserId,
		Avatar:             patient.Avatar,
		PatientType:        patient.PatientType,
		DialysisNo:         patient.DialysisNo,
		AdmissionNumber:    patient.AdmissionNumber,
		Source:             patient.Source,
		Lapseto:            patient.Lapseto,
		PartitionId:        patient.PartitionId,
		BedId:              patient.BedId,
		Name:               patient.Name,
		Alias:              patient.Alias,
		Gender:             patient.Gender,
		Nation:             patient.Nation,
		NativePlace:        patient.NativePlace,
		MaritalStatus:      patient.MaritalStatus,
		IdCardNo:           patient.IdCardNo,
		Birthday:           patient.Birthday,
		ReimbursementWayId: patient.ReimbursementWayId,
		HealthCareType:     patient.HealthCareType,
		HealthCareNo:       patient.HealthCareNo,
		HealthCareDueDate:  patient.HealthCareDueDate,
		Height:             patient.Height,
		BloodType:          patient.BloodType,
		Rh:                 patient.Rh,
		HealthCareDueAlertDate:       patient.HealthCareDueAlertDate,
		EducationLevel:               patient.EducationLevel,
		Profession:                   patient.Profession,
		Phone:                        patient.Phone,
		HomeTelephone:                patient.HomeTelephone,
		RelativePhone:                patient.RelativePhone,
		HomeAddress:                  patient.HomeAddress,
		WorkUnit:                     patient.WorkUnit,
		UnitAddress:                  patient.UnitAddress,
		ReceivingDate:                patient.ReceivingDate,
		IsHospitalFirstDialysis:      patient.IsHospitalFirstDialysis,
		FirstDialysisDate:            patient.FirstDialysisDate,
		FirstDialysisHospital:        patient.FirstDialysisHospital,
		PredialysisCondition:         patient.PredialysisCondition,
		PreHospitalDialysisFrequency: patient.PreHospitalDialysisFrequency,
		PreHospitalDialysisTimes:     patient.PreHospitalDialysisTimes,
		HospitalFirstDialysisDate:    patient.HospitalFirstDialysisDate,
		InductionPeriod:              patient.InductionPeriod,
		InitialDialysis:              patient.InitialDialysis,
		TotalDialysis:                patient.TotalDialysis,
		AttendingDoctorId:            patient.AttendingDoctorId,
		HeadNurseId:                  patient.HeadNurseId,
		Evaluate:                     patient.Evaluate,
		Diagnose:                     patient.Diagnose,
		Remark:                       patient.Remark,
		RegistrarsId:                 patient.RegistrarsId,
		Registrars:                   patient.Registrars,
		QrCode:                       patient.QrCode,
		BindingState:                 patient.BindingState,
		PatientComplains:             patient.PatientComplains,
		PresentHistory:               patient.PresentHistory,
		PastHistory:                  patient.PastHistory,
		Temperature:                  patient.Temperature,
		Pulse:                        patient.Pulse,
		Respiratory:                  patient.Respiratory,
		Sbp:                          patient.SBP,
		Dbp:                          patient.DBP,
		Status:                       1,
		CreatedTime:                  time.Now().Unix(),
		UpdatedTime:                  time.Now().Unix(),
		Age:                          patient.Age,
		InfectiousNextRecordTime: patient.InfectiousNextRecordTime,
		IsInfectious:             patient.IsInfectious,
		RemindCycle:              patient.RemindCycle,
		ResponseResult:           patient.ResponseResult,
		IsOpenRemind:             patient.IsOpenRemind,
		DialysisAge:              patient.DialysisAge,
		ExpenseKind:              patient.ExpenseKind,
		TellPhone:                patient.TellPhone,
		FirstTreatmentDate:       patient.FirstTreatmentDate,
		ContactName:              patient.ContactName,
		HisUserId:                his_user_id,
		XtPatientId:              patient.ID,
	}

	err := service.CreatePatientsHis(hisPatient)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"patient": hisPatient,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)

	}
	return

}

func (c *IntegrationConfigApiController) GetAdminsList() {
	page, _ := c.GetInt("page", 1)
	limit, _ := c.GetInt("limit", 10)

	if page <= 0 {
		page = 1
	}
	if limit <= 0 {
		limit = 10
	}

	adminUserInfo := c.GetAdminUserInfo()

	viewModels, total, getAdminsErr := service.GetAdminUsers(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, page, limit)
	if getAdminsErr != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	c.ServeSuccessJSON(map[string]interface{}{
		"admins":      viewModels,
		"total_count": total,
	})

	return

}

func (c *IntegrationConfigApiController) EditAdminHis() {
	his_user_id := c.GetString("his_user_id")
	id, _ := c.GetInt64("id", 0)

	adminUserInfo := c.GetAdminUserInfo()

	total, _ := service.FindHisAdminByHisId(adminUserInfo.CurrentOrgId, his_user_id, adminUserInfo.CurrentAppId)

	if total > 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeHisIdExist)
		return

	}

	err := service.UpdateAdminsHis(adminUserInfo.CurrentOrgId, his_user_id, id)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"his_user_id": his_user_id,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)

	}
	return

}

func (c *IntegrationConfigApiController) CreateAdminHis() {
	his_user_id := c.GetString("his_user_id")
	id, _ := c.GetInt64("id", 0)

	adminUserInfo := c.GetAdminUserInfo()
	adminRole, _ := service.FindVMAdminRoleById(adminUserInfo.CurrentOrgId, id, adminUserInfo.CurrentAppId)

	total, _ := service.FindHisAdminByHisId(adminUserInfo.CurrentOrgId, his_user_id, adminUserInfo.CurrentAppId)

	if total > 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeHisIdExist)
		return

	}

	hisAdminRole := &models.HisUserAdminRole{
		OrgId:       adminUserInfo.CurrentOrgId,
		AdminUserId: adminRole.AdminUserId,
		AppId:       adminRole.AppId,
		RoleId:      adminRole.RoleId,
		UserName:    adminRole.UserName,
		Avatar:      adminRole.Avatar,
		UserType:    adminRole.UserType,
		UserTitle:   adminRole.UserTitle,
		Intro:       adminRole.Intro,
		Status:      1,
		Ctime:       time.Now().Unix(),
		Mtime:       time.Now().Unix(),
		XtRoleId:    adminRole.ID,
		HisUserId:   his_user_id,
	}

	err := service.CreateAdminsHis(hisAdminRole)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"his_role": hisAdminRole,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)

	}
	return

}
