package service

import (
	"XT_New/models"
	"fmt"
	"time"
)

type DialysisTotalDataStruct struct {
	Date   string `json:"date"`
	Number string `json:"number"`
	ModeID string `json:"mode_id"`
}

func GetDialysisTotalData(orgID, page, limit, lapseto, statisticalMethod, modeID, startTime, endTime int64, isStartTime, isEndTime bool) (dtd []*DialysisTotalDataStruct, ttd []*DialysisTotalDataStruct, total int64, err error) {
	db := readDb

	sql := "s.mode_id, from_unixtime(s.schedule_date, '%Y%m%d') as date, count(s.schedule_date) as number"
	datesql := "s.schedule_date as date"
	group := "from_unixtime(s.schedule_date, '%Y%m%d')"

	db = db.Table("xt_schedule as s")
	if statisticalMethod == 1 {
		db = db.Joins("JOIN xt_dialysis_order as o ON o.user_org_id =? and o.patient_id=s.patient_id and o.dialysis_date=s.schedule_date and o.status=1", orgID)
	}
	db = db.Where("s.user_org_id=?", orgID)
	if modeID > 0 {
		db = db.Where("s.mode_id=?", modeID)
	}
	if isStartTime {
		db = db.Where("s.schedule_date>=?", startTime)
	}
	if isEndTime {
		db = db.Where("s.schedule_date<=?", endTime)
	}
	db = db.Where("s.status=1")

	if lapseto > 0 {
		joinString := "JOIN xt_patients as p ON o.patient_id=p.id and p.lapseto=? and p.status=1"
		joinParams := make([]interface{}, 0)
		joinParams = append(joinParams, lapseto)
		if orgID > 0 {
			joinString += " AND p.user_org_id=?"
			joinParams = append(joinParams, orgID)
		}

		db = db.Joins(joinString, joinParams...)
	}

	err = db.Select("s.mode_id, count(s.mode_id) as number").Group("s.mode_id").Order("s.mode_id asc").Find(&ttd).Error
	if err != nil {
		return
	}

	offset := (page - 1) * limit

	var ds []*DialysisTotalDataStruct
	err = db.Select(datesql).Group(group).Count(&total).Order("date asc").Offset(offset).Limit(limit).Find(&ds).Error
	if err != nil {
		return
	}

	dates := make([]string, 0)
	if len(ds) > 0 {
		for _, d := range ds {
			dates = append(dates, d.Date)
		}

		db = db.Where("s.schedule_date IN (?)", dates)

	}

	err = db.Select(sql).Group(group + ", s.mode_id").Order("date asc, mode_id").Find(&dtd).Error
	return
}

type PIInspectionPageStruct struct {
	PatientID   int64 `json:"patient_id"`
	InspectDate int64 `json:"inspect_date"`
}

type PIInspectionProjectCountStruct struct {
	Count int64 `json:"count"`
}

func GetProcessIndicatorsData(orgID, page, limit, lapseto, dialysisAge, projectID, startTime, endTime int64, isStartTime, isEndTime bool) (inspections []*models.Inspection, references []*models.InspectionReference, patients []*models.Patients, counts []*PIInspectionProjectCountStruct, total int64, err error) {
	err = readDb.Table("xt_inspection_reference").Find(&references).Error
	if err != nil || len(references) == 0 {
		return
	}

	projects := make(map[int64]int64, 0)
	for _, reference := range references {
		if _, exist := projects[reference.ProjectId]; !exist {
			projects[reference.ProjectId] = reference.ProjectId
		}
	}
	projectLen := len(projects)

	countSQL := "SELECT count(distinct project_id) as projects FROM xt_inspection as i "
	countParams := make([]interface{}, 0)
	if dialysisAge > 0 || lapseto > 0 {
		countSQL += " JOIN xt_patients as p ON i.patient_id=p.id"
		if orgID > 0 {
			countSQL += " and p.user_org_id=?"
			countParams = append(countParams, orgID)
		}
		if lapseto > 0 {
			countSQL += " and p.lapseto=?"
			countParams = append(countParams, lapseto)
		}
		if dialysisAge > 0 {
			loc, _ := time.LoadLocation("Local")
			nowTime := time.Now()
			nowDay := nowTime.Format("2006-01-02")
			dayTime, err := time.ParseInLocation("2006-01-02 15:04:05", nowDay+" 00:00:00", loc)
			if err != nil {
				return inspections, references, patients, counts, total, err
			}
			timePoint := dayTime.AddDate(0, -3, 0).Unix()
			if dialysisAge == 1 {
				countSQL += " and p.first_dialysis_date<>0 AND p.first_dialysis_date <= ?"
				countParams = append(countParams, timePoint)
			} else {
				countSQL += " and p.first_dialysis_date<>0 AND p.first_dialysis_date > ?"
				countParams = append(countParams, timePoint)
			}
		}
	}

	countSQL += " WHERE i.status=1"
	if orgID > 0 {
		countSQL += " AND i.org_id=?"
		countParams = append(countParams, orgID)
	}
	if projectID > 0 {
		countSQL += " AND i.project_id=?"
		countParams = append(countParams, projectID)
	}
	if isStartTime {
		countSQL += " AND i.inspect_date>=?"
		countParams = append(countParams, startTime)
	}
	if isEndTime {
		countSQL += " AND i.inspect_date<=?"
		countParams = append(countParams, endTime)
	}
	countParams = append(countParams, projectLen)

	err = readDb.Raw("SELECT COUNT(*) as count from ("+countSQL+" GROUP BY inspect_date, patient_id) as t where t.projects<?", countParams...).Scan(&counts).Error
	if err != nil {
		return
	}

	db := readDb.Table("xt_inspection as i")
	if orgID > 0 {
		db = db.Where("i.org_id=?", orgID)
	}
	if projectID > 0 {
		db = db.Where("i.project_id=?", projectID)
	}
	if isStartTime {
		db = db.Where("i.inspect_date>=?", startTime)
	}
	if isEndTime {
		db = db.Where("i.inspect_date<=?", endTime)
	}
	db = db.Where("i.status=1")

	if dialysisAge > 0 || lapseto > 0 {
		joinString := "JOIN xt_patients as p ON i.patient_id=p.id"
		joinParams := make([]interface{}, 0)
		if orgID > 0 {
			joinString += " and p.user_org_id=?"
			joinParams = append(joinParams, orgID)
		}

		if lapseto > 0 {
			joinString += " and p.lapseto=?"
			joinParams = append(joinParams, lapseto)
		}
		if dialysisAge > 0 {
			loc, _ := time.LoadLocation("Local")
			nowTime := time.Now()
			nowDay := nowTime.Format("2006-01-02")
			dayTime, err := time.ParseInLocation("2006-01-02 15:04:05", nowDay+" 00:00:00", loc)
			if err != nil {
				return inspections, references, patients, counts, total, err
			}
			timePoint := dayTime.AddDate(0, -3, 0).Unix()
			if dialysisAge == 1 {
				joinString += " and p.first_dialysis_date<>0 AND p.first_dialysis_date <= ?"
				joinParams = append(joinParams, timePoint)
			} else {
				joinString += " and p.first_dialysis_date<>0 AND p.first_dialysis_date > ?"
				joinParams = append(joinParams, timePoint)
			}
		}

		db = db.Joins(joinString, joinParams...)
	}

	offset := (page - 1) * limit

	var ds []*PIInspectionPageStruct
	err = db.Select("i.patient_id, i.inspect_date").Group("inspect_date, patient_id").Count(&total).Order("inspect_date desc, i.created_time desc, i.id asc, patient_id asc").Offset(offset).Limit(limit).Find(&ds).Error
	if err != nil {
		return
	}

	dates := make([]int64, 0)
	ids := make([]int64, 0)
	if len(ds) > 0 {
		for _, d := range ds {
			dates = append(dates, d.InspectDate)
			ids = append(ids, d.PatientID)
		}

		db = db.Where("i.inspect_date IN (?)", dates).Where("i.patient_id IN (?)", ids)
	}

	err = db.Select("i.id, i.patient_id, org_id, i.project_id, i.item_id, i.item_name, i.project_name, i.inspect_type, i.inspect_value, i.inspect_date, i.status, i.created_time, i.updated_time").Order("inspect_date desc, created_time desc, id asc, patient_id asc").Find(&inspections).Error
	if err != nil {
		return
	}

	if len(ids) > 0 {
		err = readDb.Table("xt_patients").Where("id IN (?)", ids).Find(&patients).Error
		if err != nil {
			return
		}
	}

	return
}

