package schedule_dialysis

import (
	"XT_New/models"
	p_service "XT_New/service"
	"XT_New/utils"
	"time"

	"github.com/jinzhu/gorm"
)

func GetSchedules(orgID int64, schIDs []string) ([]*ScheduleVM, error) {
	recordDateStr := time.Now().Format("2006-01-02")
	recordDate, _ := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
	var schedules []*ScheduleVM
	db := p_service.XTReadDB()
	err := db.Model(&ScheduleVM{}).
		Preload("Patient", "user_org_id = ? AND status = 1", orgID).
		Preload("DialysisOrder", func(db *gorm.DB) *gorm.DB {
			return db.Where("user_org_id = ? AND status = 1", orgID).Preload("DeviceNumber", "org_id = ? AND status = 1", orgID)
		}).
		Preload("Prescription", "user_org_id = ? AND status = 1", orgID).
		Preload("ReceiveAssessment", "user_org_id = ? AND status = 1", orgID).
		Preload("XtReceiveTreatmentAsses", "user_org_id = ? AND status = 1", orgID).
		Preload("AssessmentBeforeDislysis", func(db *gorm.DB) *gorm.DB {
			return db.Where("user_org_id = ? AND status = 1", orgID)
		}).
		Preload("AssessmentAfterDislysis", "user_org_id = ? AND status = 1", orgID).
		Preload("LastAfterWeight", func(db *gorm.DB) *gorm.DB {
			return db.Where("user_org_id = ? and status = 1 and assessment_date < ?", orgID, recordDate.Unix())
		}).Preload("MonitoringRecords", func(db *gorm.DB) *gorm.DB {
		return db.Where("user_org_id = ? AND status = 1", orgID).
			Order("operate_time asc")
	}).
		Preload("DeviceNumber", "org_id = ? AND status = 1", orgID).
		Preload("DeviceZone", "org_id = ? AND status = 1", orgID).
		Preload("DoubleCheck", "user_org_id = ? AND status = 1", orgID).
		Preload("Summer", "user_org_id = ? AND status = 1", orgID).
		Preload("Advices", func(db *gorm.DB) *gorm.DB {
			return db.Select("id, user_org_id, patient_id, advice_type, advice_date, record_date, start_time, drug_spec_unit,advice_name,advice_desc, reminder_date, drug_spec, drug_spec_unit, single_dose, single_dose_unit, prescribing_number, prescribing_number_unit, delivery_way, execution_frequency, advice_doctor, status, created_time,updated_time, advice_affirm, remark, stop_time, stop_reason, stop_doctor, stop_state, parent_id, execution_time, execution_staff, execution_state, checker, check_state, check_time, groupno, IF(parent_id > 0, parent_id, id) as advice_order").
				Where("user_org_id = ? AND advice_type = 2 AND status = 1", orgID).
				Order("start_time asc, groupno desc, advice_order desc, id asc")
		}).
		Where("user_org_id = ? AND status = 1 AND id in (?)", orgID, schIDs).
		Find(&schedules).
		Error
	if err != nil {
		return nil, err
	}
	return schedules, nil
}

func GetMedicalStaffs(orgID int64, appID int64) ([]*MedicalStaffVM, error) {
	var staffs []*MedicalStaffVM
	db := p_service.UserReadDB()
	// err := db.Table("sgj_user_admin_role as uar").
	// 	Joins("JOIN sgj_user_admin as ua ON ua.id = uar.admin_user_id").
	// 	Joins("LEFT JOIN sgj_user_admin_electronic_signature as es ON es.creator = uar.admin_user_id and es.status = 1").
	// 	Where("uar.status = 1 and uar.org_id = ? and uar.app_id = ? and uar.user_type IN (2,3) and ua.status = 1", orgID, appID).
	// 	Where("uar.status = 1 and uar.org_id = ? and uar.app_id = ? and ua.status = 1", orgID, appID).
	// 	Select("ua.id, uar.user_name as name, uar.user_type, es.url as es_url").
	// 	Scan(&staffs).
	// 	Error

	err := db.Table("sgj_user_admin_electronic_signature").
		Where("org_id=? and app_id=? and status=1", orgID, appID).
		Select("creator as id, url as es_url").Scan(&staffs).Error

	if err != nil {
		return nil, err
	}
	return staffs, nil
}

type AdminUserList struct {
	Id       int64  `json:"id"`
	Name     string `json:"name"`
	UserType int64  `json:"user_type"`
}
type AdminUserListTwo struct {
	Id       int64  `json:"id"`
	Name     string `json:"name"`
	UserType int64  `json:"user_type"`
	Url      string `json:"url"`
}

func GetAllAdminUsers(orgId int64, appid int64) (list []*AdminUserList, err error) {
	db := p_service.UserReadDB()
	err = db.Table("sgj_user_admin_role as uar").Joins("JOIN sgj_user_admin as ua ON ua.id = uar.admin_user_id").Where("uar.status=1 and uar.org_id=? and uar.app_id =? and ua.status=1", orgId, appid).Select("ua.id, uar.user_name as name, uar.user_type").Scan(&list).Error
	return
}

