package controllers

import (
	"Xcx_New/enums"
	"Xcx_New/models"
	"Xcx_New/service"
	"Xcx_New/utils"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/jinzhu/gorm"
	"strconv"
	"strings"
	"time"
)

type DoctorsApiController struct {
	BaseAuthAPIController
}

func DoctorApiRegistRouters() {
	beego.Router("/api/alldoctors", &DoctorsApiController{}, "get:GetAllDoctorAndNurse")
	beego.Router("/api/admin/users", &DoctorsApiController{}, "get:GetAllAdminUsers")
	beego.Router("/api/patient/getdryweightdata", &DoctorsApiController{}, "Get:GetDryWeightData")
	beego.Router("/api/patient/getAllDoctor", &DoctorsApiController{}, "Get:GetAllDoctor")
	beego.Router("/api/patient/updatedryweightdata", &DoctorsApiController{}, "Post:UpdatedDryWeightData")
	beego.Router("/api/patient/getalldata", &DoctorsApiController{}, "Get:GetAllData")
	beego.Router("/api/paients/getdryweightdetail", &DoctorsApiController{}, "Get:GetDryWeightDetail")
	beego.Router("/api/patients/modifydryweightdata", &DoctorsApiController{}, "Get:ModifydryWeightData")
	beego.Router("/api/patient/deletedryweight", &DoctorsApiController{}, "Delete:DeleteDryWeight")
	beego.Router("/api/schedule/advices", &DoctorsApiController{}, "Get:ScheduleAdvices")
	beego.Router("/api/schedule/getdoctoradvicecount", &DoctorsApiController{}, "Get:GetDoctorAdviceCount")
	beego.Router("/api/patient/savevasularaccess", &DoctorsApiController{}, "Get:SaveVasularAccess")
	beego.Router("/api/patient/getallvascualraccesslist", &DoctorsApiController{}, "Get:GetAllVacualAccessList")
	beego.Router("/api/patient/getvascularaccessbydetial", &DoctorsApiController{}, "Get:GetVascularAccessByDetail")
	beego.Router("/api/patient/updatevasularaccess", &DoctorsApiController{}, "Get:UpdateVasularAccess")
	beego.Router("/api/patient/deletevascularaccess", &DoctorsApiController{}, "Get:DeleteVasularAccess")
	beego.Router("/api/patient/savepasswayassessment", &DoctorsApiController{}, "Get:SavePassWayAssessment")
	beego.Router("/api/patient/getallpasswayassessment", &DoctorsApiController{}, "Get:GetAllPassWayAssessment")
	beego.Router("/api/patient/getpasswayassmentbyid", &DoctorsApiController{}, "Get:GetPasswayAssesmentById")
	beego.Router("/api/patient/updatepasswayassesment", &DoctorsApiController{}, "Get:UpdatePassWayAssesment")
	beego.Router("/api/patient/deletepasswayassessment", &DoctorsApiController{}, "Get:DeleteWayAssessment")
	beego.Router("/api/patient/getaccesslist", &DoctorsApiController{}, "Get:GetAccessList")

	//阶段小结路由
	beego.Router("/api/patient/getinspectionmajoritem", &DoctorsApiController{}, "Get:GetInspectionMajorItem")
	beego.Router("/api/patient/getinspectiondetail", &DoctorsApiController{}, "Get:GetInspectionDetailByProject")
	beego.Router("/api/patient/getinspectionitemlist", &DoctorsApiController{}, "Get:GetInspectionItemlist")
	beego.Router("/api/patient/getinitdatelist", &DoctorsApiController{}, "Get:GetInitDateList")
	beego.Router("/api/patient/savecreationinspection", &DoctorsApiController{}, "Post:SaveCreationInspection")
	beego.Router("/api/patient/getemlatesummarylist", &DoctorsApiController{}, "Get:GetTemplateSummaryList")
	beego.Router("/api/patient/gettemplatesummarydetail", &DoctorsApiController{}, "Get:GetTemplateSummaryDetail")
	beego.Router("/api/patient/gettemplatesummaryprintdetail", &DoctorsApiController{}, "Get:GetTemplateSummaryPrintDetail")
	beego.Router("/api/patient/updatetemplatesummary", &DoctorsApiController{}, "Post:UpdateTempalteSummary")
	beego.Router("/api/patient/deletesummary", &DoctorsApiController{}, "Get:DeleteSummary")
}