func GetOICData(orgID, page, limit, lapseto, dialysisAge, projectID, itemID, startTime, endTime int64, isStartTime, isEndTime bool) (inspections []*models.Inspection, references []*models.InspectionReference, patients []*models.Patients, counts []*PIInspectionProjectCountStruct, total int64, err error) {
	err = readDb.Table("xt_inspection_reference").Order("project_id").Find(&references).Error
	if err != nil || len(references) == 0 {
		return
	}

	countSQL := "SELECT count(distinct i.project_id) as projects FROM xt_inspection as i "
	countParams := make([]interface{}, 0)
	countSQL += " JOIN xt_inspection_reference as ir ON ir.id=i.item_id and ir.project_id=i.project_id"

	if dialysisAge > 0 || lapseto > 0 {
		countSQL += " JOIN xt_patients as p ON i.patient_id=p.id"
		if orgID > 0 {
			countSQL += " and p.user_org_id=?"
			countParams = append(countParams, orgID)
		}
		if lapseto > 0 {
			countSQL += " and p.lapseto=?"
			countParams = append(countParams, lapseto)
		}
		if dialysisAge > 0 {
			loc, _ := time.LoadLocation("Local")
			nowTime := time.Now()
			nowDay := nowTime.Format("2006-01-02")
			dayTime, err := time.ParseInLocation("2006-01-02 15:04:05", nowDay+" 00:00:00", loc)
			if err != nil {
				return inspections, references, patients, counts, total, err
			}
			timePoint := dayTime.AddDate(0, -3, 0).Unix()
			if dialysisAge == 1 {
				countSQL += " and p.first_dialysis_date<>0 AND p.first_dialysis_date <= ?"
				countParams = append(countParams, timePoint)
			} else {
				countSQL += " and p.first_dialysis_date<>0 AND p.first_dialysis_date > ?"
				countParams = append(countParams, timePoint)
			}
		}
	}

	countSQL += " WHERE i.status=1"
	if orgID > 0 {
		countSQL += " AND i.org_id=?"
		countParams = append(countParams, orgID)
	}
	if projectID > 0 {
		countSQL += " AND i.project_id=?"
		countParams = append(countParams, projectID)
	}
	if isStartTime {
		countSQL += " AND i.inspect_date>=?"
		countParams = append(countParams, startTime)
	}
	if isEndTime {
		countSQL += " AND i.inspect_date<=?"
		countParams = append(countParams, endTime)
	}
	countSQL += " AND ((i.inspect_type=1 AND (CONVERT(i.inspect_value, DECIMAL)<CONVERT(ir.range_min, DECIMAL) OR CONVERT(i.inspect_value, DECIMAL)>CONVERT(ir.range_max, DECIMAL))) OR (i.inspect_type=2 AND i.inspect_value<>ir.range_value))"

	err = readDb.Raw("SELECT COUNT(*) as count from ("+countSQL+" GROUP BY inspect_date, patient_id) as t ", countParams...).Scan(&counts).Error
	if err != nil {
		return
	}

	db := readDb.Table("xt_inspection as i")
	if orgID > 0 {
		db = db.Where("i.org_id=?", orgID)
	}
	if projectID > 0 {
		db = db.Where("i.project_id=?", projectID)
	}
	if itemID > 0 {
		db = db.Where("i.item_id=?", itemID)
	}
	if isStartTime {
		db = db.Where("i.inspect_date>=?", startTime)
	}
	if isEndTime {
		db = db.Where("i.inspect_date<=?", endTime)
	}
	db = db.Where("i.status=1")

	if dialysisAge > 0 || lapseto > 0 {
		joinString := "JOIN xt_patients as p ON i.patient_id=p.id"
		joinParams := make([]interface{}, 0)
		if orgID > 0 {
			joinString += " and p.user_org_id=?"
			joinParams = append(joinParams, orgID)
		}

		if lapseto > 0 {
			joinString += " and p.lapseto=?"
			joinParams = append(joinParams, lapseto)
		}
		if dialysisAge > 0 {
			loc, _ := time.LoadLocation("Local")
			nowTime := time.Now()
			nowDay := nowTime.Format("2006-01-02")
			dayTime, err := time.ParseInLocation("2006-01-02 15:04:05", nowDay+" 00:00:00", loc)
			if err != nil {
				return inspections, references, patients, counts, total, err
			}
			timePoint := dayTime.AddDate(0, -3, 0).Unix()
			if dialysisAge == 1 {
				joinString += " and p.first_dialysis_date<>0 AND p.first_dialysis_date <= ?"
				joinParams = append(joinParams, timePoint)
			} else {
				joinString += " and p.first_dialysis_date<>0 AND p.first_dialysis_date > ?"
				joinParams = append(joinParams, timePoint)
			}
		}

		db = db.Joins(joinString, joinParams...)
	}

	offset := (page - 1) * limit

	var ds []*PIInspectionPageStruct
	err = db.Select("i.patient_id, i.inspect_date").Group("inspect_date, patient_id").Count(&total).Order("inspect_date desc, i.created_time desc, i.id asc, patient_id asc").Offset(offset).Limit(limit).Find(&ds).Error
	if err != nil {
		return
	}

	dates := make([]int64, 0)
	ids := make([]int64, 0)
	if len(ds) > 0 {
		for _, d := range ds {
			dates = append(dates, d.InspectDate)
			ids = append(ids, d.PatientID)
		}

		db = db.Where("i.inspect_date IN (?)", dates).Where("i.patient_id IN (?)", ids)
	}

	err = db.Select("i.id, i.patient_id, org_id, i.project_id, i.item_id, i.item_name, i.project_name, i.inspect_type, i.inspect_value, i.inspect_date, i.status, i.created_time, i.updated_time").Order("inspect_date desc, created_time desc, id asc, patient_id asc").Find(&inspections).Error
	if err != nil {
		return
	}

	if len(ids) > 0 {
		err = readDb.Table("xt_patients").Where("id IN (?)", ids).Find(&patients).Error
		if err != nil {
			return
		}
	}

	return
}

func GetOIQData(orgID, page, limit, projectID, startTime, endTime int64, isStartTime, isEndTime bool, searchKey string) (inspections []*models.Inspection, references []*models.InspectionReference, patients []*models.Patients, total int64, err error) {
	err = readDb.Table("xt_inspection_reference").Order("project_id").Find(&references).Error
	if err != nil || len(references) == 0 {
		return
	}
	if projectID <= 0 {
		projectID = references[0].ProjectId
	}

	db := readDb.Table("xt_inspection as i")
	if orgID > 0 {
		db = db.Where("i.org_id=?", orgID)
	}
	if projectID > 0 {
		db = db.Where("i.project_id=?", projectID)
	}
	if isStartTime {
		db = db.Where("i.inspect_date>=?", startTime)
	}
	if isEndTime {
		db = db.Where("i.inspect_date<=?", endTime)
	}

	if len(searchKey) > 0 {
		searchKey = "%" + searchKey + "%"
		joinString := "JOIN xt_patients as p ON i.patient_id=p.id AND (p.name LIKE ? OR p.dialysis_no LIKE ?)"
		joinParams := make([]interface{}, 0)
		joinParams = append(joinParams, searchKey)
		joinParams = append(joinParams, searchKey)
		db = db.Joins(joinString, joinParams...)

		db = db.Where("p.name LIKE ? OR p.dialysis_no LIKE ?", searchKey, searchKey)
	}
	db = db.Where("i.status=1")

	offset := (page - 1) * limit

	var ds []*PIInspectionPageStruct
	err = db.Select("i.patient_id, i.inspect_date").Group("inspect_date, patient_id").Count(&total).Order("inspect_date desc, i.created_time desc, i.id asc, patient_id asc").Offset(offset).Limit(limit).Find(&ds).Error
	if err != nil {
		return
	}

	dates := make([]int64, 0)
	ids := make([]int64, 0)
	if len(ds) > 0 {
		for _, d := range ds {
			dates = append(dates, d.InspectDate)
			ids = append(ids, d.PatientID)
		}

		db = db.Where("i.inspect_date IN (?)", dates).Where("i.patient_id IN (?)", ids)
	}

	err = db.Select("i.id, i.patient_id, org_id, i.project_id, i.item_id, i.item_name, i.project_name, i.inspect_type, i.inspect_value, i.inspect_date, i.status, i.created_time, i.updated_time").Order("inspect_date desc, created_time desc, id asc, patient_id asc").Find(&inspections).Error
	if err != nil {
		return
	}

	if len(ids) > 0 {
		err = readDb.Table("xt_patients").Where("id IN (?)", ids).Find(&patients).Error
		if err != nil {
			return
		}
	}

	return
}

