package controllers

import (
	"Xcx_New/enums"
	"Xcx_New/service"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/jinzhu/gorm"
	"strings"
	"time"
)

type DialysisPrameterApiController struct {
	BaseAuthAPIController
}

func DialysisPrameteRoutes() {
	beego.Router("/api/dialysis/getdialysisparameters", &DialysisPrameterApiController{}, "Get:GetDialysisParameters")
	beego.Router("/api/dialysis/getdialysisbatchparameters", &DialysisPrameterApiController{}, "Get:GetDialysisBatchParameters")
	beego.Router("/api/dialysis/getwarehouseoutlist", &DialysisPrameterApiController{}, "Get:GetWareHouseOutList")
	beego.Router("/api/dialysis/getallmaterial", &DialysisPrameterApiController{}, "Get:GetAllMaterial")
	beego.Router("/api/dialysis/getcollectlist", &DialysisPrameterApiController{}, "Get:GetCollectList")
	beego.Router("/api/dialysis/getbatchcollection", &DialysisPrameterApiController{}, "Get:GetBatchCollection")
	beego.Router("/api/dialysis/getgatherlist", &DialysisPrameterApiController{}, "Get:GetGatherList")
	beego.Router("/api/dialysis/getanticoagulantcount", &DialysisPrameterApiController{}, "Get:GetAnticoagulantCount")
}

func (this *DialysisPrameterApiController) GetDialysisParameters() {
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	page, _ := this.GetInt64("page")
	limit, _ := this.GetInt64("limit")
	schedulType, _ := this.GetInt64("scheduleType")
	start_time := this.GetString("start_time")
	partitionType, _ := this.GetInt64("partitionType")
	keywords := this.GetString("keyword")
	adminUserInfo := this.GetAdminUserInfo()
	theTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)

	fmt.Println("scheduletype", schedulType, start_time, partitionType, keywords, theTime.Unix())
	if len(keywords) > 0 {
		dialysisSchedule, err, total := service.GetDialysisParametersByKeyword(adminUserInfo.CurrentOrgId, keywords, schedulType, partitionType, page, limit, theTime.Unix())
		patient, err := service.GetDialysisTodaySchedulePatient(adminUserInfo.CurrentOrgId, theTime.Unix(), page, limit, keywords, schedulType, partitionType)
		var vlist []interface{}
		var elist []interface{}
		for _, item := range patient {
			prescription, _ := service.GetDialysisPrescriptionList(item.PatientId, adminUserInfo.CurrentOrgId, theTime.Unix())
			vlist = append(vlist, prescription)
			dialysis, _ := service.GetAssessmentBeforDialysisByStartime(item.PatientId, adminUserInfo.CurrentOrgId, theTime.Unix())
			elist = append(elist, dialysis)
		}
		if err == nil {
			this.ServeSuccessJSON(map[string]interface{}{
				"schedule":     dialysisSchedule,
				"total":        total,
				"prescription": vlist,
				"dialysbefor":  elist,
				"patient":      patient,
			})
		} else {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		}
	} else {
		dialysisSchedule, err, total := service.GetDialysisParameter(adminUserInfo.CurrentOrgId, theTime.Unix(), schedulType, partitionType, page, limit)

		//查询今日排班的病人
		patient, err := service.GetDialysisTodaySchedulePatient(adminUserInfo.CurrentOrgId, theTime.Unix(), page, limit, keywords, schedulType, partitionType)

		var vlist []interface{}
		var elist []interface{}
		for _, item := range patient {
			//查询当前日期的病人是否存在数据
			//_, errcode := service.GetToDayDialysisPrescription(item.PatientId, adminUserInfo.CurrentOrgId, theTime.Unix())
			//if errcode == gorm.ErrRecordNotFound {
			//	//查询每个病人透析处方的最后一次数据
			//	prescription, _ := service.GetLastDialysisPrescription(item.PatientId, adminUserInfo.CurrentOrgId)
			//	vlist = append(vlist, prescription)
			//} else if errcode == nil {
			//	//获取当前日期
			//	prescription, _ := service.GetDialysisPrescriptionList(item.PatientId, adminUserInfo.CurrentOrgId, theTime.Unix())
			//	vlist = append(vlist, prescription)
			//}

			//_, errcodes := service.GetTodayAssessmentBeforDialysis(item.PatientId, adminUserInfo.CurrentOrgId, theTime.Unix())
			//if errcodes == gorm.ErrRecordNotFound {
			//	//查询每个病人透前评估的最后一次数据
			//	dialysis, _ := service.GetLastAssessmentBeforDialysis(item.PatientId, adminUserInfo.CurrentOrgId)
			//	elist = append(elist, dialysis)
			//} else if errcodes == nil {
			//	dialysis, _ := service.GetAssessmentBeforDialysisByStartime(item.PatientId, adminUserInfo.CurrentOrgId, theTime.Unix())
			//	elist = append(elist, dialysis)
			//}

			prescription, _ := service.GetDialysisPrescriptionList(item.PatientId, adminUserInfo.CurrentOrgId, theTime.Unix())
			vlist = append(vlist, prescription)
			dialysis, _ := service.GetAssessmentBeforDialysisByStartime(item.PatientId, adminUserInfo.CurrentOrgId, theTime.Unix())
			elist = append(elist, dialysis)
		}

		if err == nil {
			this.ServeSuccessJSON(map[string]interface{}{
				"schedule":     dialysisSchedule,
				"total":        total,
				"prescription": vlist,
				"dialysbefor":  elist,
				"patient":      patient,
			})
		} else {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		}
	}

}