func (c *DoctorsApiController) ScheduleAdvices() {
	schedualDate := c.GetString("date")
	adviceType, _ := c.GetInt("advice_type")
	patientType, _ := c.GetInt("patient_type")
	delivery_way := c.GetString("delivery_way")
	schedule_type, _ := c.GetInt64("schedule_type")
	partition_type, _ := c.GetInt64("partition_type")
	if adviceType != 1 && adviceType != 3 && adviceType != 2 {
		adviceType = 0
	}

	if patientType != 1 && patientType != 2 {

		patientType = 0
	}

	date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
	if parseDateErr != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	adminUserInfo := c.GetAdminUserInfo()
	orgID := adminUserInfo.CurrentOrgId

	scheduals, err := service.MobileGetScheduleDoctorAdvicesOne(orgID, date.Unix(), adviceType, patientType, adminUserInfo.AdminUser.Id, delivery_way, schedule_type, partition_type)
	hisAdvices, _ := service.GetHisDoctorAdvicesOne(orgID, date.Unix(), delivery_way, schedule_type, partition_type)

	project, _ := service.GetPCHisPrescriptionProject(orgID, date.Unix(), delivery_way, patientType, partition_type)

	config, _ := service.GetHisDoctorConfig(orgID)
	project_config, _ := service.GetHisProjectConfig(orgID)

	adminUser, _ := service.GetAllAdminUsers(orgID, adminUserInfo.CurrentAppId)
	if err != nil {
		c.ErrorLog("获取排班信息失败:%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
	} else {
		filtedScheduals := []*service.MScheduleDoctorAdviceVM{}
		for _, schedual := range scheduals {
			if len(schedual.DoctorAdvices) > 0 {
				filtedScheduals = append(filtedScheduals, schedual)
			}
		}
		c.ServeSuccessJSON(map[string]interface{}{
			"scheduals":      filtedScheduals,
			"adminUser":      adminUser,
			"hisAdvices":     hisAdvices,
			"config":         config,
			"project_config": project_config,
			"project":        project,
		})
	}
}

func (c *DoctorsApiController) GetAllDoctorAndNurse() {

	adminUserInfo := c.GetAdminUserInfo()
	doctors, nursers, _ := service.GetAllDoctorAndNurse(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId)

	c.ServeSuccessJSON(map[string]interface{}{
		"doctors": doctors,
		"nursers": nursers,
	})
	return
}
func (c *DoctorsApiController) GetAllAdminUsers() {

	adminUserInfo := c.GetAdminUserInfo()
	users, _ := service.GetAllAdminUsersTwo(adminUserInfo.CurrentOrgId)
	c.ServeSuccessJSON(map[string]interface{}{
		"users": users,
	})
	return
}

func (c *DoctorsApiController) GetDryWeightData() {
	adminUserInfo := c.GetAdminUserInfo()
	orgid := adminUserInfo.CurrentOrgId

	patientid, _ := c.GetInt64("patientid")
	fmt.Println("patientid", patientid)
	id := adminUserInfo.AdminUser.Id
	fmt.Println("id", id)
	recordDateStr := time.Now().Format("2006-01-02")
	recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
	fmt.Scan("parseDateErr", parseDateErr)
	nowtime := recordDate.Unix()
	fmt.Println("nowtime", nowtime)
	pre, err := service.GetDryWeightByPatientId(patientid, orgid)
	fmt.Println("错误", err)
	c.ServeSuccessJSON(map[string]interface{}{
		"pre": pre,
	})
}

func (c *DoctorsApiController) GetAllDoctor() {
	adminUserInfo := c.GetAdminUserInfo()
	orgid := adminUserInfo.CurrentOrgId
	appid := adminUserInfo.CurrentAppId
	fmt.Println("appid", appid)
	appRole, err := service.GetAllDoctor(orgid, appid)
	fmt.Println("appRole", appRole)
	fmt.Println("错误", err)
	c.ServeSuccessJSON(map[string]interface{}{
		"appRole": appRole,
	})
}

func (c *DoctorsApiController) UpdatedDryWeightData() {
	adminUserInfo := c.GetAdminUserInfo()
	orgid := adminUserInfo.CurrentOrgId
	userid := adminUserInfo.AdminUser.Id
	fmt.Println("userid", userid)
	dry_weight, _ := c.GetFloat("dry_weight")
	fmt.Println("dry_weight", dry_weight)
	doctors, _ := c.GetInt64("doctors")
	fmt.Println("doctors", doctors)
	remarks := c.GetString("remarks")
	fmt.Println("remarks", remarks)
	patientid, _ := c.GetInt64("patient_id")
	fmt.Println("patientid", patientid)
	//透前数据
	dryweight, _ := c.GetFloat("dryweight")
	fmt.Println("dryweight", dryweight)
	var weight = dryweight - dry_weight
	weights := fmt.Sprintf("%.1f", weight)
	//weights := strconv.FormatFloat(sprintf, 'E', -1, 64)

	fmt.Println("weight", weights)
	fmt.Println("weight", weight)
	var sum string
	dryWeight, errcode := service.QueryDryWeight(orgid, patientid)
	fmt.Println("errcode", errcode)
	fmt.Println("dryWeight", dryWeight)
	if errcode == gorm.ErrRecordNotFound {
		sum = "/"
		patientDryweight := models.SgjPatientDryweight{
			DryWeight:     dry_weight,
			Creator:       doctors,
			Remakes:       remarks,
			AdjustedValue: sum,
			PatientId:     patientid,
			Ctime:         time.Now().Unix(),
			UserOrgId:     orgid,
			Status:        1,
			UserId:        userid,
		}

		err := service.CreatePatientWeight(&patientDryweight)
		fmt.Println("err", err)
		c.ServeSuccessJSON(map[string]interface{}{
			"patientDryweight": patientDryweight,
		})
		return
	}
	fmt.Println("sum", sum)
	if weight == 0 {
		sum = "/"
	}
	if weight > 0 {
		sum = weights + "(" + "下调" + ")"

	}
	if weight < 0 {
		var sums = dry_weight - dryweight
		float := fmt.Sprintf("%.1f", sums)
		//float := strconv.FormatFloat(sums, 'E', -1, 64)
		sum = float + "(" + "上调" + ")"
	}

	patientDryweight := models.SgjPatientDryweight{
		DryWeight:     dry_weight,
		Creator:       doctors,
		Remakes:       remarks,
		AdjustedValue: sum,
		PatientId:     patientid,
		Ctime:         time.Now().Unix(),
		UserOrgId:     orgid,
		Status:        1,
		UserId:        userid,
	}

	err := service.CreatePatientWeight(&patientDryweight)
	//sgjPatientDryweight, _ := service.GetLastData(orgid)
	recordDateStr := time.Now().Format("2006-01-02")
	recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
	fmt.Scan("parseDateErr", parseDateErr)
	nowtime := recordDate.Unix()
	fmt.Println("nowtime", nowtime)
	//prescription := models.PredialysisEvaluation{
	//	DryWeight: dryweight,
	//}
	//errors := service.UpdateDialysisPrescription( sgjPatientDryweight.PatientId, sgjPatientDryweight.UserOrgId, sgjPatientDryweight.DryWeight, prescription)
	//fmt.Println("error",errors)
	fmt.Println("err", err)
	fmt.Println("patientdryweight", patientDryweight)
	c.ServeSuccessJSON(map[string]interface{}{
		"patientDryweight": patientDryweight,
	})
}

func (c *DoctorsApiController) GetAllData() {
	id, _ := c.GetInt64("id")
	page, _ := c.GetInt64("page")
	fmt.Println("page", page)
	limit, _ := c.GetInt64("limit")
	fmt.Println("limit", limit)

	fmt.Println("id", id)
	adminUserInfo := c.GetAdminUserInfo()
	orgid := adminUserInfo.CurrentOrgId
	dry, total, _ := service.GetAllData(orgid, id, page, limit)

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

func (c *DoctorsApiController) GetDryWeightDetail() {

	id, _ := c.GetInt64("id")
	dryweight, _ := service.GetDryWeightDetailById(id)
	c.ServeSuccessJSON(map[string]interface{}{
		"dryweight": dryweight,
	})
}

func (c *DoctorsApiController) ModifydryWeightData() {

	adjustvalue := c.GetString("adjustvalue")

	creator, _ := c.GetInt64("creator")

	dryweight, _ := c.GetInt64("dryweight")
	dry := strconv.FormatInt(dryweight, 10)
	dry_weight, _ := strconv.ParseFloat(dry, 64)
	id, _ := c.GetInt64("id")

	remark := c.GetString("remark")

	patientDryweight := models.SgjPatientDryweight{
		AdjustedValue: adjustvalue,
		Creator:       creator,
		DryWeight:     dry_weight,
		Remakes:       remark,
	}
	service.ModifyDryWeightData(&patientDryweight, id)
	c.ServeSuccessJSON(map[string]interface{}{
		"patientDryweight": patientDryweight,
	})
}

func (c *DoctorsApiController) DeleteDryWeight() {

	id, _ := c.GetInt64("id")
	service.DeleteDryWeight(id)
	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "ok"
	c.ServeSuccessJSON(returnData)
	return
}

func (c *DoctorsApiController) GetDoctorAdviceCount() {
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	start_time := c.GetString("start_time")
	startTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)

	end_time := c.GetString("end_time")
	endTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 00:00:00", loc)

	delive_way := c.GetString("delive_way")
	adminUserInfo := c.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	list, _ := service.GetDoctorAdviceCount(startTime.Unix(), endTime.Unix(), delive_way, orgId)
	if len(list) == 0 {
		list, _ := service.GetHisDoctorAdviceCount(startTime.Unix(), endTime.Unix(), delive_way, orgId)
		c.ServeSuccessJSON(map[string]interface{}{
			"list": list,
		})
	} else {
		c.ServeSuccessJSON(map[string]interface{}{
			"list": list,
		})
	}

}

func (this *DoctorsApiController) SaveVasularAccess() {

	access_project, _ := this.GetInt64("access_project")
	blood_access_part_id := this.GetString("blood_access_part_id")
	blood_access_part_opera_id := this.GetString("blood_access_part_opera_id")
	first_start_time := this.GetString("first_start_time")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	firstStartTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", first_start_time+" 00:00:00", loc)
	inflow_pass := this.GetString("inflow_pass")
	remark := this.GetString("remark")
	start_time := this.GetString("start_time")
	startTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	stop_reason := this.GetString("stop_reason")
	user_status, _ := this.GetInt64("user_status")
	stop_time := this.GetString("stop_time")
	stopTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", stop_time+" 00:00:00", loc)
	patient_id, _ := this.GetInt64("patient_id")
	other_vascular := this.GetString("other_vascular")
	ci_type, _ := this.GetInt64("ci_type")
	blood_cultupe, _ := this.GetInt64("blood_cultupe")
	sequelae_type, _ := this.GetInt64("sequelae_type")
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	creator := adminUserInfo.AdminUser.Id

	//查询改日期是否存在
	access := models.XtPatientVascularAccess{
		AccessProject:          access_project,
		BloodAccessPartId:      blood_access_part_id,
		BloodAccessPartOperaId: blood_access_part_opera_id,
		FirstStartTime:         firstStartTime.Unix(),
		InflowPass:             inflow_pass,
		Remark:                 remark,
		StartTime:              startTime.Unix(),
		StopReason:             stop_reason,
		UserStatus:             user_status,
		Creator:                creator,
		UserOrgId:              orgId,
		Status:                 1,
		Ctime:                  time.Now().Unix(),
		StopTime:               stopTime.Unix(),
		PatientId:              patient_id,
		OtherVascular:          other_vascular,
		CiType:                 ci_type,
		BloodCultupe:           blood_cultupe,
		SequelaeType:           sequelae_type,
	}
	err := service.SaveVascularAccess(&access)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"access": access,
		})
		return
		//_, errcode := service.GetDialysisDateByDate(startTime.Unix(), patient_id, orgId)
		//if errcode == gorm.ErrRecordNotFound {
		//	access := models.XtPatientVascularAccess{
		//		AccessProject:          access_project,
		//		BloodAccessPartId:      blood_access_part_id,
		//		BloodAccessPartOperaId: blood_access_part_opera_id,
		//		FirstStartTime:         firstStartTime.Unix(),
		//		InflowPass:             inflow_pass,
		//		Remark:                 remark,
		//		StartTime:              startTime.Unix(),
		//		StopReason:             stop_reason,
		//		UserStatus:             user_status,
		//		Creator:                creator,
		//		UserOrgId:              orgId,
		//		Status:                 1,
		//		Ctime:                  time.Now().Unix(),
		//		StopTime:               stopTime.Unix(),
		//		PatientId:              patient_id,
		//		OtherVascular:          other_vascular,
		//		CiType:                 ci_type,
		//		BloodCultupe:           blood_cultupe,
		//		SequelaeType:           sequelae_type,
		//	}
		//	err := service.SaveVascularAccess(&access)
		//	if err == nil {
		//		this.ServeSuccessJSON(map[string]interface{}{
		//			"access": access,
		//		})
		//		return
		//	}
		//} else if errcode == nil {
		//	this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
		//	return
	}

}