func GetAllName(orgId int64, appid int64) (list []AdminUserListTwo, err error) {
	db := p_service.UserReadDB()
	err = db.Table("sgj_user_admin_role as uar").Joins("left join sgj_user_admin as ua on ua.id = uar.admin_user_id").Joins("left join sgj_user_admin_electronic_signature  as e on e.creator = uar.admin_user_id").Where("uar.status=1 and uar.org_id=? and uar.app_id =? and ua.status=1 and e.status = 1 and e.org_id = ? and e.app_id = ?", orgId, appid, orgId, appid).Select("ua.id, uar.user_name as name, uar.user_type,e.url").Scan(&list).Error
	return
}

func GetPatientCoursesRecords(orgID int64, id int64) (records models.PatientDiseaseCourse, err error) {
	db := p_service.XTReadDB()
	err = db.Model(&models.PatientDiseaseCourse{}).Where("org_id = ? and id = ? and status = 1", orgID, id).Find(&records).Error
	return
}

func FindPatientWithDeviceById(orgID int64, patient_id int64, time int64) (patient models.SchedualPatient2, err error) {
	db := p_service.XTReadDB()

	err = db.Preload("DialysisSchedule", func(db *gorm.DB) *gorm.DB {
		return db.Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
			Preload("DeviceZone", "status = 1 AND org_id = ?", orgID).
			Where("user_org_id = ? AND schedule_date = ? ", orgID, time)
	}).Where("user_org_id=? and id = ? and status=1", orgID, patient_id).First(&patient).Error
	return
}

func GetLastAfterWeight(orgID int64, patientID int64, maxDate int64) (*models.AssessmentAfterDislysis, error) {
	var record models.AssessmentAfterDislysis
	err := p_service.XTReadDB().Model(&models.AssessmentAfterDislysis{}).Where("patient_id = ? and user_org_id = ? and status = 1 and assessment_date < ?", patientID, orgID, maxDate).Order("assessment_date desc").First(&record).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &record, nil
}

//func GetAllName(orgid int64,appid int64)(sign,err error){
//
//  p_service.XTReadDB().Model(&sign).Where("org_id = ? and app_id =? and status = 1")
//
//}

func FindPrintStockGoodInfoByType(types int, startTime int64, end_time int64, orgId int64) (list []*models.StockInfo, err error) {
	db := p_service.XTReadDB()
	db = db.Model(&models.StockInfo{})
	db = db.Where("xt_good_information.org_id = ? AND xt_good_information.status = 1", orgId)
	if types == 1 {
		db = db.Joins("JOIN xt_warehouse_info AS info ON info.good_id=xt_good_information.id AND info.status = 1").Group("xt_good_information.id")
		db = db.Preload("QueryWarehousingInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("xt_warehouse_info.org_id = ? AND xt_warehouse_info.status = 1", orgId).Joins("JOIN xt_warehouse AS warehouse ON warehouse.id = xt_warehouse_info.warehousing_id AND warehouse.status = 1 AND warehouse.warehousing_time >=? AND warehouse.warehousing_time<= ?", startTime, end_time)
		})
	} else if types == 2 {
		db = db.Joins("JOIN xt_sales_return_info AS info ON info.good_id=xt_good_information.id AND info.status = 1").Group("xt_good_information.id")
		db = db.Preload("QuerySalesReturnInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("xt_sales_return_info.org_id = ? AND xt_sales_return_info.status = 1", orgId).Joins("JOIN xt_sales_return AS sales ON sales.id = xt_sales_return_info.sales_return_id AND sales.status = 1 AND sales.return_time >=? AND sales.return_time<= ?", startTime, end_time)
		})

	} else if types == 3 {
		db = db.Joins("JOIN xt_warehouse_out_info AS info ON info.good_id=xt_good_information.id AND info.status = 1").Group("xt_good_information.id")
		db = db.Preload("QueryWarehouseOutInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("xt_warehouse_out_info.org_id = ? AND xt_warehouse_out_info.status = 1", orgId).Joins("JOIN xt_warehouse_out ON xt_warehouse_out.id = xt_warehouse_out_info.warehouse_out_id AND xt_warehouse_out.status = 1 AND xt_warehouse_out.warehouse_out_time >=? AND xt_warehouse_out.warehouse_out_time<= ?", startTime, end_time)
		})

	} else if types == 4 {

		db = db.Joins("JOIN xt_cancel_stock_info AS info ON info.good_id=xt_good_information.id AND info.status = 1").Group("xt_good_information.id")
		db = db.Preload("QueryCancelStockInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("xt_cancel_stock_info.org_id = ? AND xt_cancel_stock_info.status = 1", orgId).Joins("JOIN xt_cancel_stock AS cancel ON cancel.id = xt_cancel_stock_info.cancel_stock_id AND cancel.status = 1 AND cancel.return_time >=? AND cancel.return_time<= ?", startTime, end_time)
		})

	}
	db = db.Preload("GoodsType", "(org_id = ? AND status = 1) OR (status = 1 AND type = 1)", orgId)
	err = db.Order("ctime desc").Find(&list).Error
	return
}

func GetOrgInfoTemplate(orgID int64) (models.GobalTemplate, error) {

	var templateInfo models.GobalTemplate
	var err error
	err = p_service.XTReadDB().Model(&models.GobalTemplate{}).Where("org_id=? and status=1", orgID).First(&templateInfo).Error
	return templateInfo, err
}