func GetPATotalData(orgID, page, limit, lapseto, source, age, startTime, endTime int64, isStartTime, isEndTime bool, searchKey string) (patients []*models.Patients, lapsetoOut, lapsetoIn, total int64, err error) {
	db := readDb.Table("xt_patients").Where("status=1")
	if orgID > 0 {
		db = db.Where("user_org_id=?", orgID)
	}
	if lapseto > 0 {
		db = db.Where("lapseto=?", lapseto)
	}
	if source > 0 {
		if source == 1 || source == 2 {
			db = db.Where("source=?", source)
		} else {
			db = db.Where("source NOT IN (1,2)")
		}
	}

	loc, _ := time.LoadLocation("Local")
	nowTime := time.Now()
	nowDay := nowTime.Format("2006-01-02")
	dayTime, err := time.ParseInLocation("2006-01-02 15:04:05", nowDay+" 00:00:00", loc)
	if err != nil {
		return
	}
	var timeStartPoint int64
	var timeEndPoint int64

	if age == 1 {
		timeStartPoint = dayTime.AddDate(-20, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-30, 0, 0).Unix()
		db = db.Where("birthday>? and birthday<=?", timeEndPoint, timeStartPoint)
	} else if age == 2 {
		timeStartPoint = dayTime.AddDate(-30, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-40, 0, 0).Unix()
		db = db.Where("birthday>? and birthday<=?", timeEndPoint, timeStartPoint)
	} else if age == 3 {
		timeStartPoint = dayTime.AddDate(-40, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-50, 0, 0).Unix()
		db = db.Where("birthday>? and birthday<=?", timeEndPoint, timeStartPoint)
	} else if age == 4 {
		timeStartPoint = dayTime.AddDate(-10, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-50, 0, 0).Unix()
		db = db.Where("birthday>? or birthday<=?", timeStartPoint, timeEndPoint)
	}
	if isStartTime {
		db = db.Where("created_time>=?", startTime)
	}
	if isEndTime {
		db = db.Where("created_time<=?", endTime)
	}
	if len(searchKey) > 0 {
		searchKey = "%" + searchKey + "%"
		db = db.Where("name LIKE ? OR dialysis_no LIKE ? ", searchKey, searchKey)
	}

	offset := (page - 1) * limit
	err = db.Count(&total).Order("id desc").Offset(offset).Limit(limit).Find(&patients).Error
	if err != nil {
		return
	}

	err = db.Where("lapseto=1").Count(&lapsetoIn).Error
	if err != nil {
		return
	}
	lapsetoOut = total - lapsetoIn

	return
}

type PADialysisAgePieDataStruct struct {
	Age   int64 `json:"age"`
	Count int64 `json:"count"`
}

func GetPADialysisAgeData(orgID, page, limit, lapseto, age, dialysisAge, startTime, endTime int64, isStartTime, isEndTime bool) (patients []*models.Patients, counts []*PADialysisAgePieDataStruct, total int64, err error) {
	loc, _ := time.LoadLocation("Local")
	nowTime := time.Now()
	nowDay := nowTime.Format("2006-01-02")
	dayTime, err := time.ParseInLocation("2006-01-02 15:04:05", nowDay+" 00:00:00", loc)
	if err != nil {
		return
	}
	var timeStartPoint int64
	var timeEndPoint int64
	oneYearPoint := dayTime.AddDate(-1, 0, 0).Unix()
	fiveYearPoint := dayTime.AddDate(-5, 0, 0).Unix()
	tenYearPoint := dayTime.AddDate(-10, 0, 0).Unix()
	twentyYearPoint := dayTime.AddDate(-20, 0, 0).Unix()

	db := readDb.Table("xt_patients").Where("status=1")
	countSQL := "SELECT nnd AS 'age',COUNT(*) AS 'count' FROM(" +
		"SELECT " +
		"CASE " +
		" WHEN first_dialysis_date<>0 AND first_dialysis_date>? THEN '1'" +
		" WHEN first_dialysis_date<>0 AND first_dialysis_date>? && first_dialysis_date<=? THEN '2'" +
		" WHEN first_dialysis_date<>0 AND first_dialysis_date>? && first_dialysis_date<=? THEN '3'" +
		" WHEN first_dialysis_date<>0 AND first_dialysis_date>? && first_dialysis_date<=? THEN '4'" +
		" WHEN first_dialysis_date<>0 AND first_dialysis_date<=? THEN '5'" +
		" ELSE '0'" +
		"END AS nnd FROM xt_patients WHERE status=1 "
	countParams := make([]interface{}, 0)
	countParams = append(countParams, oneYearPoint)
	countParams = append(countParams, fiveYearPoint)
	countParams = append(countParams, oneYearPoint)
	countParams = append(countParams, tenYearPoint)
	countParams = append(countParams, fiveYearPoint)
	countParams = append(countParams, twentyYearPoint)
	countParams = append(countParams, tenYearPoint)
	countParams = append(countParams, twentyYearPoint)

	if orgID > 0 {
		db = db.Where("user_org_id=?", orgID)
		countSQL += " AND user_org_id=?"
		countParams = append(countParams, orgID)
	}
	if lapseto > 0 {
		db = db.Where("lapseto=?", lapseto)
		countSQL += " AND lapseto=?"
		countParams = append(countParams, lapseto)
	}

	if age == 1 {
		timeStartPoint = dayTime.AddDate(-20, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-30, 0, 0).Unix()
		db = db.Where("birthday>? and birthday<=?", timeEndPoint, timeStartPoint)
		countSQL += " AND (birthday>? and birthday<=?)"
		countParams = append(countParams, timeEndPoint)
		countParams = append(countParams, timeStartPoint)
	} else if age == 2 {
		timeStartPoint = dayTime.AddDate(-30, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-40, 0, 0).Unix()
		db = db.Where("birthday>? and birthday<=?", timeEndPoint, timeStartPoint)
		countSQL += " AND (birthday>? and birthday<=?)"
		countParams = append(countParams, timeEndPoint)
		countParams = append(countParams, timeStartPoint)
	} else if age == 3 {
		timeStartPoint = dayTime.AddDate(-40, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-50, 0, 0).Unix()
		db = db.Where("birthday>? and birthday<=?", timeEndPoint, timeStartPoint)
		countSQL += " AND (birthday>? and birthday<=?)"
		countParams = append(countParams, timeEndPoint)
		countParams = append(countParams, timeStartPoint)
	} else if age == 4 {
		timeStartPoint = dayTime.AddDate(-10, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-50, 0, 0).Unix()
		db = db.Where("birthday>? or birthday<=?", timeStartPoint, timeEndPoint)
		countSQL += " AND (birthday>? or birthday<=?)"
		countParams = append(countParams, timeStartPoint)
		countParams = append(countParams, timeEndPoint)
	}

	if dialysisAge == 1 {
		timeStartPoint = dayTime.AddDate(-1, 0, 0).Unix()
		db = db.Where("first_dialysis_date>?", timeStartPoint)
		db = db.Where("first_dialysis_date<>0")
		countSQL += " AND (first_dialysis_date<>0 AND first_dialysis_date>?)"
		countParams = append(countParams, timeStartPoint)
	} else if dialysisAge == 2 {
		timeStartPoint = dayTime.AddDate(-1, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-5, 0, 0).Unix()
		db = db.Where("first_dialysis_date<>0")
		db = db.Where("first_dialysis_date>? and first_dialysis_date<=?", timeEndPoint, timeStartPoint)
		countSQL += " AND (first_dialysis_date<>0 AND first_dialysis_date>? and first_dialysis_date<=?)"
		countParams = append(countParams, timeEndPoint)
		countParams = append(countParams, timeStartPoint)
	} else if dialysisAge == 3 {
		timeStartPoint = dayTime.AddDate(-5, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-10, 0, 0).Unix()
		db = db.Where("first_dialysis_date<>0")
		db = db.Where("first_dialysis_date>? and first_dialysis_date<=?", timeEndPoint, timeStartPoint)
		countSQL += " AND (first_dialysis_date<>0 AND first_dialysis_date>? and first_dialysis_date<=?)"
		countParams = append(countParams, timeEndPoint)
		countParams = append(countParams, timeStartPoint)
	} else if dialysisAge == 4 {
		timeStartPoint = dayTime.AddDate(-10, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-20, 0, 0).Unix()
		db = db.Where("first_dialysis_date<>0")
		db = db.Where("first_dialysis_date>? and first_dialysis_date<=?", timeEndPoint, timeStartPoint)
		countSQL += " AND (first_dialysis_date<>0 AND first_dialysis_date>? and first_dialysis_date<=?)"
		countParams = append(countParams, timeEndPoint)
		countParams = append(countParams, timeStartPoint)
	} else if dialysisAge == 5 {
		timeStartPoint = dayTime.AddDate(-20, 0, 0).Unix()
		db = db.Where("first_dialysis_date<>0")
		db = db.Where("first_dialysis_date<=?", timeStartPoint)
		countSQL += " AND (first_dialysis_date<>0 AND first_dialysis_date<=?)"
		countParams = append(countParams, timeStartPoint)
	}

	if isStartTime {
		db = db.Where("created_time>=?", startTime)
		countSQL += " AND (created_time>=?)"
		countParams = append(countParams, startTime)
	}
	if isEndTime {
		db = db.Where("created_time<=?", endTime)
		countSQL += " AND (created_time<=?)"
		countParams = append(countParams, endTime)
	}
	countSQL += ")a GROUP BY nnd"
	err = readDb.Raw(countSQL, countParams...).Scan(&counts).Error
	if err != nil {
		return
	}

	offset := (page - 1) * limit
	err = db.Count(&total).Order("id desc").Offset(offset).Limit(limit).Find(&patients).Error
	if err != nil {
		return
	}

	return
}