func (this *DoctorsApiController) GetAllVacualAccessList() {

	limit, _ := this.GetInt64("limit")
	page, _ := this.GetInt64("page")
	patient_id, _ := this.GetInt64("patient_id")
	orgId := this.GetAdminUserInfo().CurrentOrgId
	appId := this.GetAdminUserInfo().CurrentAppId
	list, total, err := service.GetAllVacualAccessList(orgId, limit, page, patient_id)
	doctor, err := service.GetAllDoctor(orgId, appId)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"list":   list,
			"total":  total,
			"doctor": doctor,
		})
		return
	}
}

func (this *DoctorsApiController) GetVascularAccessByDetail() {

	id, _ := this.GetInt64("id")

	accessDetail, err := service.GetVasularAccessByDetail(id)
	orgId := this.GetAdminUserInfo().CurrentOrgId
	appId := this.GetAdminUserInfo().CurrentAppId
	doctor, err := service.GetAllDoctor(orgId, appId)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"accessDetail": accessDetail,
			"doctor":       doctor,
		})
		return
	}
}

func (this *DoctorsApiController) UpdateVasularAccess() {
	id, _ := this.GetInt64("id")
	access_project, _ := this.GetInt64("access_project")
	blood_access_part_id := this.GetString("blood_access_part_id")
	blood_access_part_opera_id := this.GetString("blood_access_part_opera_id")
	first_start_time := this.GetString("first_start_time")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	firstStartTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", first_start_time+" 00:00:00", loc)
	inflow_pass := this.GetString("inflow_pass")
	remark := this.GetString("remark")
	start_time := this.GetString("start_time")
	startTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	stop_reason := this.GetString("stop_reason")
	user_status, _ := this.GetInt64("user_status")
	stop_time := this.GetString("stop_time")
	stopTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", stop_time+" 00:00:00", loc)
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	creator := adminUserInfo.AdminUser.Id
	patientId, _ := this.GetInt64("patient_id")
	other_vascular := this.GetString("other_vascular")
	ci_type, _ := this.GetInt64("ci_type")
	blood_cultupe, _ := this.GetInt64("blood_cultupe")
	sequelae_type, _ := this.GetInt64("sequelae_type")
	access := models.XtPatientVascularAccess{
		AccessProject:          access_project,
		BloodAccessPartId:      blood_access_part_id,
		BloodAccessPartOperaId: blood_access_part_opera_id,
		FirstStartTime:         firstStartTime.Unix(),
		InflowPass:             inflow_pass,
		Remark:                 remark,
		StartTime:              startTime.Unix(),
		StopReason:             stop_reason,
		UserStatus:             user_status,
		Modify:                 creator,
		UserOrgId:              orgId,
		Status:                 1,
		StopTime:               stopTime.Unix(),
		OtherVascular:          other_vascular,
		CiType:                 ci_type,
		BloodCultupe:           blood_cultupe,
		SequelaeType:           sequelae_type,
		PatientId:              patientId,
	}

	err := service.UpdateVascularAccess(&access, id)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"access": access,
		})
		return
	}
	//_, errcode := service.GetDialysisDateByDateOne(startTime.Unix(), patientId, orgId, id)
	//if errcode == gorm.ErrRecordNotFound {
	//	err := service.UpdateVascularAccess(&access, id)
	//	if err == nil {
	//		this.ServeSuccessJSON(map[string]interface{}{
	//			"access": access,
	//		})
	//		return
	//	}
	//} else if errcode == nil {
	//	this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
	//	return
	//}

}

