package service

import (
	"XT_New/enums"
	"XT_New/models"
	"XT_New/utils"
	"fmt"
	"github.com/astaxie/beego/config"
	"golang.org/x/sync/errgroup"

	"reflect"
	"strconv"
	"time"
)

func GetHisPrescriptionTemplatesList(patient_id int64, org_id int64, page int64, limit int64) (templates []*models.HisPrescriptionTemplate, total int64, err error) {
	offset := (page - 1) * limit
	db := readDb.Model(&models.HisPrescriptionTemplate{}).Where("user_org_id = ? AND patient_id= ? AND status = 1", org_id, patient_id)
	err = db.Count(&total).Offset(offset).Limit(limit).Find(&templates).Error
	return
}

func GetHisPrescriptionTemplateByID(template_id int64) (prescription models.HisPrescriptionTemplate, err error) {
	err = readDb.Model(&models.HisPrescriptionTemplate{}).Where("id = ? AND status = 1 ", template_id).First(&prescription).Error
	return
}

func GetHisPrescriptionTemplateByModeId(mode_id int64, patient_id int64, user_org_id int64) (prescription models.HisPrescriptionTemplate, err error) {
	err = readDb.Model(&models.HisPrescriptionTemplate{}).Where("mode = ? AND status = 1 AND patient_id = ? and user_org_id = ?", mode_id, patient_id, user_org_id).First(&prescription).Error
	return
}

func GetHisPrescriptionTemplateByModeIdTwo(mode_id int64, patient_id int64, user_org_id int64, id int64) (prescription models.HisPrescriptionTemplate, err error) {
	err = readDb.Model(&models.HisPrescriptionTemplate{}).Where("mode = ? AND status = 1 AND patient_id = ? and user_org_id = ? and id <> ?", mode_id, patient_id, user_org_id, id).First(&prescription).Error
	return
}

func SaveHisPrescriptionTemplate(template *models.HisPrescriptionTemplate) (err error) {
	err = writeDb.Save(&template).Error
	return

}
func GetHisPrescriptionInfoTemplates(p_id int64, user_org_id int64) (p []*models.HisPrescriptionInfoTemplate, err error) {
	err = writeDb.Model(&models.HisPrescriptionInfoTemplate{}).Where("user_org_id = ? AND p_template_id = ?", user_org_id, p_id).Find(&p).Error
	return
}