type PAWeightDataStruct struct {
	models.Schedule

	Patient                  *models.Patients                `json:"patient" gorm:"foreignkey:PatientId;"`
	AssessmentAfterDislysis  *models.AssessmentAfterDislysis `gorm:"ForeignKey:AssessmentDate,PatientId;AssociationForeignKey:ScheduleDate,PatientId" json:"assessment_after_dislysis"`
	AssessmentBeforeDislysis *models.PredialysisEvaluation   `gorm:"ForeignKey:AssessmentDate,PatientId;AssociationForeignKey:ScheduleDate,PatientId" json:"assessment_before_dislysis"`
}

type PAWeightPieDataStruct struct {
	Weight int64 `json:"weight"`
	Count  int64 `json:"count"`
}

func (PAWeightDataStruct) TableName() string {
	return "xt_schedule"
}

func GetPAWeightData(orgID, page, limit, lapseto, age, startTime, endTime int64, isStartTime, isEndTime bool) (weight []*PAWeightDataStruct, dryweight []*PAWeightPieDataStruct, weightincrease []*PAWeightPieDataStruct, afterweight []*PAWeightPieDataStruct, total int64, err error) {
	loc, _ := time.LoadLocation("Local")
	nowTime := time.Now()
	nowDay := nowTime.Format("2006-01-02")
	dayTime, err := time.ParseInLocation("2006-01-02 15:04:05", nowDay+" 00:00:00", loc)
	if err != nil {
		return
	}
	var timeStartPoint int64
	var timeEndPoint int64

	dryCountSQL := "SELECT nnd AS 'weight',COUNT(*) AS 'count' FROM(" +
		"SELECT " +
		"CASE " +
		" WHEN abd.dry_weight<>0 and abd.dry_weight<40 THEN '1'" +
		" WHEN abd.dry_weight>=40 && abd.dry_weight<50 THEN '2'" +
		" WHEN abd.dry_weight>=50 && abd.dry_weight<60 THEN '3'" +
		" WHEN abd.dry_weight>=60 && abd.dry_weight<70 THEN '4'" +
		" WHEN abd.dry_weight>=70  THEN '5'" +
		" ELSE '0'" +
		"END AS nnd FROM xt_assessment_before_dislysis as abd JOIN xt_patients as p ON p.id=abd.patient_id and p.user_org_id=? WHERE p.status=1"
	dryCountParams := make([]interface{}, 0)
	dryCountParams = append(dryCountParams, orgID)

	increaseCountSQL := "SELECT nnd AS 'weight',COUNT(*) AS 'count' FROM(" +
		"SELECT " +
		"CASE " +
		" WHEN (abd.weight_before-abd.dry_weight)<1 THEN '1'" +
		" WHEN (abd.weight_before-abd.dry_weight)>=1 && (abd.weight_before-abd.dry_weight)<2 THEN '2'" +
		" WHEN (abd.weight_before-abd.dry_weight)>=2 && (abd.weight_before-abd.dry_weight)<3 THEN '3'" +
		" WHEN (abd.weight_before-abd.dry_weight)>=3 && (abd.weight_before-abd.dry_weight)<4 THEN '4'" +
		" WHEN (abd.weight_before-abd.dry_weight)>=4 THEN '5'" +
		" ELSE '0'" +
		"END AS nnd FROM xt_assessment_before_dislysis as abd JOIN xt_patients as p ON p.id=abd.patient_id and p.user_org_id=? WHERE p.status=1"
	increaseCountParams := make([]interface{}, 0)
	increaseCountParams = append(increaseCountParams, orgID)

	afterCountSQL := "SELECT nnd AS 'weight',COUNT(*) AS 'count' FROM(" +
		"SELECT " +
		"CASE " +
		" WHEN afd.weight_after<>0 and afd.weight_after<40 THEN '1'" +
		" WHEN afd.weight_after>=40 && afd.weight_after<50 THEN '2'" +
		" WHEN afd.weight_after>=50 && afd.weight_after<60 THEN '3'" +
		" WHEN afd.weight_after>=60 && afd.weight_after<70 THEN '4'" +
		" WHEN afd.weight_after>=70  THEN '5'" +
		" ELSE '0'" +
		"END AS nnd FROM xt_assessment_after_dislysis as afd JOIN xt_patients as p ON p.id=afd.patient_id and p.user_org_id=? WHERE p.status=1"
	afterCountParams := make([]interface{}, 0)
	afterCountParams = append(afterCountParams, orgID)

	db := readDb.Table("xt_schedule as c").Joins("JOIN xt_patients as p ON p.id=c.patient_id and p.user_org_id=?", orgID)
	if lapseto > 0 {
		db = db.Where("p.lapseto=?", lapseto)
		dryCountSQL += " AND p.lapseto=?"
		dryCountParams = append(dryCountParams, lapseto)
		increaseCountSQL += " AND p.lapseto=?"
		increaseCountParams = append(increaseCountParams, lapseto)
		afterCountSQL += " AND p.lapseto=?"
		afterCountParams = append(afterCountParams, lapseto)
	}

	if age == 1 {
		timeStartPoint = dayTime.AddDate(-20, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-30, 0, 0).Unix()
		db = db.Where("p.birthday>? and p.birthday<=?", timeEndPoint, timeStartPoint)
		dryCountSQL += " AND p.birthday>? and p.birthday<=?"
		dryCountParams = append(dryCountParams, timeEndPoint, timeStartPoint)
		increaseCountSQL += " AND p.birthday>? and p.birthday<=?"
		increaseCountParams = append(increaseCountParams, timeEndPoint, timeStartPoint)
		afterCountSQL += " AND p.birthday>? and p.birthday<=?"
		afterCountParams = append(afterCountParams, timeEndPoint, timeStartPoint)
	} else if age == 2 {
		timeStartPoint = dayTime.AddDate(-30, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-40, 0, 0).Unix()
		db = db.Where("p.birthday>? and p.birthday<=?", timeEndPoint, timeStartPoint)
		dryCountSQL += " AND p.birthday>? and p.birthday<=?"
		dryCountParams = append(dryCountParams, timeEndPoint, timeStartPoint)
		increaseCountSQL += " AND p.birthday>? and p.birthday<=?"
		increaseCountParams = append(increaseCountParams, timeEndPoint, timeStartPoint)
		afterCountSQL += " AND p.birthday>? and p.birthday<=?"
		afterCountParams = append(afterCountParams, timeEndPoint, timeStartPoint)
	} else if age == 3 {
		timeStartPoint = dayTime.AddDate(-40, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-50, 0, 0).Unix()
		db = db.Where("p.birthday>? and p.birthday<=?", timeEndPoint, timeStartPoint)
		dryCountSQL += " AND p.birthday>? and p.birthday<=?"
		dryCountParams = append(dryCountParams, timeEndPoint, timeStartPoint)
		increaseCountSQL += " AND p.birthday>? and p.birthday<=?"
		increaseCountParams = append(increaseCountParams, timeEndPoint, timeStartPoint)
		afterCountSQL += " AND p.birthday>? and p.birthday<=?"
		afterCountParams = append(afterCountParams, timeEndPoint, timeStartPoint)
	} else if age == 4 {
		timeStartPoint = dayTime.AddDate(-10, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-50, 0, 0).Unix()
		db = db.Where("p.birthday>? or p.birthday<=?", timeStartPoint, timeEndPoint)
		dryCountSQL += " AND (p.birthday>? or p.birthday<=?)"
		dryCountParams = append(dryCountParams, timeStartPoint, timeEndPoint)
		increaseCountSQL += " AND (p.birthday>? or p.birthday<=?)"
		increaseCountParams = append(increaseCountParams, timeStartPoint, timeEndPoint)
		afterCountSQL += " AND (p.birthday>? or p.birthday<=?)"
		afterCountParams = append(afterCountParams, timeStartPoint, timeEndPoint)
	}

	if isStartTime {
		db = db.Where("c.schedule_date>=?", startTime)
		dryCountSQL += " AND abd.assessment_date>=?"
		dryCountParams = append(dryCountParams, startTime)
		increaseCountSQL += " AND abd.assessment_date>=?"
		increaseCountParams = append(increaseCountParams, startTime)
		afterCountSQL += " AND afd.assessment_date>=?"
		afterCountParams = append(afterCountParams, startTime)
	}
	if isEndTime {
		db = db.Where("c.schedule_date<=?", endTime)
		dryCountSQL += " AND abd.assessment_date<=?"
		dryCountParams = append(dryCountParams, endTime)
		increaseCountSQL += " AND abd.assessment_date<=?"
		increaseCountParams = append(increaseCountParams, endTime)
		afterCountSQL += " AND afd.assessment_date<=?"
		afterCountParams = append(afterCountParams, endTime)
	}

	dryCountSQL += ")a GROUP BY nnd"
	err = readDb.Raw(dryCountSQL, dryCountParams...).Scan(&dryweight).Error
	if err != nil {
		return
	}

	increaseCountSQL += ")a GROUP BY nnd"
	err = readDb.Raw(increaseCountSQL, increaseCountParams...).Scan(&weightincrease).Error
	if err != nil {
		return
	}

	afterCountSQL += ")a GROUP BY nnd"
	err = readDb.Raw(afterCountSQL, afterCountParams...).Scan(&afterweight).Error
	if err != nil {
		return
	}

	db = db.Where("c.status=1")

	offset := (page - 1) * limit
	err = db.Select("c.id, c.user_org_id, c.partition_id, c.bed_id, c.patient_id, c.schedule_date, c.schedule_type, c.schedule_week, c.mode_id, c.status, c.created_time, c.updated_time").
		Preload("Patient", "user_org_id = ? AND status = 1", orgID).
		Preload("AssessmentAfterDislysis", "user_org_id = ? AND status = 1", orgID).
		Preload("AssessmentBeforeDislysis", "user_org_id = ? AND status = 1", orgID).
		Order("c.schedule_date desc, c.schedule_type desc, c.id desc").Count(&total).Offset(offset).Limit(limit).Find(&weight).Error
	return
}