func (this *DoctorsApiController) DeleteVasularAccess() {
	id, _ := this.GetInt64("id")
	err := service.DeleteVasularAccess(id)
	fmt.Println(err)
	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "ok"
	this.ServeSuccessJSON(returnData)
	return
}

func (this *DoctorsApiController) SavePassWayAssessment() {

	blood_dealwidth := this.GetString("blood_dealwith")
	blood_project := this.GetString("blood_project")
	blood_result := this.GetString("blood_result")
	creator, _ := this.GetInt64("creator")
	parent_id, _ := this.GetInt64("parent_id")
	patient_id, _ := this.GetInt64("patient_id")
	start_time := this.GetString("start_time")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	startTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	modify := this.GetAdminUserInfo().AdminUser.Id
	orgId := this.GetAdminUserInfo().CurrentOrgId
	assessment := models.XtPatientPasswayAssessment{
		StartTime:     startTime.Unix(),
		BloodDealwith: blood_dealwidth,
		BloodProject:  blood_project,
		BloodResult:   blood_result,
		Creator:       creator,
		PatientId:     patient_id,
		ParentId:      parent_id,
		Modify:        modify,
		UserOrgId:     orgId,
		Status:        1,
		Ctime:         time.Now().Unix(),
	}

	err := service.CreatePatientWayAssessment(&assessment)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"assessment": assessment,
		})
		return
	}
}