func (this *DialysisPrameterApiController) GetDialysisBatchParameters() {
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	adminUser := this.GetAdminUserInfo()
	orgId := adminUser.CurrentOrgId
	schIDStr := this.GetString("ids")
	if len(schIDStr) == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	idStrs := strings.Split(schIDStr, ",")
	startime := this.GetString("startime")
	theTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", startime+" 00:00:00", loc)
	parameters, err := service.GetDialysisBatchParameters(idStrs, orgId)
	var vlist []interface{}
	var elist []interface{}
	for _, item := range parameters {
		//查询当前日期的病人是否存在数据
		_, errcode := service.GetToDayDialysisPrescription(item.PatientId, orgId, theTime.Unix())
		if errcode == gorm.ErrRecordNotFound {
			//查询每个病人透析处方的最后一次数据
			prescription, _ := service.GetLastDialysisPrescription(item.PatientId, orgId)
			vlist = append(vlist, prescription)
		} else if errcode == nil {
			//获取当前日期
			prescription, _ := service.GetDialysisPrescriptionList(item.PatientId, orgId, theTime.Unix())
			vlist = append(vlist, prescription)
		}

		_, errcodes := service.GetTodayAssessmentBeforDialysis(item.PatientId, orgId, theTime.Unix())
		if errcodes == gorm.ErrRecordNotFound {
			//查询每个病人透前评估的最后一次数据
			dialysis, _ := service.GetLastAssessmentBeforDialysis(item.PatientId, orgId)
			elist = append(elist, dialysis)
		} else if errcodes == nil {
			dialysis, _ := service.GetAssessmentBeforDialysisByStartime(item.PatientId, orgId, theTime.Unix())
			elist = append(elist, dialysis)
		}

	}
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"schedule":     parameters,
			"prescription": vlist,
			"dialysbefor":  elist,
		})
	}
}

func (this *DialysisPrameterApiController) GetWareHouseOutList() {

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	start_time := this.GetString("start_time")
	startime, _ := 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(start_time, end_time)
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	wareoutlist, err := service.GetWareHouseOutList(startime.Unix(), endtime.Unix(), orgId)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"wareoutlist": wareoutlist,
		})
	}
}

func (this *DialysisPrameterApiController) GetAllMaterial() {

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	start_time := this.GetString("startime")
	startime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	endtime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 23:59:59", loc)
	orgId := this.GetAdminUserInfo().CurrentOrgId
	material, err := service.GetAllMaterial(startime.Unix(), endtime.Unix(), orgId)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"material": material,
		})
	}
}