type PABloodPressureDataStruct struct {
	models.Schedule

	Patient                  *models.Patients                `json:"patient" gorm:"foreignkey:PatientId;"`
	AssessmentAfterDislysis  *models.AssessmentAfterDislysis `gorm:"ForeignKey:AssessmentDate,PatientId;AssociationForeignKey:ScheduleDate,PatientId" json:"assessment_after_dislysis"`
	AssessmentBeforeDislysis *models.PredialysisEvaluation   `gorm:"ForeignKey:AssessmentDate,PatientId;AssociationForeignKey:ScheduleDate,PatientId" json:"assessment_before_dislysis"`
	MonitoringRecord         []*models.MonitoringRecord      `gorm:"ForeignKey:MonitoringDate,PatientId;AssociationForeignKey:ScheduleDate,PatientId" json:"monitor_records"`
}

func (PABloodPressureDataStruct) TableName() string {
	return "xt_schedule"
}

type PABloodPressurePieDataStruct struct {
	Blood int64 `json:"blood"`
	Count int64 `json:"count"`
}

func GetPABloodPressureData(orgID, page, limit, lapseto, dialysisStage, startTime, endTime int64, isStartTime, isEndTime bool) (bloodPressures []*PABloodPressureDataStruct, bps []*PABloodPressurePieDataStruct, total int64, err error) {

	db := readDb.Table("xt_schedule as c").Joins("JOIN xt_patients as p ON p.id=c.patient_id and p.user_org_id=?", orgID)

	countSQL := "SELECT lmr.* from xt_monitoring_record as lmr JOIN xt_patients as p ON p.id=lmr.patient_id and p.user_org_id=? "
	countParams := make([]interface{}, 0)
	countParams = append(countParams, orgID)

	if dialysisStage == 1 {
		db = db.Joins("JOIN xt_assessment_before_dislysis as abd ON abd.patient_id=c.patient_id and abd.assessment_date=c.schedule_date and abd.user_org_id=?", orgID)
		countSQL += "JOIN xt_assessment_before_dislysis as abd ON abd.patient_id=lmr.patient_id and abd.assessment_date=lmr.monitoring_date and abd.user_org_id=?"
		countParams = append(countParams, orgID)
	} else if dialysisStage == 2 {
		db = db.Joins("JOIN xt_assessment_after_dislysis as aad ON aad.patient_id=c.patient_id and aad.assessment_date=c.schedule_date and aad.user_org_id=?", orgID)
		countSQL += "JOIN xt_assessment_after_dislysis as aad ON aad.patient_id=lmr.patient_id and aad.assessment_date=lmr.monitoring_date and aad.user_org_id=?"
		countParams = append(countParams, orgID)
	}

	countSQL += " WHERE lmr.user_org_id=? AND lmr.status=1"
	countParams = append(countParams, orgID)

	if lapseto > 0 {
		db = db.Where("p.lapseto=?", lapseto)
		countSQL += " AND p.lapseto=?"
		countParams = append(countParams, lapseto)
	}

	if isStartTime {
		db = db.Where("c.schedule_date>=?", startTime)
		countSQL += " AND lmr.monitoring_date>=?"
		countParams = append(countParams, startTime)
	}
	if isEndTime {
		db = db.Where("c.schedule_date<=?", endTime)
		countSQL += " AND lmr.monitoring_date<=?"
		countParams = append(countParams, endTime)
	}
	countSQL += "  order by lmr.systolic_blood_pressure desc, lmr.diastolic_blood_pressure desc"
	lastSQL := "SELECT nnd as 'blood' ,COUNT(*) AS 'count' FROM(" +
		"SELECT " +
		"CASE " +
		" WHEN systolic_blood_pressure<>0 && diastolic_blood_pressure <> 0 && systolic_blood_pressure<140 && diastolic_blood_pressure<90 THEN '1'" +
		" WHEN systolic_blood_pressure>=160 && diastolic_blood_pressure>=100 THEN '2'" +
		" WHEN systolic_blood_pressure<160 && systolic_blood_pressure>=140 && diastolic_blood_pressure<100 && diastolic_blood_pressure>=90 THEN '3'" +
		" ELSE '0' " +
		"END AS nnd FROM (" + countSQL + ") b group by monitoring_date, patient_id)a GROUP BY nnd"
	err = readDb.Raw(lastSQL, countParams...).Find(&bps).Error
	if err != nil {
		return
	}

	db = db.Where("c.status=1")

	offset := (page - 1) * limit
	err = db.Select("c.id, c.user_org_id, c.partition_id, c.bed_id, c.patient_id, c.schedule_date, c.schedule_type, c.schedule_week, c.mode_id, c.status, c.created_time, c.updated_time").
		Preload("Patient", "user_org_id = ? AND status = 1", orgID).
		Preload("AssessmentAfterDislysis", "user_org_id = ? AND status = 1", orgID).
		Preload("AssessmentBeforeDislysis", "user_org_id = ? AND status = 1", orgID).
		Preload("MonitoringRecord", "user_org_id = ? AND status = 1", orgID).
		Order("c.schedule_date desc, c.schedule_type desc, c.id desc").Count(&total).Offset(offset).Limit(limit).Find(&bloodPressures).Error
	return
}