func (this *DoctorsApiController) GetAllPassWayAssessment() {

	patient_id, _ := this.GetInt64("patient_id")
	parent_id, _ := this.GetInt64("parent_id")
	page, _ := this.GetInt64("page")
	limit, _ := this.GetInt64("limit")
	adminUserInfo := this.GetAdminUserInfo()
	list, total, err := service.GetAllPassWayAssessment(parent_id, patient_id, page, limit, adminUserInfo.CurrentOrgId)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"list":  list,
			"total": total,
		})
		return
	}
}

func (this *DoctorsApiController) GetPasswayAssesmentById() {

	id, _ := this.GetInt64("id")
	assessment, err := service.GetPasswayAssesmentById(id)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"assessment": assessment,
		})
		return
	}
}

func (this *DoctorsApiController) UpdatePassWayAssesment() {
	id, _ := this.GetInt64("id")
	blood_dealwidth := this.GetString("blood_dealwith")
	blood_project := this.GetString("blood_project")
	blood_result := this.GetString("blood_result")
	creator, _ := this.GetInt64("creator")
	start_time := this.GetString("start_time")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	startTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	modify := this.GetAdminUserInfo().AdminUser.Id
	assessment := models.XtPatientPasswayAssessment{
		BloodResult:   blood_result,
		BloodDealwith: blood_dealwidth,
		BloodProject:  blood_project,
		Creator:       creator,
		StartTime:     startTime.Unix(),
		Modify:        modify,
	}
	err := service.UpdatePassWayAssesment(&assessment, id)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"assessment": assessment,
		})
		return
	}
}

func (this *DoctorsApiController) DeleteWayAssessment() {

	id, _ := this.GetInt64("id")
	err := service.DeleteWayAssessment(id)
	fmt.Println(err)
	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "ok"
	this.ServeSuccessJSON(returnData)
	return
}

func (this *DoctorsApiController) GetAccessList() {

	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	//血管通路
	list, err := service.GetAccessList(orgId)
	blood_access_part_opera, err := service.GetParentAccessList(orgId, list.ID)

	//血管通路部位
	access, err := service.GetBloodAccess(orgId)
	blood_access_part, err := service.GetParentAccessList(orgId, access.ID)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"blood_access_part_opera": blood_access_part_opera,
			"blood_access_part":       blood_access_part,
		})
		return
	}
}

func (this *DoctorsApiController) GetInspectionMajorItem() {

	other_start_time := this.GetString("other_start_time")
	last_time := this.GetString("last_time")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	startTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", other_start_time+" 23:59:59", loc)
	lastTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", last_time+" 00:00:00", loc)
	patient_id, _ := this.GetInt64("patient_id")
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	list, err := service.GetInspectionMajorItem(startTime.Unix(), lastTime.Unix(), orgId, patient_id)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"list": list,
		})
		return
	}
}

func (this *DoctorsApiController) GetInspectionDetailByProject() {

	project_id, _ := this.GetInt64("project_id")
	patient_id, _ := this.GetInt64("patient_id")
	inspect_date, _ := this.GetInt64("inspect_date")
	orgId := this.GetAdminUserInfo().CurrentOrgId
	list, err := service.GetInspectionDetailByProject(project_id, patient_id, inspect_date, orgId)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"list": list,
		})
		return
	}
}

func (this *DoctorsApiController) GetInspectionItemlist() {
	patient_id, _ := this.GetInt64("patient_id")
	ids := this.GetString("ids")
	inspect_date := this.GetString("inspect_date")
	idSplit := strings.Split(ids, ",")
	indateSplit := strings.Split(inspect_date, ",")
	list, err := service.GetInspectionItemlist(patient_id, indateSplit, idSplit)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"list": list,
		})
		return
	}
}