func DelelteHisPrescriptionInfoTemplate(id int64, user_org_id int64) (err error) {
	err = writeDb.Model(&models.HisPrescriptionInfoTemplate{}).Where("user_org_id = ? AND id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	err = writeDb.Model(&models.HisPrescriptionAdviceTemplate{}).Where("user_org_id = ? AND prescription_id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	err = writeDb.Model(&models.HisPrescriptionProjectTemplate{}).Where("user_org_id = ? AND prescription_id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	return
}

func BatchDelelteHisPrescriptionInfoTemplate(id []int64, user_org_id int64) (err error) {

	err = writeDb.Model(&models.HisPrescriptionInfoTemplate{}).Where("user_org_id = ? AND id in (?)", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	err = writeDb.Model(&models.HisPrescriptionAdviceTemplate{}).Where("user_org_id = ? AND prescription_id in (?)", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	err = writeDb.Model(&models.HisPrescriptionProjectTemplate{}).Where("user_org_id = ? AND prescription_id in (?)", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	return
}

func DelelteHisPrescriptionTemplate(id int64, user_org_id int64) (err error) {
	err = writeDb.Model(&models.HisPrescriptionTemplate{}).Where("user_org_id = ? AND id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0}).Error
	err = writeDb.Model(&models.HisPrescriptionInfoTemplate{}).Where("user_org_id = ? AND p_template_id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	return
}

func DelelteHisPrescriptionAdviceTemplate(id int64, user_org_id int64) (err error) {
	err = writeDb.Model(&models.HisPrescriptionAdviceTemplate{}).Where("user_org_id = ? AND id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	return
}

func DelelteHisPrescriptionProjectTemplate(id int64, user_org_id int64) (err error) {
	err = writeDb.Model(&models.HisPrescriptionProjectTemplate{}).Where("user_org_id = ? AND id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error

	return
}

// 封装保存接口
func FenCreatePrescriptionTemplate(id, mode_id, types, patient_id int64, name string, adminInfo *AdminUserInfo, dataBody map[string]interface{}) (err error) {
	tmp_bool_id := IsDialysisMode(adminInfo.CurrentOrgId, patient_id, mode_id)

	var src_template models.HisPrescriptionTemplate
	if !tmp_bool_id {
		template := models.HisPrescriptionTemplate{
			UserOrgId: adminInfo.CurrentOrgId,
			PatientId: patient_id,
			Type:      types,
			Status:    1,
			Ctime:     time.Now().Unix(),
			Mtime:     time.Now().Unix(),
			Name:      name,
			Mode:      mode_id,
		}
		src_template = template
		CreateHisPrescriptionTemplate(&src_template)
	} else {
		//查询出该模板的id
		err = XTReadDB().Model(&models.HisPrescriptionTemplate{}).Where("user_org_id = ? and patient_id = ? and status = 1 and mode = ?", adminInfo.CurrentOrgId, patient_id, mode_id).Find(&src_template).Error
		if err != nil {
			return
		}
		src_template.Name = name
		src_template.Mode = mode_id
		SaveHisPrescriptionTemplate(&src_template)
	}

	if dataBody["prescriptions"] != nil && reflect.TypeOf(dataBody["prescriptions"]).String() == "[]interface {}" {
		prescriptions, _ := dataBody["prescriptions"].([]interface{})
		if len(prescriptions) > 0 {
			for _, item := range prescriptions {
				items := item.(map[string]interface{})

				if items["id"] == nil || reflect.TypeOf(items["id"]).String() != "float64" {
					utils.ErrorLog("id")
					//c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					err = fmt.Errorf("参数错误")
					return
				}

				id := int64(items["id"].(float64))

				if items["type"] == nil || reflect.TypeOf(items["type"]).String() != "float64" {
					utils.ErrorLog("type")
					//c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					err = fmt.Errorf("参数错误")
					return
				}
				types := int64(items["type"].(float64))

				if items["med_type"] == nil || reflect.TypeOf(items["med_type"]).String() != "float64" {
					utils.ErrorLog("med_type")
					//c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					err = fmt.Errorf("参数错误")
					return
				}
				med_type := strconv.Itoa(int(items["med_type"].(float64)))

				ctime := time.Now().Unix()
				prescription := &models.HisPrescriptionInfoTemplate{
					ID:          id,
					PatientId:   patient_id,
					UserOrgId:   adminInfo.CurrentOrgId,
					Ctime:       ctime,
					Mtime:       ctime,
					Type:        types,
					Modifier:    adminInfo.AdminUser.Id,
					Creator:     adminInfo.AdminUser.Id,
					Status:      1,
					PTemplateId: src_template.ID,
					MedType:     med_type,
				}
				CreateHisPrescriptionInfoTemplate(prescription)

				if items["advices"] != nil && reflect.TypeOf(items["advices"]).String() == "[]interface {}" {
					advices := items["advices"].([]interface{})
					//group := service.GetMaxAdviceGroupID(adminInfo.CurrentOrgId)
					groupNo := int64(0)
					ctime := time.Now().Unix()
					mtime := ctime
					if len(advices) > 0 {
						for _, advice := range advices {
							var s models.HisPrescriptionAdviceTemplate
							s.PrescriptionId = prescription.ID
							s.AdviceType = 2
							s.StopState = 2
							s.ExecutionState = 2
							s.Status = 1
							s.UserOrgId = adminInfo.CurrentOrgId
							s.Groupno = groupNo
							s.CreatedTime = ctime
							s.UpdatedTime = mtime
							s.PatientId = patient_id
							errcode := FensetAdviceTemplateWithJSON(&s, advice.(map[string]interface{}))
							if errcode > 0 {
								//c.ServeFailJSONWithSGJErrorCode(errcode)
								err = fmt.Errorf("参数错误")
								return
							}
							CreateHisPrescriptionAdviceTemplate(&s)
						}
					}
				}
				if items["project"] != nil && reflect.TypeOf(items["project"]).String() == "[]interface {}" {
					projects := items["project"].([]interface{})
					if len(projects) > 0 {
						for _, project := range projects {
							var p models.HisPrescriptionProjectTemplate
							p.PrescriptionId = prescription.ID
							p.Ctime = time.Now().Unix()
							p.Mtime = time.Now().Unix()
							p.PatientId = patient_id
							p.UserOrgId = adminInfo.CurrentOrgId
							p.Status = 1
							errcode := FensetProjectTemplateWithJSON(&p, project.(map[string]interface{}))
							if errcode > 0 {
								//c.ServeFailJSONWithSGJErrorCode(errcode)
								err = fmt.Errorf("参数错误")
								return
							}
							CreateHisPrescriptionProjectTemplate(&p)

						}
					}
				}
			}
			return nil
		}
	}
	return
}

// 复制一个setProjectTemplateWithJSON接口
func FensetProjectTemplateWithJSON(project *models.HisPrescriptionProjectTemplate, json map[string]interface{}) int {
	if json["id"] != nil {
		id := json["id"].(string)
		if id != "" {
			tmpPid := id[1:]
			project_id, _ := strconv.ParseInt(tmpPid, 10, 64)
			if id[0] == 112 {
				project.Type = 2
			}
			if id[0] == 105 {
				project.Type = 3
			}
			project.ProjectId = project_id
		} else {
			project.ProjectId = int64(0)
		}

	}
	if json["frequency_type"] != nil && reflect.TypeOf(json["frequency_type"]).String() == "string" {
		tmp_drugid := json["frequency_type"].(string)
		frequency_type, _ := strconv.ParseInt(tmp_drugid, 10, 64)
		project.FrequencyType = frequency_type
	}
	if json["frequency_type"] != nil && reflect.TypeOf(json["frequency_type"]).String() == "float64" {
		frequency_type := int64(json["frequency_type"].(float64))
		project.FrequencyType = frequency_type
	}

	if json["day_count"] != nil && reflect.TypeOf(json["day_count"]).String() == "string" {
		tmp_drugid := json["day_count"].(string)
		day_count, _ := strconv.ParseInt(tmp_drugid, 10, 64)
		project.DayCount = day_count
	}
	if json["day_count"] != nil && reflect.TypeOf(json["day_count"]).String() == "float64" {
		day_count := int64(json["day_count"].(float64))
		project.DayCount = day_count
	}

	if json["week_day"] != nil && reflect.TypeOf(json["week_day"]).String() == "string" {
		week_day, _ := json["week_day"].(string)
		project.WeekDay = week_day
	}
	if json["week_day"] != nil && reflect.TypeOf(json["week_day"]).String() == "float64" {
		week_day := config.ToString(json["week_day"].(float64))
		project.WeekDay = week_day
	}

	//if json["type"] != nil || reflect.TypeOf(json["type"]).String() == "float64" {
	//	types := int64(json["type"].(float64))
	//	project.Type = types
	//}
	//if json["project_id"] != nil || reflect.TypeOf(json["project_id"]).String() == "float64" {
	//	project_id := int64(json["project_id"].(float64))
	//	project.ProjectId = project_id
	//}
	if json["price"] != nil && reflect.TypeOf(json["price"]).String() == "string" {
		price, _ := strconv.ParseFloat(json["price"].(string), 64)
		project.Price = price
	}

	if json["price"] != nil && reflect.TypeOf(json["price"]).String() == "float64" {
		price := json["price"].(float64)
		project.Price = price
	}

	if json["prescribing_number"] != nil && reflect.TypeOf(json["prescribing_number"]).String() == "string" {
		total, _ := json["prescribing_number"].(string)
		//totals, _ := strconv.ParseInt(total, 10, 64)
		project.Count = total
	}
	if json["prescribing_number"] != nil && reflect.TypeOf(json["prescribing_number"]).String() == "float64" {
		total := config.ToString(json["prescribing_number"].(float64))
		//totals, _ := strconv.ParseInt(total, 10, 64)
		project.Count = total
	}

	//if json["medical_code"] != nil && reflect.TypeOf(json["medical_code"]).String() == "string" {
	//	medical_code, _ := json["medical_code"].(string)
	//	project.MedListCodg = medical_code
	//}
	if json["single_dose"] != nil && reflect.TypeOf(json["single_dose"]).String() == "string" {
		single_dose, _ := json["single_dose"].(string)
		project.SingleDose = single_dose
	}
	if json["single_dose"] != nil && reflect.TypeOf(json["single_dose"]).String() == "float64" {
		single_dose := config.ToString(json["single_dose"].(float64))
		project.SingleDose = single_dose
	}

	if json["delivery_way"] != nil && reflect.TypeOf(json["delivery_way"]).String() == "string" {
		delivery_way, _ := json["delivery_way"].(string)
		project.DeliveryWay = delivery_way
	}
	if json["execution_frequency"] != nil && reflect.TypeOf(json["execution_frequency"]).String() == "string" {
		execution_frequency, _ := json["execution_frequency"].(string)
		project.ExecutionFrequency = execution_frequency
	}
	if json["remark"] != nil && reflect.TypeOf(json["remark"]).String() == "string" {
		remark, _ := json["remark"].(string)
		project.Remark = remark
	}
	if json["day"] != nil && reflect.TypeOf(json["remark"]).String() == "string" {
		day, _ := json["number_days"].(string)
		project.Day = day
	}
	if json["day"] != nil && reflect.TypeOf(json["remark"]).String() == "float64" {
		day := config.ToString(json["number_days"].(float64))
		project.Day = day
	}

	if json["unit"] != nil && reflect.TypeOf(json["unit"]).String() == "string" {
		unit, _ := json["unit"].(string)
		project.Unit = unit
	}
	return 0
}

// 复制一个setAdviceTemplateWithJSON接口
func FensetAdviceTemplateWithJSON(advice *models.HisPrescriptionAdviceTemplate, json map[string]interface{}) int {
	//if json["advice_id"] != nil || reflect.TypeOf(json["advice_id"]).String() == "float64" {
	//	advice_id := int64(json["advice_id"].(float64))
	//	advice.ID = advice_id
	//}

	if json["drug_name"] == nil {
		utils.ErrorLog("drug_name")
		return enums.ErrorCodeParamWrong
	}
	var tmpdrugid int64
	if json["drug_name"] != nil && reflect.TypeOf(json["drug_name"]).String() == "string" {
		tmpdrugid, _ = strconv.ParseInt(json["drug_name"].(string), 10, 64)
	}
	if json["drug_name"] != nil && reflect.TypeOf(json["drug_name"]).String() == "float64" {
		tmpdrugid = int64(json["drug_name"].(float64))
	}

	advice.AdviceName = FindDrugsName(tmpdrugid)
	//adviceDesc, _ := json["advice_desc"].(string)
	//advice.AdviceDesc = adviceDesc
	//if json["drug_spec"] != nil && reflect.TypeOf(json["drug_spec"]).String() == "string" {
	//	drugSpec, _ := strconv.ParseFloat(json["drug_spec"].(string), 64)
	//	advice.DrugSpec = drugSpec
	//}

	if json["remark"] != nil && reflect.TypeOf(json["remark"]).String() == "string" {
		remark, _ := json["remark"].(string)
		advice.Remark = remark
	}

	if json["id"] == nil {
		advice.DrugId = 0
	} else {
		if json["id"] != nil && reflect.TypeOf(json["id"]).String() == "string" {
			tmp_drugid := json["id"].(string)
			drug_id, _ := strconv.ParseInt(tmp_drugid, 10, 64)
			advice.DrugId = drug_id
		}
		if json["id"] != nil && reflect.TypeOf(json["id"]).String() == "float64" {
			drug_id := int64(json["id"].(float64))
			advice.DrugId = drug_id
		}
	}

	//if json["min_unit"] != nil && reflect.TypeOf(json["min_unit"]).String() == "string" {
	//	drugSpecUnit, _ := json["min_unit"].(string)
	//	advice.DrugSpecUnit = drugSpecUnit
	//}
	if json["single_dose"] != nil && reflect.TypeOf(json["single_dose"]).String() == "string" {
		singleDose, _ := strconv.ParseFloat(json["single_dose"].(string), 64)
		advice.SingleDose = singleDose
	}
	if json["single_dose"] != nil && reflect.TypeOf(json["single_dose"]).String() == "float64" {
		singleDose := json["single_dose"].(float64)
		advice.SingleDose = singleDose
	}
	if json["single_dose_unit"] != nil && reflect.TypeOf(json["single_dose_unit"]).String() == "string" {
		singleDoseUnit, _ := json["single_dose_unit"].(string)
		advice.SingleDoseUnit = singleDoseUnit
	}
	if json["prescribing_number"] != nil && reflect.TypeOf(json["prescribing_number"]).String() == "string" {
		prescribingNumber, _ := strconv.ParseFloat(json["prescribing_number"].(string), 64)
		advice.PrescribingNumber = prescribingNumber
	}
	if json["prescribing_number"] != nil && reflect.TypeOf(json["prescribing_number"]).String() == "float64" {
		prescribingNumber := json["prescribing_number"].(float64)
		advice.PrescribingNumber = prescribingNumber
	}
	if json["prescribing_number_unit"] != nil && reflect.TypeOf(json["prescribing_number_unit"]).String() == "string" {
		prescribingNumberUnit, _ := json["prescribing_number_unit"].(string)
		advice.PrescribingNumberUnit = prescribingNumberUnit
	}
	if json["delivery_way"] != nil && reflect.TypeOf(json["delivery_way"]).String() == "string" {
		deliveryWay, _ := json["delivery_way"].(string)
		advice.DeliveryWay = deliveryWay
	}
	if json["execution_frequency"] != nil && reflect.TypeOf(json["execution_frequency"]).String() == "string" {
		executionFrequency, _ := json["execution_frequency"].(string)
		advice.ExecutionFrequency = executionFrequency
	}
	fmt.Println("44444444444")
	if json["price"] != nil && reflect.TypeOf(json["price"]).String() == "string" {
		price, _ := strconv.ParseFloat(json["price"].(string), 64)
		advice.Price = price
	}
	if json["price"] != nil && reflect.TypeOf(json["price"]).String() == "float64" {
		price := json["price"].(float64)
		advice.Price = price
	}
	//if json["medical_insurance_number"] != nil || reflect.TypeOf(json["medical_insurance_number"]).String() == "string" {
	//	med_list_codg, _ := json["medical_insurance_number"].(string)
	//	advice.MedListCodg = med_list_codg
	//}
	//fmt.Println("333333333")
	if json["day"] != nil && reflect.TypeOf(json["day"]).String() == "string" {
		day, _ := strconv.ParseInt(json["day"].(string), 10, 64)
		advice.Day = day
	}
	if json["day"] != nil && reflect.TypeOf(json["day"]).String() == "float64" {
		day := int64(json["day"].(float64))
		advice.Day = day
	}
	//if json["groupno"] != nil || reflect.TypeOf(json["groupno"]).String() == "float64" {
	//	groupno := int64(json["groupno"].(float64))
	//	advice.Groupno = groupno
	//}

	//if json["frequency_type"] != nil || reflect.TypeOf(json["frequency_type"]).String() == "float64" {//原型图没画不考虑
	//	frequency_type := int64(json["frequency_type"].(float64))
	//	advice.FrequencyType = frequency_type
	//}
	//
	//if json["day_count"] != nil || reflect.TypeOf(json["day_count"]).String() == "float64" {
	//	day_count := int64(json["day_count"].(float64))
	//	advice.DayCount = day_count
	//}
	//
	//if json["week_day"] != nil || reflect.TypeOf(json["week_day"]).String() == "string" {
	//	week_day, _ := json["week_day"].(string)
	//	advice.WeekDay = week_day
	//}
	//fmt.Println("aaaaaaaaaaaaaaaaaaaaaaaaa")
	return 0
}

// 判断该患者是否有该透析模式
func IsDialysisMode(orgid, patient_id, mode int64) bool {
	var total int
	XTReadDB().Model(&models.HisPrescriptionTemplate{}).Where("user_org_id = ? and patient_id = ? and status = 1 and mode = ?", orgid, patient_id, mode).Count(&total)
	if total > 0 {
		return true
	} else {
		return false
	}
}

// 获取该透析模式的患者列表
func GetDialysisModePatient(orgid, model int64) (list []*models.DialysisPatient, err error) {
	var tmp []*models.DialysisPatient
	err = XTReadDB().Raw("select id,name from xt_patients,(SELECT patient_id FROM his_prescription_template WHERE user_org_id = ? and "+
		"mode = ? and status = 1)a where id = a.patient_id", orgid, model).Scan(&tmp).Error
	if err != nil {
		return
	}
	return tmp, err
}

// 如果没有名字默认透析模式
func DialysisModeName(mode int64) string {
	tmp := make(map[int64]string)
	tmp[1] = "HD"
	tmp[2] = "HDF"
	tmp[3] = "HD+HP"
	tmp[4] = "HP"
	tmp[5] = "HF"
	tmp[6] = "SCUF"
	tmp[7] = "IUF"
	tmp[8] = "HFHD"
	tmp[9] = "HFHD+HP"
	tmp[10] = "PHF"
	tmp[11] = "HFR"
	tmp[12] = "HDF+HP"
	tmp[13] = "CRRT"
	tmp[14] = "腹水回输"
	//tmp[15] = "HD前置换"
	//tmp[16] = "HD后置换"
	//tmp[17] = "HDF前置换"
	//tmp[18] = "HDF后置换"
	tmp[19] = "IUF+HD"
	tmp[20] = "UF"
	tmp[21] = "HD+"
	tmp[22] = "血浆胆红素吸附+HDF"
	tmp[23] = "血浆胆红素吸附"
	tmp[24] = "I-HDF"
	tmp[25] = "HD高通"
	tmp[26] = "CVVH"
	tmp[27] = "CVVHD"
	tmp[28] = "CVVHDF"
	tmp[29] = "PE"
	tmp[30] = "血浆胆红素吸附+HP"
	tmp[31] = "HPD"
	tmp[32] = "HDP"
	if v, ok := tmp[mode]; ok {
		return v
	}
	return ""
}

// 查询出该模板的id
func IdOfTheTemplate(orgid, patient_id, mode_id int64) (src_template models.HisPrescriptionTemplate, err error) {
	err = XTReadDB().Model(&models.HisPrescriptionTemplate{}).Where("user_org_id = ? and "+
		"patient_id = ? and status = 1 and mode = ?", orgid, patient_id, mode_id).Find(&src_template).Error
	return src_template, err
}

// 根据透析模式、患者姓名、药品项目获取处方内容
func GetPrescriptionContent(mode, orgid, patient_id int64) (list []*models.HisPrescriptionInfoTemplate, err error) {
	var tmp models.HisPrescriptionTemplate
	err = XTReadDB().Model(&models.HisPrescriptionTemplate{}).Where("user_org_id = ? and patient_id = ? and mode = ? and status = 1", orgid, patient_id, mode).Find(&tmp).Error
	if err != nil {
		return
	}
	var prescriptions []*models.HisPrescriptionInfoTemplate
	prescriptions, err = GetHisPrescriptionTemplate(tmp.ID, orgid)
	return prescriptions, err

}

// 获取该透析模式患者列表(批量删除时用)药品
func GetDialysisDrugDelect(orgid, model, drug_id int64) (list []*models.DialysisPatient, err error) {
	var tmp []*models.DialysisPatient
	err = XTReadDB().Raw("select id,name from xt_patients,("+
		"select distinct patient_id from his_prescription_advice_template,("+
		"select his_prescription_info_template.id from his_prescription_info_template,("+
		"SELECT id FROM his_prescription_template WHERE user_org_id = ? and mode = ? and status = 1"+
		")his where status = 1 and his_prescription_info_template.p_template_id = his.id"+
		")hisa where status = 1 and prescription_id = hisa.id and drug_id = ?)a where id = a.patient_id", orgid, model, drug_id).Scan(&tmp).Error
	if err != nil {
		return
	}
	return tmp, err
}

// 获取该透析模式患者列表(批量删除时用)项目
func GetDialysisProjectDelect2(orgid, model, drug_id int64) (list []*models.DialysisPatient, err error) {
	var tmp []*models.DialysisPatient
	err = XTReadDB().Raw("select id,name from xt_patients,("+
		"select distinct patient_id from his_prescription_project_template,("+
		"select his_prescription_info_template.id from his_prescription_info_template,("+
		"SELECT id FROM his_prescription_template WHERE user_org_id = ? and mode = ? and status = 1"+
		")his where status = 1 and his_prescription_info_template.p_template_id = his.id"+
		")hisb where status = 1 and prescription_id = hisb.id and project_id = ? and type = 2)a where id = a.patient_id", orgid, model, drug_id).Scan(&tmp).Error
	if err != nil {
		return
	}
	return tmp, err
}

// 获取该透析模式患者列表(批量删除时用)耗材
func GetDialysisProjectDelect3(orgid, model, drug_id int64) (list []*models.DialysisPatient, err error) {
	var tmp []*models.DialysisPatient
	err = XTReadDB().Raw("select id,name from xt_patients,("+
		"select distinct patient_id from his_prescription_project_template,("+
		"select his_prescription_info_template.id from his_prescription_info_template,("+
		"SELECT id FROM his_prescription_template WHERE user_org_id = ? and mode = ? and status = 1"+
		")his where status = 1 and his_prescription_info_template.p_template_id = his.id"+
		")hisb where status = 1 and prescription_id = hisb.id and project_id = ? and type = 3)a where id = a.patient_id", orgid, model, drug_id).Scan(&tmp).Error
	if err != nil {
		return
	}
	return tmp, err
}

// 根据透析模式删除药品
func ModeDeleteDrug(orgid, model, drug_id int64, patient_id []int64) (err error) {
	//开事务
	tx := XTWriteDB().Begin()
	defer func() {
		if err != nil {
			utils.ErrorLog("事务失败,原因为: %v", err)
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	var g errgroup.Group
	var tmp []*models.DialysisPatient
	err = tx.Raw("select his_prescription_advice_template.id from his_prescription_advice_template,("+
		"select his_prescription_info_template.id from his_prescription_info_template,("+
		"SELECT id FROM his_prescription_template WHERE user_org_id = ? and mode = ? and status = 1"+
		")his where status = 1 and his_prescription_info_template.p_template_id = his.id"+
		")hisa where status = 1 and prescription_id = hisa.id and drug_id = ? and patient_id in (?)", orgid, model, drug_id, patient_id).Scan(&tmp).Error
	for _, v := range tmp {
		g.Go(func() error {
			tmp := v
			var err error
			err = tx.Model(&models.HisPrescriptionAdviceTemplate{}).Where("id = ?", tmp.ID).Updates(map[string]interface{}{
				"status":       0,
				"updated_time": time.Now().Unix(),
			}).Error
			return err
		})
	}
	if errs := g.Wait(); errs != nil {
		err = errs
		return
	}
	return
}

// 根据透析模式删除项目和耗材
func ModeDelectItemsAndConsumables(orgid, model int64, drug_id string, patient_id []int64) (err error) {
	//开事务
	tx := XTWriteDB().Begin()
	defer func() {
		if err != nil {
			utils.ErrorLog("事务失败,原因为: %v", err)
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	front := drug_id[:1]
	after := drug_id[1:]
	project_id, _ := strconv.ParseInt(after, 10, 64)
	var g errgroup.Group
	var tmp []*models.DialysisPatient
	if front == "p" {
		err = tx.Raw("select his_prescription_project_template.id from his_prescription_project_template,("+
			"select his_prescription_info_template.id from his_prescription_info_template,("+
			"SELECT id FROM his_prescription_template WHERE user_org_id = ? and mode = ? and status = 1"+
			")his where status = 1 and his_prescription_info_template.p_template_id = his.id"+
			")hisb where status = 1 and prescription_id = hisb.id and project_id = ? and type = 2 and patient_id in (?)", orgid, model, project_id, patient_id).Scan(&tmp).Error
		if err != nil {
			return
		}
	}
	if front == "i" {
		err = tx.Raw("select his_prescription_project_template.id from his_prescription_project_template,("+
			"select his_prescription_info_template.id from his_prescription_info_template,("+
			"SELECT id FROM his_prescription_template WHERE user_org_id = ? and mode = ? and status = 1"+
			")his where status = 1 and his_prescription_info_template.p_template_id = his.id"+
			")hisb where status = 1 and prescription_id = hisb.id and project_id = ? and type = 3 and patient_id in (?)", orgid, model, project_id, patient_id).Scan(&tmp).Error
		if err != nil {
			return
		}
	}
	for _, v := range tmp {
		g.Go(func() error {
			tmp := v
			var err error
			err = tx.Model(&models.HisPrescriptionProjectTemplate{}).Where("id = ?", tmp.ID).Updates(map[string]interface{}{
				"status": 0,
				"mtime":  time.Now().Unix(),
			}).Error
			return err
		})
	}
	if errs := g.Wait(); errs != nil {
		err = errs
		return
	}
	return
}

// 替换该透析模式药品
func ReplaceDrug(orgid, model, drug_id int64, patient_id []int64, advice models.HisPrescriptionAdviceTemplate) (err error) {
	//开事务
	tx := XTWriteDB().Begin()
	defer func() {
		if err != nil {
			utils.ErrorLog("事务失败,原因为: %v", err)
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	var g errgroup.Group
	var tmp []*models.DialysisPatient
	err = tx.Raw("select his_prescription_advice_template.id from his_prescription_advice_template,("+
		"select his_prescription_info_template.id from his_prescription_info_template,("+
		"SELECT id FROM his_prescription_template WHERE user_org_id = ? and mode = ? and status = 1"+
		")his where status = 1 and his_prescription_info_template.p_template_id = his.id"+
		")hisa where status = 1 and prescription_id = hisa.id and drug_id = ? and patient_id in (?)", orgid, model, drug_id, patient_id).Scan(&tmp).Error
	for _, v := range tmp {
		g.Go(func() error {
			tmp := v
			var err error
			err = tx.Model(&models.HisPrescriptionAdviceTemplate{}).Where("id = ?", tmp.ID).Updates(map[string]interface{}{
				"drug_id":                 advice.DrugId,
				"single_dose":             advice.SingleDose,
				"single_dose_unit":        advice.SingleDoseUnit,
				"delivery_way":            advice.DeliveryWay,
				"execution_frequency":     advice.ExecutionFrequency,
				"day":                     advice.Day,
				"prescribing_number":      advice.PrescribingNumber,
				"prescribing_number_unit": advice.PrescribingNumberUnit,
				"price":                   advice.Price,
				"remark":                  advice.Remark,
				"updated_time":            time.Now().Unix(),
			}).Error
			return err
		})
	}
	if errs := g.Wait(); errs != nil {
		err = errs
		return
	}
	return
}

// 替换该透析模式耗材
func ReplaceItemsAndConsumables(orgid, model int64, drug_id string, patient_id []int64, project models.HisPrescriptionProjectTemplate) (err error) {
	//开事务
	tx := XTWriteDB().Begin()
	defer func() {
		if err != nil {
			utils.ErrorLog("事务失败,原因为: %v", err)
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	front := drug_id[:1]
	after := drug_id[1:]
	project_id, _ := strconv.ParseInt(after, 10, 64)
	var g errgroup.Group
	var tmp []*models.DialysisPatient
	if front == "p" {
		project.Type = 2
		err = tx.Raw("select his_prescription_project_template.id from his_prescription_project_template,("+
			"select his_prescription_info_template.id from his_prescription_info_template,("+
			"SELECT id FROM his_prescription_template WHERE user_org_id = ? and mode = ? and status = 1"+
			")his where status = 1 and his_prescription_info_template.p_template_id = his.id"+
			")hisb where status = 1 and prescription_id = hisb.id and project_id = ? and type = 2 and patient_id in (?)", orgid, model, project_id, patient_id).Scan(&tmp).Error
		if err != nil {
			return
		}
	}
	if front == "i" {
		project.Type = 3
		err = tx.Raw("select his_prescription_project_template.id from his_prescription_project_template,("+
			"select his_prescription_info_template.id from his_prescription_info_template,("+
			"SELECT id FROM his_prescription_template WHERE user_org_id = ? and mode = ? and status = 1"+
			")his where status = 1 and his_prescription_info_template.p_template_id = his.id"+
			")hisb where status = 1 and prescription_id = hisb.id and project_id = ? and type = 3 and patient_id in (?)", orgid, model, project_id, patient_id).Scan(&tmp).Error
		if err != nil {
			return
		}
	}
	for _, v := range tmp {
		g.Go(func() error {
			tmp := v
			var err error
			err = tx.Model(&models.HisPrescriptionProjectTemplate{}).Where("id = ?", tmp.ID).Updates(map[string]interface{}{
				"single_dose":         project.SingleDose,
				"delivery_way":        project.DeliveryWay,
				"execution_frequency": project.ExecutionFrequency,
				"day":                 project.Day,
				"count":               project.Count,
				"price":               project.Price,
				"remark":              project.Remark,
				"type":                project.Type,
				"mtime":               time.Now().Unix(),
			}).Error
			return err
		})
	}
	if errs := g.Wait(); errs != nil {
		err = errs
		return
	}
	return
}

// 跟据id查询药品、项目、耗材、套餐
func QueryFourTables(id string, orgid int64) (tmp interface{}, err error) {
	if id[0] == 112 {
		after := id[1:]
		var project []*models.XtHisProjectL
		err = XTReadDB().Model(&project).Where("id = ?", after).Find(&project).Error
		if err != nil {
			return nil, err
		} else {
			for i := 0; i < len(project); i++ {
				project[i].Translate, err = TranslateZu(project[i].StatisticalClassification, orgid, "统计分类")
				if err != nil {
					return nil, err
				}
			}
			return project, err
		}

	} else if id[0] == 105 {
		after := id[1:]
		var good []*models.GoodInfoL
		err = XTReadDB().Model(&models.GoodInfoL{}).Where("id = ?", after).Find(&good).Error
		if err != nil {
			return nil, err
		} else {
			for i := 0; i < len(good); i++ {
				good[i].Translate = "耗材"
			}
			return good, err
		}

	} else if id[0] == 104 {
		after := id[1:]
		var team []*models.XtHisProjectTeam
		err = XTReadDB().Model(&models.XtHisProjectTeam{}).Where("id = ?", after).Find(&team).Error
		if err != nil {
			return nil, err
		} else {
			return team, err
		}

	} else {
		var lib []*models.BaseDrugLibL
		err = XTReadDB().Model(&models.BaseDrugLibL{}).Where("id = ?", id).Find(&lib).Error
		if err != nil {
			return nil, err
		} else {
			for i := 0; i < len(lib); i++ {
				lib[i].SingleDoseUnit = TypeConversion02(config.ToString(lib[i].DrugDoseUnit))
				if err != nil {
					return nil, err
				}
				type m struct {
					Name string `json:"name"`
				}
				newM := []m{
					{
						lib[i].DoseUnit, //计量单位
					},
					{
						lib[i].MinUnit, //拆零单位
					},
				}
				newN := []m{
					{
						lib[i].MinUnit,
					},
					{
						lib[i].MaxUnit,
					},
				}
				lib[i].List1 = newM
				lib[i].List2 = newN
			}
			return lib, err
		}
	}
}

// 获取机构项目中所用的组
func GetDataConfig(orgid int64) (dataconfig []*models.DictDataconfig, err error) {
	err = XTReadDB().Raw("select * from xt_drug_data_config where parent_id in "+
		"(select id from xt_drug_data_config where name = \"统计分类\" and parent_id = 0) "+
		"and status =1 and (org_id = ? or org_id = 0)", orgid).Scan(&dataconfig).Error
	return
}

// 翻译项目中的组
func TranslateZu(sc, orgid int64, types string) (s string, err error) {
	var dataconfig []*models.DictDataconfig
	tmp := "select * from xt_drug_data_config where parent_id in (select id from xt_d·rug_data_config where name = \"" + types + "\" and parent_id = 0) and value = " + config.ToString(sc) + " and status = 1 and (org_id = " + config.ToString(orgid) + " or org_id = 0)"

	err = XTReadDB().Raw(tmp).Scan(&dataconfig).Error
	if err != nil {
		return
	}
	if len(dataconfig) > 1 {
		err = fmt.Errorf("sql数据异常:%v", tmp)
	}
	if len(dataconfig) == 0 {
		return "", err
	}
	return dataconfig[0].Name, err
}

type TempOrder struct {
	UserOrgId     int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
	Status        int64  `gorm:"column:status" json:"status" form:"status"`
	OrderStatus   int64  `gorm:"column:order_status" json:"order_status" form:"order_status"`
	PsnName       string `gorm:"column:psn_name" json:"psn_name" form:"psn_name"`
	Insutype      string `gorm:"column:insutype" json:"insutype" form:"insutype"`
	MdtrtCertType string `gorm:"column:mdtrt_cert_type" json:"mdtrt_cert_type" form:"mdtrt_cert_type"`
}

func (TempOrder) TableName() string {
	return "his_order"
}

func GetHisMdtrtCertType(start_time string, end_time string, org_id int64) (os []TempOrder, err error) {
	err = readDb.Model(&TempOrder{}).Where("user_org_id = ? and setl_time >= ? and setl_time <= ? and order_status = 2 and status = 1", org_id, start_time, end_time).Find(&os).Error
	return
}