type PAComplicationDataStruct struct {
	models.Schedule

	Patient                  *models.Patients                `json:"patient" gorm:"foreignkey:PatientId;"`
	AssessmentAfterDislysis  *models.AssessmentAfterDislysis `gorm:"ForeignKey:AssessmentDate,PatientId;AssociationForeignKey:ScheduleDate,PatientId" json:"assessment_after_dislysis"`
	AssessmentBeforeDislysis *models.PredialysisEvaluation   `gorm:"ForeignKey:AssessmentDate,PatientId;AssociationForeignKey:ScheduleDate,PatientId" json:"assessment_before_dislysis"`
}

type PAComplicationPieDataStruct struct {
	Complication int64  `json:"complication"`
	Name         string `json:"name"`
	Count        int64  `json:"count"`
}

func GetPAComplicationData(orgID, page, limit, age, statisticalState, startTime, endTime int64, isStartTime, isEndTime bool) (complications []*PAComplicationDataStruct, pcps []*PAComplicationPieDataStruct, total int64, err error) {
	db := readDb.Table("xt_schedule as c").Joins("JOIN xt_patients as p ON p.id=c.patient_id and p.user_org_id=?", orgID)
	if statisticalState == 1 {
		db = db.Joins("JOIN xt_assessment_before_dislysis as abd ON abd.patient_id=c.patient_id and abd.assessment_date=c.schedule_date and abd.user_org_id=?", orgID)
	} else if statisticalState == 2 {
		db = db.Joins("JOIN xt_assessment_after_dislysis as aad ON aad.patient_id=c.patient_id and aad.assessment_date=c.schedule_date and aad.user_org_id=?", orgID)
	} else {
		return
	}

	var dc models.Dataconfig
	err = readDb.Model(&models.Dataconfig{}).Where("module='hemodialysis' AND field_name='complication'").First(&dc).Error
	if err != nil {
		return
	}

	ComplicationsMap := make([]map[string]interface{}, 0)
	if dc.ID > 0 {
		var dcs []*models.Dataconfig
		err = readDb.Model(&models.Dataconfig{}).Where("parent_id=? and org_id in (0,?) and status = 1 ", dc.ID, orgID).Order("orders desc, id asc").Find(&dcs).Error
		if err != nil {
			return
		}

		if len(dcs) > 0 {
			for _, item := range dcs {
				mapItem := map[string]interface{}{"id": item.ID, "name": item.Name}
				ComplicationsMap = append(ComplicationsMap, mapItem)
			}

		}
	}

	sqlMap := make(map[int64]string, 0)
	countParamsMap := make(map[int64][]interface{}, 0)
	for _, citem := range ComplicationsMap {
		mapID := citem["id"].(int64)
		mapName := citem["name"].(string)
		countParamsMap[mapID] = make([]interface{}, 0)
		sqlMap[mapID] = fmt.Sprintf(" SELECT COUNT(ad.id) as count, '%d' AS complication, '%s' AS `name` FROM ", mapID, mapName)
		if statisticalState == 1 {
			sqlMap[mapID] += "xt_assessment_before_dislysis AS ad"
		} else {
			sqlMap[mapID] += "xt_assessment_after_dislysis AS ad"
		}
		likeKeyMap := make([]interface{}, 0)
		likeKeyMap = append(likeKeyMap, mapName)
		likeKeyMap = append(likeKeyMap, mapName+",%")
		likeKeyMap = append(likeKeyMap, "%,"+mapName)
		likeKeyMap = append(likeKeyMap, "%,"+mapName+",%")
		sqlMap[mapID] += " JOIN xt_patients as p ON p.id=ad.patient_id and p.user_org_id=? WHERE ad.user_org_id=? AND (complication = ? OR complication LIKE ? OR complication LIKE ? OR complication LIKE ?)"
		countParamsMap[mapID] = append(countParamsMap[mapID], orgID)
		countParamsMap[mapID] = append(countParamsMap[mapID], orgID)
		countParamsMap[mapID] = append(countParamsMap[mapID], likeKeyMap...)

	}

	loc, _ := time.LoadLocation("Local")
	nowTime := time.Now()
	nowDay := nowTime.Format("2006-01-02")
	dayTime, err := time.ParseInLocation("2006-01-02 15:04:05", nowDay+" 00:00:00", loc)
	if err != nil {
		return
	}
	var timeStartPoint int64
	var timeEndPoint int64

	if age == 1 {
		timeStartPoint = dayTime.AddDate(-20, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-30, 0, 0).Unix()
		db = db.Where("p.birthday>? and p.birthday<=?", timeEndPoint, timeStartPoint)
		for key := range sqlMap {
			sqlMap[key] += " AND p.birthday>? and p.birthday<=?"
			countParamsMap[key] = append(countParamsMap[key], timeEndPoint)
			countParamsMap[key] = append(countParamsMap[key], timeStartPoint)
		}
	} else if age == 2 {
		timeStartPoint = dayTime.AddDate(-30, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-40, 0, 0).Unix()
		db = db.Where("p.birthday>? and p.birthday<=?", timeEndPoint, timeStartPoint)
		for key := range sqlMap {
			sqlMap[key] += " AND p.birthday>? and p.birthday<=?"
			countParamsMap[key] = append(countParamsMap[key], timeEndPoint)
			countParamsMap[key] = append(countParamsMap[key], timeStartPoint)
		}
	} else if age == 3 {
		timeStartPoint = dayTime.AddDate(-40, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-50, 0, 0).Unix()
		db = db.Where("p.birthday>? and p.birthday<=?", timeEndPoint, timeStartPoint)
		for key := range sqlMap {
			sqlMap[key] += " AND p.birthday>? and p.birthday<=?"
			countParamsMap[key] = append(countParamsMap[key], timeEndPoint)
			countParamsMap[key] = append(countParamsMap[key], timeStartPoint)
		}
	} else if age == 4 {
		timeStartPoint = dayTime.AddDate(-10, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-50, 0, 0).Unix()
		db = db.Where("p.birthday>? or p.birthday<=?", timeStartPoint, timeEndPoint)
		for key := range sqlMap {
			sqlMap[key] += " AND (p.birthday>? or p.birthday<=?)"
			countParamsMap[key] = append(countParamsMap[key], timeStartPoint)
			countParamsMap[key] = append(countParamsMap[key], timeEndPoint)
		}
	}

	if isStartTime {
		db = db.Where("c.schedule_date>=?", startTime)
		for key := range sqlMap {
			sqlMap[key] += " AND ad.assessment_date>=?"
			countParamsMap[key] = append(countParamsMap[key], startTime)
		}
	}
	if isEndTime {
		db = db.Where("c.schedule_date<=?", endTime)
		for key := range sqlMap {
			sqlMap[key] += " AND ad.assessment_date<=?"
			countParamsMap[key] = append(countParamsMap[key], endTime)
		}
	}

	db = db.Where("c.status=1")
	for key := range sqlMap {
		sqlMap[key] += " AND ad.status=1"
		var pcp []*PAComplicationPieDataStruct
		err = readDb.Raw(sqlMap[key], countParamsMap[key]...).Find(&pcp).Error
		if err != nil {
			return
		}
		for _, item := range pcp {
			pcps = append(pcps, item)
		}
	}

	offset := (page - 1) * limit
	err = db.Select("c.id, c.user_org_id, c.partition_id, c.bed_id, c.patient_id, c.schedule_date, c.schedule_type, c.schedule_week, c.mode_id, c.status, c.created_time, c.updated_time").
		Preload("Patient", "user_org_id = ? AND status = 1", orgID).
		Preload("AssessmentAfterDislysis", "user_org_id = ? AND status = 1", orgID).
		Preload("AssessmentBeforeDislysis", "user_org_id = ? AND status = 1", orgID).
		Order("c.schedule_date desc, c.schedule_type desc, c.id desc").Count(&total).Offset(offset).Limit(limit).Find(&complications).Error
	return
}