func (this *DoctorsApiController) GetInitDateList() {
	patient_id, _ := this.GetInt64("patient_id")
	start_time := this.GetString("start_time")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	startTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	end_time := this.GetString("end_time")
	endTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
	fmt.Println("endtime2323232233223232332", endTime)
	prescription_list, _ := service.GetDialysisPrescriptionDataList(patient_id, startTime.Unix(), endTime.Unix())
	befor_list, err := service.GetDialysisBeforInitDateList(patient_id, startTime.Unix(), endTime.Unix())
	after_list, err := service.GetDialysisAssementAfter(patient_id, startTime.Unix(), endTime.Unix())
	orgId := this.GetAdminUserInfo().CurrentOrgId
	//统计透析次数
	modelist, err := service.GetDialysisDialysisMode(patient_id, startTime.Unix(), endTime.Unix(), orgId)

	docList, _ := service.GetAllDoctorThree(orgId)
	stockType, err := service.GetStockType(orgId)

	summaryList, err := service.GetTemplateSummary(orgId)
	planList, err := service.GetTemplatePlan(orgId)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"beforlist":         befor_list,
			"prescription_list": prescription_list,
			"after_list":        after_list,
			"modelist":          modelist,
			"docList":           docList,
			"stockType":         stockType,
			"summaryList":       summaryList,
			"planList":          planList,
		})
		return
	}
}

func (this *DoctorsApiController) SaveCreationInspection() {

	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	title := dataBody["title"].(string)
	dryWeight := dataBody["dry_weight"].(string)
	dry_weight, _ := strconv.ParseFloat(dryWeight, 64)
	dialysis_count := int64(dataBody["dialysis_count"].(float64))
	hd_count := int64(dataBody["hd_count"].(float64))
	hdf_count := int64(dataBody["hdf_count"].(float64))
	hp_count := int64(dataBody["hp_count"].(float64))
	other_count := int64(dataBody["other_count"].(float64))
	dialzer_apparatus := dataBody["dialzer_apparatus"].(string)
	perfusion_apparatus := dataBody["perfusion_apparatus"].(string)
	anticoagulant := int64(dataBody["anticoagulant"].(float64))
	kaliumstr := dataBody["kalium"].(string)
	kalium, _ := strconv.ParseFloat(kaliumstr, 64)
	autunitestr := dataBody["autunite"].(string)
	autunite, _ := strconv.ParseFloat(autunitestr, 64)
	natriumstr := dataBody["natrium"].(string)
	natrium, _ := strconv.ParseFloat(natriumstr, 64)
	hour := int64(dataBody["hour"].(float64))
	minute := int64(dataBody["minute"].(float64))
	beforWeight := dataBody["befor_weight"].(string)
	befor_weight, _ := strconv.ParseFloat(beforWeight, 64)
	afterWeight := dataBody["after_weight"].(string)
	after_weight, _ := strconv.ParseFloat(afterWeight, 64)
	befor_pressure := dataBody["befor_pressure"].(string)
	template_summary_content := dataBody["template_summary_content"].(string)
	template_plan_content := dataBody["template_plan_content"].(string)
	admin_user_id := int64(dataBody["admin_user_id"].(float64))
	record_time := dataBody["record_time"].(string)
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	recordTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", record_time, loc)
	after_pressure := dataBody["after_pressure"].(string)
	template_summary_id := int64(dataBody["template_summary_id"].(float64))
	template_plan_id := int64(dataBody["template_plan_id"].(float64))
	patient_id := int64(dataBody["patient_id"].(float64))
	orgId := this.GetAdminUserInfo().CurrentOrgId
	inspect_date := dataBody["inspect_date"].(string)
	project_id := dataBody["project_id"].(string)
	template_inspection_id := int64(dataBody["template_inspection_id"].(float64))
	//title := this.GetString("title")
	//dryWeight := this.GetString("dry_weight")
	//dry_weight, _ := strconv.ParseFloat(dryWeight, 64)
	//dialysis_count, _ := this.GetInt64("dialysis_count")
	//hd_count, _ := this.GetInt64("hd_count")
	//hdf_count, _ := this.GetInt64("hdf_count")
	//hp_count, _ := this.GetInt64("hp_count")
	//other_count, _ := this.GetInt64("other_count")
	//dialzer_apparatus := this.GetString("dialzer_apparatus")
	//perfusion_apparatus := this.GetString("perfusion_apparatus")
	//anticoagulant, _ := this.GetInt64("anticoagulant")
	//kaliumstr := this.GetString("kalium")
	//kalium, _ := strconv.ParseFloat(kaliumstr, 64)
	//
	//autunitestr := this.GetString("autunite")
	//autunite, _ := strconv.ParseFloat(autunitestr, 64)
	//natriumstr := this.GetString("natrium")
	//natrium, _ := strconv.ParseFloat(natriumstr, 64)
	//hour, _ := this.GetInt64("hour")
	//minute, _ := this.GetInt64("minute")
	//beforWeight := this.GetString("befor_weight")
	//befor_weight, _ := strconv.ParseFloat(beforWeight, 64)
	//afterWeight := this.GetString("after_weight")
	//after_weight, _ := strconv.ParseFloat(afterWeight, 64)
	//befor_pressure := this.GetString("befor_pressure")
	//template_summary_content := this.GetString("template_summary_content")
	//template_plan_content := this.GetString("template_plan_content")
	//admin_user_id, _ := this.GetInt64("admin_user_id")
	//record_time := this.GetString("record_time")
	//timeLayout := "2006-01-02"
	//loc, _ := time.LoadLocation("Local")
	//recordTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", record_time, loc)
	//after_pressure := this.GetString("after_pressure")
	//template_summary_id, _ := this.GetInt64("template_summary_id")
	//template_plan_id, _ := this.GetInt64("template_plan_id")
	//template_inspection_id, _ := this.GetInt64("template_inspection_id")
	//patient_id, _ := this.GetInt64("patient_id")
	//fmt.Println("patient_id", patient_id)
	//orgId := this.GetAdminUserInfo().CurrentOrgId
	//inspect_date := this.GetString("inspect_date")
	//project_id := this.GetString("project_id")
	summary := models.XtTemplateSummary{
		StartYear:              0,
		StartMonth:             0,
		Radio:                  0,
		Quarter:                0,
		DryWeight:              dry_weight,
		DialysisCount:          dialysis_count,
		HdCount:                hd_count,
		HdfCount:               hdf_count,
		HpCount:                hp_count,
		OtherCount:             other_count,
		DialzerApparatus:       dialzer_apparatus,
		PerfusionApparatus:     perfusion_apparatus,
		Anticoagulant:          anticoagulant,
		Kalium:                 kalium,
		Autunite:               autunite,
		Natrium:                natrium,
		Hour:                   hour,
		Minute:                 minute,
		BeforWeight:            befor_weight,
		AfterWeight:            after_weight,
		BeforPressure:          befor_pressure,
		AfterPressure:          after_pressure,
		TemplateSummaryId:      template_summary_id,
		TemplateSummaryContent: template_summary_content,
		TemplatePlanId:         template_plan_id,
		TemplatePlanContent:    template_plan_content,
		TemplateInspectionId:   template_inspection_id,
		AdminUserId:            admin_user_id,
		RecordTime:             recordTime.Unix(),
		PatientId:              patient_id,
		UserOrgId:              orgId,
		Status:                 1,
		Ctime:                  time.Now().Unix(),
		Mtime:                  0,
		Title:                  title,
		InspectDate:            inspect_date,
		ProjectId:              project_id,
	}

	err = service.CreateSummary(&summary)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"summary": summary,
		})
		return
	}

}