func (this *DialysisPrameterApiController) GetCollectList() {

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	limit, _ := this.GetInt64("limit")
	fmt.Println(limit)
	page, _ := this.GetInt64("page")
	fmt.Println("page", page)
	partitiontype, _ := this.GetInt64("partitionType")
	fmt.Println(partitiontype)
	scheduletype, _ := this.GetInt64("scheduleType")
	fmt.Println(scheduletype)
	start_time := this.GetString("start_time")
	fmt.Println(start_time)
	startime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	fmt.Println("startime", startime.Unix())
	orgId := this.GetAdminUserInfo().CurrentOrgId
	endtime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 23:59:59", loc)
	keyword := this.GetString("keyword")
	//获取透析参数数据
	schedule, err, _ := service.GetCollectList(limit, page, partitiontype, scheduletype, startime.Unix(), orgId, keyword)

	//查询今日排班的病人
	patient, err := service.GetDialysisTodaySchedulePatient(orgId, startime.Unix(), page, limit, keyword, scheduletype, partitiontype)
	var vlist []interface{}
	var clist []interface{}
	for _, item := range patient {
		fmt.Println("---------", item.PatientId)
		//查询当前日期的病人是否存在数据
		//_, errcode := service.GetToDayDialysisPrescription(item.PatientId, orgId, startime.Unix())
		//if errcode == gorm.ErrRecordNotFound {
		//	//查询每个病人透析处方的最后一次数据
		//	prescription, _ := service.GetLastDialysisPrescription(item.PatientId, orgId)
		//	vlist = append(vlist, prescription)
		//} else if errcode == nil {
		//	//获取当前日期
		//	prescription, _ := service.GetDialysisPrescriptionList(item.PatientId, orgId, startime.Unix())
		//	vlist = append(vlist, prescription)
		//}

		//查询每个病人当前日期是否存在数据
		//_, errco := service.GetAotoMaticReduceByPatientId(item.PatientId, orgId, startime.Unix(), endtime.Unix())
		//fmt.Println("errco--------------------------", errco)
		//if errco == gorm.ErrRecordNotFound {
		//	reduece, _ := service.GetMaticReduece(item.PatientId, orgId)
		//	clist = append(clist, reduece)
		//} else if errco == nil {
		//	reduece, _ := service.GetMaticeReduceByPatientId(item.PatientId, orgId, startime.Unix(), endtime.Unix())
		//	clist = append(clist, reduece)
		//}

		prescription, _ := service.GetDialysisPrescriptionList(item.PatientId, orgId, startime.Unix())
		vlist = append(vlist, prescription)

		reduece, _ := service.GetMaticeReduceByPatientId(item.PatientId, orgId, startime.Unix(), endtime.Unix())
		clist = append(clist, reduece)
	}
	//获取透析耗材数据
	//consumables, err := service.GetDialysisConsumables(startime.Unix(), endtime.Unix(), orgId)

	//if err == nil {
	// this.ServeSuccessJSON(map[string]interface{}{
	//   "schedule":     schedule,
	//   "total":        total,
	//   "consumables":  consumables,
	//   "prescription": vlist,
	//   "reducelist":   clist,
	// })
	//}

	_, errors := service.FindStockOutByIsSys(orgId, 1, startime.Unix())

	goodTypes, _ := service.FindAllGoodType(orgId) //two, err, i := service.PCGetDialysisGoodsTwo(orgId, startime.Unix(), scheduletype, partitiontype, page, limit, keyword)

	if errors == gorm.ErrRecordNotFound {

		dialysisGoods, _, total := service.PCGetDialysisGoodsTwo(orgId, startime.Unix(), scheduletype, partitiontype, page, limit, keyword)
		for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
			goodUser, _ := service.GetLastDialysisGoodsTwo(item.PatientId, orgId, startime.Unix())
			lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepareTwo(item.PatientId, orgId, startime.Unix())
			item.LastAutomaticReduceDetail = goodUser
			item.LastDialysisBeforePrepare = lastGoodUserDetial
		}
		this.ServeSuccessJSON(map[string]interface{}{
			"dialysis_goods": dialysisGoods,
			"good_type":      goodTypes,
			"total":          total,
			"schedule":       schedule,
			//"consumables":    consumables,
			"prescription": vlist,
			"reducelist":   clist,
		})
		return

	} else if err == nil {
		//获取当天排班的每个患者的库存使用情况
		dialysisGoods, err, total := service.PCGetDialysisGoodsTwo(orgId, startime.Unix(), scheduletype, partitiontype, page, limit, keyword)
		for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
			goodUser, _ := service.GetLastDialysisGoodsTwo(item.PatientId, orgId, startime.Unix())
			lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepareTwo(item.PatientId, orgId, startime.Unix())

			fmt.Println(goodUser)
			fmt.Println(lastGoodUserDetial)

			item.LastAutomaticReduceDetail = goodUser
			item.LastDialysisBeforePrepare = lastGoodUserDetial
		}
		if err == nil {
			this.ServeSuccessJSON(map[string]interface{}{
				"dialysis_goods": dialysisGoods,
				"good_type":      goodTypes,
				"total":          total,
				"schedule":       schedule,
				//"consumables":    consumables,
				"prescription": vlist,
				"reducelist":   clist,
			})
			return

		} else {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
			return
		}
	} else if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return

	}

}