type PADiseasesCountPieStruct struct {
	Diseases int64 `json:"diseases"`
	Count    int64 `json:"count"`
}

func GetPAInfectiousDiseasesData(orgID, page, limit, lapseto, age, diseasesID, startTime, endTime int64, isStartTime, isEndTime bool) (patients []*models.Patients, dsp []*PADiseasesCountPieStruct, total int64, err error) {
	loc, _ := time.LoadLocation("Local")
	nowTime := time.Now()
	nowDay := nowTime.Format("2006-01-02")
	dayTime, err := time.ParseInLocation("2006-01-02 15:04:05", nowDay+" 00:00:00", loc)
	if err != nil {
		return
	}
	var timeStartPoint int64
	var timeEndPoint int64

	db := readDb.Table("xt_patients as p")

	countSQL := "SELECT count(pid.id) as count, pid.disease_id as diseases FROM xt_patients as p JOIN xt_patients_infectious_diseases as pid ON pid.patient_id=p.id"
	countParams := make([]interface{}, 0)

	if diseasesID > 0 {
		db = db.Joins("JOIN xt_patients_infectious_diseases as pid ON pid.patient_id=p.id AND pid.disease_id=? AND pid.status=1", diseasesID)
		countSQL += " AND pid.disease_id=? "
		countParams = append(countParams, diseasesID)
	}
	countSQL += " AND pid.status=1 WHERE p.user_org_id = ? AND p.status=1"
	countParams = append(countParams, orgID)

	db = db.Where("p.user_org_id = ? AND p.status=1", orgID)
	if lapseto > 0 {
		db = db.Where("p.lapseto=?", lapseto)
		countSQL += " AND p.lapseto=?"
		countParams = append(countParams, lapseto)
	}

	if age == 1 {
		timeStartPoint = dayTime.AddDate(-20, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-30, 0, 0).Unix()
		db = db.Where("p.birthday>? and p.birthday<=?", timeEndPoint, timeStartPoint)
		countSQL += " AND p.birthday>? and p.birthday<=?"
		countParams = append(countParams, timeEndPoint)
		countParams = append(countParams, timeStartPoint)
	} else if age == 2 {
		timeStartPoint = dayTime.AddDate(-30, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-40, 0, 0).Unix()
		db = db.Where("p.birthday>? and p.birthday<=?", timeEndPoint, timeStartPoint)
		countSQL += " AND p.birthday>? and p.birthday<=?"
		countParams = append(countParams, timeEndPoint)
		countParams = append(countParams, timeStartPoint)
	} else if age == 3 {
		timeStartPoint = dayTime.AddDate(-40, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-50, 0, 0).Unix()
		db = db.Where("p.birthday>? and p.birthday<=?", timeEndPoint, timeStartPoint)
		countSQL += " AND p.birthday>? and p.birthday<=?"
		countParams = append(countParams, timeEndPoint)
		countParams = append(countParams, timeStartPoint)
	} else if age == 4 {
		timeStartPoint = dayTime.AddDate(-10, 0, 0).Unix()
		timeEndPoint = dayTime.AddDate(-50, 0, 0).Unix()
		db = db.Where("p.birthday>? or p.birthday<=?", timeStartPoint, timeEndPoint)
		countSQL += " AND (p.birthday>? or p.birthday<=?)"
		countParams = append(countParams, timeStartPoint)
		countParams = append(countParams, timeEndPoint)
	}

	if isStartTime {
		db = db.Where("p.created_time>=?", startTime)
		countSQL += " AND p.created_time>=?"
		countParams = append(countParams, startTime)
	}
	if isEndTime {
		db = db.Where("p.created_time<=?", endTime)
		countSQL += " AND p.created_time<=?"
		countParams = append(countParams, endTime)
	}

	countSQL += " GROUP BY pid.disease_id"
	err = readDb.Raw(countSQL, countParams...).Find(&dsp).Error
	if err != nil {
		return
	}

	offset := (page - 1) * limit
	err = db.Select("p.id, p.user_org_id, p.user_id, p.avatar, p.patient_type, p.dialysis_no, p.admission_number, p.source, p.lapseto, p.partition_id, p.bed_id, p.name, p.alias, p.gender, p.nation, p.native_place, p.marital_status, p.id_card_no, p.birthday, p.reimbursement_way_id, p.health_care_type, p.health_care_no, p.health_care_due_date, p.height, p.blood_type, p.rh, p.health_care_due_alert_date, p.education_level, p.profession, p.phone, p.home_telephone, p.relative_phone, p.relative_relations, p.home_address, p.work_unit, p.unit_address, p.children, p.receiving_date, p.is_hospital_first_dialysis, p.first_dialysis_date, p.first_dialysis_hospital, p.predialysis_condition, p.pre_hospital_dialysis_frequency, p.pre_hospital_dialysis_times, p.hospital_first_dialysis_date, p.induction_period, p.initial_dialysis, p.total_dialysis, p.attending_doctor_id, p.head_nurse_id, p.evaluate, p.diagnose, p.remark, p.registrars_id, p.registrars, p.qr_code, p.binding_state, p.patient_complains, p.present_history, p.past_history, p.temperature, p.pulse, p.respiratory, p.sbp, p.dbp, p.status, p.created_time, p.updated_time").
		Preload("Contagions", "status = 1").
		Count(&total).Order("p.id desc").Offset(offset).Limit(limit).Find(&patients).Error

	if err != nil {
		return
	}

	return
}

func GetPersonLapsetoData(orgID, patientID, page, limit int64) (*models.Patients, []*models.PatientLapseto, int64, error) {
	var patient models.Patients
	var pls []*models.PatientLapseto
	var total int64
	var err error

	err = readDb.Model(&models.Patients{}).Where("user_org_id =? and id=?", orgID, patientID).First(&patient).Error
	if patient.ID == 0 {
		return nil, pls, total, err
	}
	offset := (page - 1) * limit
	err = readDb.Model(&models.PatientLapseto{}).Where("patient_id=? and status=1", patientID).Count(&total).Offset(offset).Limit(limit).Order("lapseto_time desc, id desc").Find(&pls).Error
	if err != nil {
		return nil, pls, total, err
	}
	return &patient, pls, total, err
}

func GetPersonWeightData(orgID, patientID, page, limit, startTime, endTime int64, isStartTime, isEndTime bool) (*models.Patients, []*PAWeightDataStruct, []*PAWeightDataStruct, int64, error) {
	var patient models.Patients
	var weight []*PAWeightDataStruct
	var pie []*PAWeightDataStruct
	var total int64
	var err error
	err = readDb.Model(&models.Patients{}).Where("user_org_id =? and id=?", orgID, patientID).First(&patient).Error
	if patient.ID == 0 {
		return nil, weight, pie, total, err
	}

	db := readDb.Table("xt_schedule as c").Joins("JOIN xt_patients as p ON p.id=c.patient_id and p.user_org_id=? and p.id=?", orgID, patientID)

	db = db.Where("c.patient_id=?", patientID)
	if isStartTime {
		db = db.Where("c.schedule_date>=?", startTime)
	}
	if isEndTime {
		db = db.Where("c.schedule_date<=?", endTime)
	}

	db = db.Where("c.status=1")

	offset := (page - 1) * limit
	err = db.Select("c.id, c.user_org_id, c.partition_id, c.bed_id, c.patient_id, c.schedule_date, c.schedule_type, c.schedule_week, c.mode_id, c.status, c.created_time, c.updated_time").
		Preload("AssessmentAfterDislysis", "user_org_id = ? AND status = 1", orgID).
		Preload("AssessmentBeforeDislysis", "user_org_id = ? AND status = 1", orgID).
		Order("c.schedule_date desc, c.schedule_type desc, c.id desc").Count(&total).Offset(offset).Limit(limit).Find(&weight).Error
	if err != nil {
		return nil, weight, pie, total, err
	}

	err = db.Select("c.id, c.user_org_id, c.partition_id, c.bed_id, c.patient_id, c.schedule_date, c.schedule_type, c.schedule_week, c.mode_id, c.status, c.created_time, c.updated_time").
		Preload("AssessmentAfterDislysis", "user_org_id = ? AND status = 1", orgID).
		Preload("AssessmentBeforeDislysis", "user_org_id = ? AND status = 1", orgID).
		Order("c.schedule_date asc, c.schedule_type asc, c.id asc").Find(&pie).Error
	if err != nil {
		return nil, weight, pie, total, err
	}
	return &patient, weight, pie, total, err
}