func (this *DoctorsApiController) GetTemplateSummaryList() {
	patient_id, _ := this.GetInt64("patient_id")
	start_time := this.GetString("start_time")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	end_time := this.GetString("end_time")
	orgId := this.GetAdminUserInfo().CurrentOrgId
	startTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	endTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
	fmt.Println("hhhhhhhhhhhhhh777777", endTime.Unix())
	list, err := service.GetTemplateSummaryList(patient_id, orgId, startTime.Unix(), endTime.Unix())
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"list": list,
		})
		return
	}
}

func (this *DoctorsApiController) GetTemplateSummaryDetail() {

	id, _ := this.GetInt64("id")
	list, err := service.GetTemplateSummaryDetail(id)

	ids := strings.Split(list.ProjectId, ",")
	datelist := strings.Split(list.InspectDate, ",")
	inspectlist, err := service.GetInspectionItemlist(list.PatientId, datelist, ids)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"list":        list,
			"inspectlist": inspectlist,
		})
		return
	}
}

func (this *DoctorsApiController) GetTemplateSummaryPrintDetail() {

	id, _ := this.GetInt64("id")
	list, err := service.GetTemplateSummaryPrintDetail(id)
	ids := strings.Split(list.ProjectId, ",")
	datelist := strings.Split(list.InspectDate, ",")
	inspectlist, err := service.GetInspectionItemlist(list.PatientId, datelist, ids)
	orgId := this.GetAdminUserInfo().CurrentOrgId
	doctorList, _ := service.GetAllDoctorThree(orgId)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"list":        list,
			"doctorList":  doctorList,
			"inspectlist": inspectlist,
		})
		return
	}
}