func (this *DialysisPrameterApiController) GetBatchCollection() {
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	adminUser := this.GetAdminUserInfo()
	orgId := adminUser.CurrentOrgId
	fmt.Println(orgId)
	start_time := this.GetString("startime")
	startime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	endtime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 23:59:59", loc)
	schIDStr := this.GetString("ids")
	//获取透析耗材数据
	consumables, err := service.GetDialysisConsumables(startime.Unix(), endtime.Unix(), orgId)

	if len(schIDStr) == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	idStrs := strings.Split(schIDStr, ",")
	fmt.Println(idStrs)
	var vlist []interface{}
	var clist []interface{}
	schedule, err := service.GetBatchCollection(orgId, idStrs)
	for _, item := range schedule {
		//查询当前日期的病人是否存在数据
		_, errcode := service.GetToDayDialysisPrescription(item.PatientId, orgId, startime.Unix())
		if errcode == gorm.ErrRecordNotFound {
			//查询每个病人透析处方的最后一次数据
			prescription, _ := service.GetLastDialysisPrescription(item.PatientId, orgId)
			vlist = append(vlist, prescription)
		} else if errcode == nil {
			//获取当前日期
			prescription, _ := service.GetDialysisPrescriptionList(item.PatientId, orgId, startime.Unix())
			vlist = append(vlist, prescription)
		}

		//查询每个病人当前日期是否存在数据
		_, errco := service.GetAotoMaticReduceByPatientId(item.PatientId, orgId, startime.Unix(), endtime.Unix())
		fmt.Println("errco", errco)
		if errco == gorm.ErrRecordNotFound {
			reduece, _ := service.GetMaticReduece(item.PatientId, orgId)
			clist = append(clist, reduece)
		} else if errco == nil {
			reduece, _ := service.GetMaticeReduceByPatientId(item.PatientId, orgId, startime.Unix(), endtime.Unix())
			clist = append(clist, reduece)
		}

	}
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"schedule":     schedule,
			"consumables":  consumables,
			"prescripiton": vlist,
			"reducelist":   clist,
		})
	}
}

func (this *DialysisPrameterApiController) GetGatherList() {

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	adminUser := this.GetAdminUserInfo()
	orgId := adminUser.CurrentOrgId
	fmt.Println(orgId)
	start_time := this.GetString("start_time")
	end_time := this.GetString("end_time")
	startime, _ := 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("开始时间", startime)
	fmt.Println("结束时间", endtime)

	warehouselist, err := service.GetWareHouseOutList(startime.Unix(), endtime.Unix(), orgId)

	//获取透析耗材数据
	consumables, err := service.GetDialysisConsumables(startime.Unix(), endtime.Unix(), orgId)

	//统计抗凝剂数据
	count, err := service.GetAnticoagulantCount(startime.Unix(), endtime.Unix(), orgId)

	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"warehouselist": warehouselist,
			"consumables":   consumables,
			"count":         count,
		})
	}
}

func (this *DialysisPrameterApiController) GetAnticoagulantCount() {
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	adminUser := this.GetAdminUserInfo()
	orgId := adminUser.CurrentOrgId
	fmt.Println(orgId)
	start_time := this.GetString("start_time")
	end_time := this.GetString("end_time")
	startime, _ := 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("开始时间2222", startime)
	fmt.Println("结束时间3333", endtime)
	//统计抗凝剂数据
	count, err := service.GetAnticoagulantCount(startime.Unix(), endtime.Unix(), orgId)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"count": count,
		})
	}
}