func GetPersonBloodPressureData(orgID, patientID, page, limit, startTime, endTime int64, isStartTime, isEndTime bool) (*models.Patients, []*PABloodPressureDataStruct, []*PABloodPressureDataStruct, int64, error) {
	var patient models.Patients
	var bloodPressures []*PABloodPressureDataStruct
	var lines []*PABloodPressureDataStruct
	var total int64
	var err error
	err = readDb.Model(&models.Patients{}).Where("user_org_id =? and id=?", orgID, patientID).First(&patient).Error
	if patient.ID == 0 {
		return nil, bloodPressures, lines, total, err
	}

	db := readDb.Table("xt_schedule as c").Joins("JOIN xt_patients as p ON p.id=c.patient_id and p.user_org_id=? and c.patient_id=? and p.id = ?", orgID, patientID, patientID)

	if isStartTime {
		db = db.Where("c.schedule_date>=?", startTime)
	}
	if isEndTime {
		db = db.Where("c.schedule_date<=?", endTime)
	}

	db = db.Where("c.patient_id=? AND c.status=1", patientID)

	err = db.Select("c.id, c.user_org_id, c.partition_id, c.bed_id, c.patient_id, c.schedule_date, c.schedule_type, c.schedule_week, c.mode_id, c.status, c.created_time, c.updated_time").
		Preload("AssessmentAfterDislysis", "user_org_id = ? AND status = 1", orgID).
		Preload("AssessmentBeforeDislysis", "user_org_id = ? AND status = 1", orgID).
		Preload("MonitoringRecord", "user_org_id = ? AND status = 1", orgID).
		Order("c.schedule_date asc, c.schedule_type asc, c.id asc").Find(&lines).Error
	if err != nil {
		return &patient, bloodPressures, lines, total, err
	}

	offset := (page - 1) * limit
	err = db.Select("c.id, c.user_org_id, c.partition_id, c.bed_id, c.patient_id, c.schedule_date, c.schedule_type, c.schedule_week, c.mode_id, c.status, c.created_time, c.updated_time").
		Preload("Patient", "user_org_id = ? AND status = 1", orgID).
		Preload("AssessmentAfterDislysis", "user_org_id = ? AND status = 1", orgID).
		Preload("AssessmentBeforeDislysis", "user_org_id = ? AND status = 1", orgID).
		Preload("MonitoringRecord", "user_org_id = ? AND status = 1", orgID).
		Order("c.schedule_date desc, c.schedule_type desc, c.id desc").Count(&total).Offset(offset).Limit(limit).Find(&bloodPressures).Error
	return &patient, bloodPressures, lines, total, err
}

func GetPersonICData(orgID, patientID, page, limit int64) (*models.Patients, []*models.Inspection, []*models.InspectionReference, int64, error) {
	var patient models.Patients
	var inspections []*models.Inspection
	var references []*models.InspectionReference
	var total int64
	var err error
	err = readDb.Model(&models.Patients{}).Where("user_org_id =? and id=?", orgID, patientID).First(&patient).Error
	if patient.ID == 0 {
		return nil, inspections, references, total, err
	}

	err = readDb.Table("xt_inspection_reference").Order("project_id").Find(&references).Error
	if err != nil || len(references) == 0 {
		return nil, inspections, references, total, err
	}

	db := readDb.Table("xt_inspection as i").Where("i.patient_id=?", patientID)
	if orgID > 0 {
		db = db.Where("i.org_id=?", orgID)
	}
	db = db.Where("i.status=1")

	offset := (page - 1) * limit

	var ds []*PIInspectionPageStruct
	err = db.Select("i.inspect_date").Group("inspect_date").Count(&total).Order("inspect_date desc, i.created_time desc, i.id asc").Offset(offset).Limit(limit).Find(&ds).Error
	if err != nil {
		return nil, inspections, references, total, err
	}

	dates := make([]int64, 0)
	if len(ds) > 0 {
		for _, d := range ds {
			dates = append(dates, d.InspectDate)
		}

		db = db.Where("i.inspect_date IN (?)", dates)
	}

	err = db.Select("i.id, i.patient_id, org_id, i.project_id, i.item_id, i.item_name, i.project_name, i.inspect_type, i.inspect_value, i.inspect_date, i.status, i.created_time, i.updated_time").Order("inspect_date desc, created_time desc, id asc, patient_id asc").Find(&inspections).Error
	if err != nil {
		return nil, inspections, references, total, err
	}

	return &patient, inspections, references, total, err
}

func GetPersonAdviceData(orgID, patientID, page, limit, adviceType, medicalType, startTime, endTime int64, isStartTime, isEndTime bool) (*models.Patients, []*models.DoctorAdvice, int64, error) {
	var patient models.Patients
	var advices []*models.DoctorAdvice
	var total int64
	var err error
	err = readDb.Model(&models.Patients{}).Where("user_org_id =? and id=?", orgID, patientID).First(&patient).Error
	if patient.ID == 0 {
		return nil, advices, total, err
	}

	db := readDb.Table("xt_doctor_advice as da").Where("da.patient_id=? and da.delivery_way='口服'", patientID)
	if orgID > 0 {
		db = db.Where("da.user_org_id=?", orgID)
	}

	db = db.Where("da.status=1")

	if adviceType > 0 {
		db = db.Where("da.advice_type=?", adviceType)
	} else {
		db = db.Where("da.advice_type IN (1,2)")
	}

	if isStartTime {
		db = db.Where("da.advice_date>=?", startTime)
	}
	if isEndTime {
		db = db.Where("da.advice_date<=?", endTime)
	}

	offset := (page - 1) * limit

	var groups []*models.DoctorAdvice
	err = db.Select("da.id, da.user_org_id, da.patient_id, da.advice_type, da.advice_date, da.record_date, da.start_time, da.advice_name, da.advice_desc, da.reminder_date, da.drug_spec, da.drug_spec_unit, da.single_dose, da.single_dose_unit, da.prescribing_number, da.prescribing_number_unit, da.delivery_way, da.execution_frequency, da.advice_doctor, da.status, da.created_time,da.updated_time, da.advice_affirm, da.remark, da.stop_time, da.stop_reason, da.stop_doctor, da.stop_state, da.parent_id, da.execution_time, da.execution_staff, da.execution_state, da.checker, da.check_state, da.check_time, da.groupno, IF(da.parent_id > 0, da.parent_id, da.id) as advice_order").Group("da.groupno").Count(&total).Order("da.start_time desc, da.groupno desc, advice_order desc, da.id asc").Offset(offset).Limit(limit).Find(&groups).Error
	if err != nil {
		return nil, advices, total, err
	}

	if len(groups) > 0 {
		gs := make([]int64, 0)
		for _, g := range groups {
			gs = append(gs, g.GroupNo)
		}
		db = db.Where("da.groupno IN (?)", gs)
	}

	err = db.Select("da.id, da.user_org_id, da.patient_id, da.advice_type, da.advice_date, da.record_date, da.start_time, da.advice_name, da.advice_desc, da.reminder_date, da.drug_spec, da.drug_spec_unit, da.single_dose, da.single_dose_unit, da.prescribing_number, da.prescribing_number_unit, da.delivery_way, da.execution_frequency, da.advice_doctor, da.status, da.created_time,da.updated_time, da.advice_affirm, da.remark, da.stop_time, da.stop_reason, da.stop_doctor, da.stop_state, da.parent_id, da.execution_time, da.execution_staff, da.execution_state, da.checker, da.check_state, da.check_time, da.groupno, IF(da.parent_id > 0, da.parent_id, da.id) as advice_order").Order("da.start_time desc, da.groupno desc, advice_order desc, da.id asc").Find(&advices).Error
	if err != nil {
		return nil, advices, total, err
	}

	return &patient, advices, total, err
}