func (this *DoctorsApiController) UpdateTempalteSummary() {

	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	id := int64(dataBody["id"].(float64))
	title := dataBody["title"].(string)
	dryWeight := dataBody["dry_weight"].(string)
	dry_weight, _ := strconv.ParseFloat(dryWeight, 64)
	dialysis_count := int64(dataBody["dialysis_count"].(float64))
	hd_count := int64(dataBody["hd_count"].(float64))
	hdf_count := int64(dataBody["hdf_count"].(float64))
	hp_count := int64(dataBody["hp_count"].(float64))
	other_count := int64(dataBody["other_count"].(float64))
	dialzer_apparatus := dataBody["dialzer_apparatus"].(string)
	perfusion_apparatus := dataBody["perfusion_apparatus"].(string)
	anticoagulant := int64(dataBody["anticoagulant"].(float64))
	kaliumstr := dataBody["kalium"].(string)
	kalium, _ := strconv.ParseFloat(kaliumstr, 64)
	autunitestr := dataBody["autunite"].(string)
	autunite, _ := strconv.ParseFloat(autunitestr, 64)
	natriumstr := dataBody["natrium"].(string)
	natrium, _ := strconv.ParseFloat(natriumstr, 64)
	hour := int64(dataBody["hour"].(float64))
	minute := int64(dataBody["minute"].(float64))
	beforWeight := dataBody["befor_weight"].(string)
	befor_weight, _ := strconv.ParseFloat(beforWeight, 64)
	afterWeight := dataBody["after_weight"].(string)
	after_weight, _ := strconv.ParseFloat(afterWeight, 64)
	befor_pressure := dataBody["befor_pressure"].(string)
	template_summary_content := dataBody["template_summary_content"].(string)
	template_plan_content := dataBody["template_plan_content"].(string)
	admin_user_id := int64(dataBody["admin_user_id"].(float64))
	record_time := dataBody["record_time"].(string)
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	recordTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", record_time, loc)
	after_pressure := dataBody["after_pressure"].(string)
	template_summary_id := int64(dataBody["template_summary_id"].(float64))
	template_plan_id := int64(dataBody["template_plan_id"].(float64))
	patient_id := int64(dataBody["patient_id"].(float64))
	orgId := this.GetAdminUserInfo().CurrentOrgId
	inspect_date := dataBody["inspect_date"].(string)
	project_id := dataBody["project_id"].(string)
	template_inspection_id := int64(dataBody["template_inspection_id"].(float64))

	//id, _ := this.GetInt64("id")
	//title := this.GetString("title")
	//
	//dryWeight := this.GetString("dry_weight")
	//dry_weight, _ := strconv.ParseFloat(dryWeight, 64)
	//dialysis_count, _ := this.GetInt64("dialysis_count")
	//hd_count, _ := this.GetInt64("hd_count")
	//hdf_count, _ := this.GetInt64("hdf_count")
	//hp_count, _ := this.GetInt64("hp_count")
	//other_count, _ := this.GetInt64("other_count")
	//dialzer_apparatus := this.GetString("dialzer_apparatus")
	//perfusion_apparatus := this.GetString("perfusion_apparatus")
	//anticoagulant, _ := this.GetInt64("anticoagulant")
	//kaliumstr := this.GetString("kalium")
	//kalium, _ := strconv.ParseFloat(kaliumstr, 64)
	//
	//autunitestr := this.GetString("autunite")
	//autunite, _ := strconv.ParseFloat(autunitestr, 64)
	//natriumstr := this.GetString("natrium")
	//natrium, _ := strconv.ParseFloat(natriumstr, 64)
	//hour, _ := this.GetInt64("hour")
	//minute, _ := this.GetInt64("minute")
	//beforWeight := this.GetString("befor_weight")
	//befor_weight, _ := strconv.ParseFloat(beforWeight, 64)
	//afterWeight := this.GetString("after_weight")
	//after_weight, _ := strconv.ParseFloat(afterWeight, 64)
	//befor_pressure := this.GetString("befor_pressure")
	//template_summary_content := this.GetString("template_summary_content")
	//template_plan_content := this.GetString("template_plan_content")
	//admin_user_id, _ := this.GetInt64("admin_user_id")
	//record_time := this.GetString("record_time")
	//timeLayout := "2006-01-02"
	//loc, _ := time.LoadLocation("Local")
	//recordTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", record_time, loc)
	//after_pressure := this.GetString("after_pressure")
	//template_summary_id, _ := this.GetInt64("template_summary_id")
	//template_plan_id, _ := this.GetInt64("template_plan_id")
	//template_inspection_id, _ := this.GetInt64("template_inspection_id")
	//patient_id, _ := this.GetInt64("patient_id")
	//fmt.Println("patient_id", patient_id)
	//orgId := this.GetAdminUserInfo().CurrentOrgId
	//inspect_date := this.GetString("inspect_date")
	//project_id := this.GetString("project_id")
	summary := models.XtTemplateSummary{
		ID:                     id,
		StartYear:              0,
		StartMonth:             0,
		Radio:                  0,
		Quarter:                0,
		DryWeight:              dry_weight,
		DialysisCount:          dialysis_count,
		HdCount:                hd_count,
		HdfCount:               hdf_count,
		HpCount:                hp_count,
		OtherCount:             other_count,
		DialzerApparatus:       dialzer_apparatus,
		PerfusionApparatus:     perfusion_apparatus,
		Anticoagulant:          anticoagulant,
		Kalium:                 kalium,
		Autunite:               autunite,
		Natrium:                natrium,
		Hour:                   hour,
		Minute:                 minute,
		BeforWeight:            befor_weight,
		AfterWeight:            after_weight,
		BeforPressure:          befor_pressure,
		AfterPressure:          after_pressure,
		TemplateSummaryId:      template_summary_id,
		TemplateSummaryContent: template_summary_content,
		TemplatePlanId:         template_plan_id,
		TemplatePlanContent:    template_plan_content,
		TemplateInspectionId:   template_inspection_id,
		AdminUserId:            admin_user_id,
		RecordTime:             recordTime.Unix(),
		PatientId:              patient_id,
		UserOrgId:              orgId,
		Status:                 1,
		Ctime:                  time.Now().Unix(),
		Mtime:                  0,
		Title:                  title,
		ProjectId:              project_id,
		InspectDate:            inspect_date,
	}
	err = service.UpdateTempalteSummary(&summary)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"list": summary,
		})
		return
	}
}

func (this *DoctorsApiController) DeleteSummary() {

	ids := this.GetString("ids")
	idsplit := strings.Split(ids, ",")
	err := service.DeleteSummary(idsplit)
	fmt.Println(err)
	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "ok"
	this.ServeSuccessJSON(returnData)
	return
}