package service

import (
	"XT_New/models"
	"XT_New/utils"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/config"
	"github.com/astaxie/beego/context"
	"github.com/jinzhu/gorm"
	"math"
	"strconv"
	"strings"
	"time"
)

func SaveErrs(org_id int64, input *context.BeegoInput, err error) {
	dataBody := make(map[string]interface{}, 0)
	json.Unmarshal(input.RequestBody, &dataBody)
	route := input.Context.Request.RequestURI
	parameter := MapToJson(dataBody)
	tmp := models.XtErrs{
		org_id,
		route,
		parameter,
		err.Error(),
	}
	XTWriteDB().Create(&tmp)
}

//
func SavePharmacy() (err error) {
	var advice_info []*models.HisDoctorAdviceInfo
	err = XTReadDB().Raw("select * from xt_doctor_advice where id > 21780 and id < 21790").Scan(&advice_info).Error
	if err != nil {
		return
	}
	return nil
}

//查询药房中某一天的患者人数,is_medicine:0未发，1已发(改)
func GetTodayPharmacy(stime, etime, orgid, is_medicine int64) (num int, err error) {
	//orgid = 9675
	InitDrugidIsNil(orgid, stime, etime)
	var tmp []*models.TmpTTT
	if is_medicine == 0 {
		err = XTReadDB().Raw("select distinct patient_id from his_doctor_advice_info where "+
			"status = 1 and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = 0 and "+
			"drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1) "+
			"union "+
			"select distinct patient_id from xt_doctor_advice where "+
			"status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = 0 and "+
			"drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1) ",
			stime, etime, orgid, orgid, stime, etime, orgid, orgid).Scan(&tmp).Error
		if err != nil {
			return
		}
	} else {
		err = XTReadDB().Raw("select distinct patient_id from his_doctor_advice_info where "+
			"status = 1 and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = 1 and "+
			"drug_id in (select id from xt_base_drug where org_id = ? and status = 1) "+
			"union "+
			"select distinct patient_id from xt_doctor_advice where "+
			"status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = 1 and "+
			"drug_id in (select id from xt_base_drug where org_id = ? and status = 1) ",
			stime, etime, orgid, orgid, stime, etime, orgid, orgid).Scan(&tmp).Error
		if err != nil {
			return
		}
	}

	return len(tmp), err

}

//(改)
func GetTodayDrug(stime, etime, orgid, is_medicine int64, keyword string) (list []*models.TmpPatient, err error) {
	InitDrugidIsNil(orgid, stime, etime)
	//病人
	var tmp []*models.TmpTTT
	//tmp := make([]string,0)
	if is_medicine == 0 {
		if keyword != "" {
			keyword = "%" + keyword + "%"
			err = XTReadDB().Raw("select a.* from(select distinct patient_id,dispensing_time from his_doctor_advice_info where "+
				"status = 1 and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
				"patient_id in (select id from xt_patients where user_org_id = ? and name like ? or dialysis_no like ?) and "+
				"drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1) "+
				"union "+
				"select distinct patient_id,dispensing_time from xt_doctor_advice where "+
				"status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
				"patient_id in (select id from xt_patients where user_org_id = ? and name like ? or dialysis_no like ?) and "+
				"drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1))a order by dispensing_time desc ",
				stime, etime, orgid, is_medicine, orgid, keyword, keyword, orgid, stime, etime, orgid, is_medicine, orgid, keyword, keyword, orgid).Scan(&tmp).Error
		} else {
			err = XTReadDB().Raw("select a.* from(select distinct patient_id,dispensing_time from his_doctor_advice_info where "+
				"status = 1 and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
				"drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1) "+
				"union "+
				"select distinct patient_id,dispensing_time from xt_doctor_advice where "+
				"status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
				"drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1))a order by dispensing_time desc",
				stime, etime, orgid, is_medicine, orgid, stime, etime, orgid, is_medicine, orgid).Scan(&tmp).Error
		}

		if err != nil {
			return
		}
	} else {
		if keyword != "" {
			keyword = "%" + keyword + "%"
			err = XTReadDB().Raw("select a.* from(select distinct patient_id,dispensing_time from his_doctor_advice_info where "+
				"status = 1 and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
				"patient_id in (select id from xt_patients where user_org_id = ? and name like ? or dialysis_no like ?) and "+
				"drug_id in (select id from xt_base_drug where org_id = ? and status = 1) "+
				"union "+
				"select distinct patient_id,dispensing_time from xt_doctor_advice where "+
				"status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
				"patient_id in (select id from xt_patients where user_org_id = ? and name like ? or dialysis_no like ?) and "+
				"drug_id in (select id from xt_base_drug where org_id = ? and status = 1))a order by dispensing_time desc ",
				stime, etime, orgid, is_medicine, orgid, keyword, keyword, orgid, stime, etime, orgid, is_medicine, orgid, keyword, keyword, orgid).Scan(&tmp).Error
		} else {
			err = XTReadDB().Raw("select a.* from(select distinct patient_id,dispensing_time from his_doctor_advice_info where "+
				"status = 1 and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
				"drug_id in (select id from xt_base_drug where org_id = ? and status = 1) "+
				"union "+
				"select distinct patient_id,dispensing_time from xt_doctor_advice where "+
				"status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
				"drug_id in (select id from xt_base_drug where org_id = ? and status = 1))a order by dispensing_time desc",
				stime, etime, orgid, is_medicine, orgid, stime, etime, orgid, is_medicine, orgid).Scan(&tmp).Error
		}

		if err != nil {
			return
		}
	}

	tmp_s := make([]int64, 0)
	s_map := make(map[int64]int64)
	for _, v := range tmp {
		if _, ok := s_map[v.PatientID]; !ok {
			s_map[v.PatientID] = v.PatientID
			tmp_s = append(tmp_s, v.PatientID)
		}
	}
	list, err = GetManyUsers(tmp_s)
	return

}

//查询患者（改）
func GetManyUsers(tmp []int64) (list []*models.TmpPatient, err error) {

	for i := 0; i < len(tmp); i++ {
		var tt models.Patients
		err = XTReadDB().Model(&models.Patients{}).Where("id = ?", tmp[i]).Find(&tt).Error

		tmp_list := &models.TmpPatient{
			PatientID:  tt.ID,
			Name:       tt.Name,
			DialysisNo: tt.DialysisNo,
		}
		list = append(list, tmp_list)
	}
	return
}

//查询患者当天时间段中的药,is_medicine:0未发，1已发(改)
func GetPatientMedication(orgid, patient_id, stime, etime, is_medicine int64) (pp []*models.PharmacyContent, err error) {
	InitDrugidIsNil(orgid, stime, etime)
	var tmp []*models.HisDoctorAdviceInfoL
	if is_medicine == 0 {
		err = XTReadDB().Model(&models.HisDoctorAdviceInfoL{}).Where(
			"status = 1 and created_time >= ? and created_time <= ? and user_org_id = ? and patient_id = ? and is_medicine = ? and drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1)", stime, etime, orgid, patient_id, is_medicine, orgid).Find(&tmp).Error
		if err != nil {
			return pp, err
		}
	} else {
		err = XTReadDB().Model(&models.HisDoctorAdviceInfoL{}).Where(
			"status = 1 and created_time >= ? and created_time <= ? and user_org_id = ? and patient_id = ? and is_medicine = ? and drug_id in (select id from xt_base_drug where org_id = ? and status = 1)", stime, etime, orgid, patient_id, is_medicine, orgid).Find(&tmp).Error
		if err != nil {
			return pp, err
		}
	}

	for _, v := range tmp {
		pp = append(pp, &models.PharmacyContent{
			Name:         v.AdviceName,
			SingleDosage: config.ToString(v.SingleDose) + v.SingleDoseUnit,
			Usage:        v.DeliveryWay,
			Frequency:    v.ExecutionFrequency,
			Days:         config.ToString(v.Day) + "天",
			Total:        config.ToString(v.PrescribingNumber) + v.PrescribingNumberUnit,
			Doctor:       GetAdminUserName(v.AdviceDoctor, orgid), //开立医生
			DataSources:  "his处方",
			Remarks:      v.Remark, //备注
		})
	}

	var tmp_advice []*models.XtDoctorAdviceL
	if is_medicine == 0 {
		err = XTReadDB().Model(&models.XtDoctorAdviceL{}).Where(
			"status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and user_org_id = ? and patient_id = ? and is_medicine = ? and drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1)", stime, etime, orgid, patient_id, is_medicine, orgid).Find(&tmp_advice).Error
		if err != nil {
			return pp, err
		}
	} else {
		err = XTReadDB().Model(&models.XtDoctorAdviceL{}).Where(
			"status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and user_org_id = ? and patient_id = ? and is_medicine = ? and drug_id in (select id from xt_base_drug where org_id = ? and status = 1)", stime, etime, orgid, patient_id, is_medicine, orgid).Find(&tmp_advice).Error
		if err != nil {
			return pp, err
		}
	}

	for _, v := range tmp_advice {
		pp = append(pp, &models.PharmacyContent{
			Name:         v.AdviceName,
			SingleDosage: config.ToString(v.SingleDose) + v.SingleDoseUnit,
			Usage:        v.DeliveryWay,
			Frequency:    v.ExecutionFrequency,
			Days:         "-",
			Total:        config.ToString(v.PrescribingNumber) + v.PrescribingNumberUnit,
			Doctor:       GetAdminUserName(v.AdviceDoctor, orgid),
			DataSources:  "临时医嘱",
			Remarks:      v.Remark,
		})
	}
	return
}

//获取创建者姓名(改)
func GetAdminUserName(doctor, orgid int64) string {
	var tmp models.VmUserAdminRole
	XTReadDB().Model(&models.VmUserAdminRole{}).Where("admin_user_id = ? and org_id = ? and status = 1", doctor, orgid).Find(&tmp)
	return tmp.UserName
}

//查询该机构的药房配置,true: 通过药房发药，false：不通过药房发药。如果没有该机构的信息则生成一条数据
func GetOrgIdPharmacyConfig(orgid int64) bool {
	var total int
	var tmp_pharmacy models.PharmacyConfig
	XTReadDB().Model(&models.PharmacyConfig{}).Where("user_org_id = ? and status = 1", orgid).Find(&tmp_pharmacy).Count(&total)
	if total > 0 {
		//有记录
		if tmp_pharmacy.IsOpen == 1 {
			return true
		} else {
			return false
		}
	} else {
		//没有记录生成一条
		tmp := models.PharmacyConfig{
			UserOrgId: orgid,
			IsOpen:    2,
			Status:    1,
			Ctime:     time.Now().Unix(),
			Mtime:     time.Now().Unix(),
		}
		XTWriteDB().Create(&tmp)
		return false
	}
}

//修改该机构的药房配置
func ModifyPharmacyConfig(orgid, isopen int64) (err error) {
	if isopen == 1 || isopen == 2 {
		err = XTWriteDB().Model(&models.PharmacyConfig{}).Where("user_org_id = ? and status = 1", orgid).Updates(map[string]interface{}{
			"mtime":   time.Now().Unix(),
			"is_open": isopen,
		}).Error
	} else {
		err = fmt.Errorf("类型解析错误")
	}
	return
}

//查询该药品是否通过药房发药.0否；1是
func DrugAllocation(drug_id int64) (is_pharmacy int64, err error) {
	tmp := models.BaseDrugLib{}
	err = XTReadDB().Model(&models.BaseDrugLib{}).Where("id = ?", drug_id).Find(&tmp).Error
	return tmp.IsPharmacy, err
}

//根据id查询该药是否发药
func MedicineState(id int64) (is_medicine models.HisDoctorAdviceInfoL, err error) {
	tmp := models.HisDoctorAdviceInfoL{}
	err = XTReadDB().Model(&models.HisDoctorAdviceInfoL{}).Where("id = ?", id).Find(&tmp).Error
	return tmp, err
}

//发药明细列表(
func DispensingDetailsList(stime, etime, orgid, page, limit int64, keyword string) (dislist []*models.DispensingList, total int64, err error) {
	var fenye []*models.Pharmary //分页用的
	offset := (page - 1) * limit
	dbone := XTReadDB().Model(&models.Pharmary{}).Where("status = 1 and user_org_id = ? and record_date >= ? and record_date <= ?", orgid, stime, etime)
	if keyword != "" {
		var tmp_id []*models.TmpID
		keyword = "%" + keyword + "%"
		XTReadDB().Raw("select id from xt_patients where name like ? and user_org_id = ?", keyword, orgid).Scan(&tmp_id)
		tmp_ids := make([]int64, 0)
		for _, v := range tmp_id {
			tmp_ids = append(tmp_ids, v.Id)
		}
		dbone = dbone.Where("patient_id in (?)", tmp_ids)
	}
	//查询出分页用的数据
	err = dbone.Count(&total).Offset(offset).Order("mtime desc").Limit(limit).Find(&fenye).Error
	if err != nil {
		return
	}
	for _, v := range fenye {
		tmp_doctorid, tmp_doctorname, errs := GetDoctorIds(v.PatientId, v.RecordDate, orgid)
		if errs != nil {
			err = errs
			return
		}
		pat, _ := GetPatientName(v.PatientId)
		dislist = append(dislist, &models.DispensingList{
			PatientID:  v.PatientId,
			Name:       pat.Name,
			DoctorId:   tmp_doctorid,
			DoctorName: tmp_doctorname,
			RecordTime: v.RecordDate,
			RecordDate: fmt.Sprintf(time.Unix(v.RecordDate, 0).Format("2006-01-02 15:04:05")),
		})
	}
	return
}

//处方详情//////////////////////
func PrescriptionDetails(patient_id, record_date, orgid int64) (pre []*models.PrescripDetails, err error) {
	var tmp []*models.HisDoctorAdviceInfoL
	err = XTReadDB().Model(&models.HisDoctorAdviceInfoL{}).Where(
		"status = 1 and patient_id = ? and user_org_id = ? and dispensing_time = ? and is_medicine = 1 and drug_id in (select id from xt_base_drug where org_id = ? and status = 1)", patient_id, orgid, record_date, orgid).Find(&tmp).Error
	if err != nil {
		return
	}
	for _, v := range tmp {
		pre = append(pre, &models.PrescripDetails{
			Drugname:     v.AdviceName,
			SingleDosage: config.ToString(v.SingleDose) + v.SingleDoseUnit,
			Usage:        v.DeliveryWay,
			Frequency:    v.ExecutionFrequency,
			Days:         config.ToString(v.Day) + "天",
			Total:        config.ToString(v.PrescribingNumber) + v.PrescribingNumberUnit,
			UnitPrice:    config.ToString(v.Price) + "元",
			Remarks:      v.Remark,
		})
	}

	var tmp_advice []*models.XtDoctorAdviceL
	err = XTReadDB().Model(&models.XtDoctorAdviceL{}).Where(
		"status = 1 and (advice_type = 2 or advice_type = 3) and patient_id = ? and user_org_id = ? and dispensing_time = ? and is_medicine = 1 and drug_id in (select id from xt_base_drug where org_id = ? and status = 1)", patient_id, orgid, record_date, orgid).Find(&tmp_advice).Error
	if err != nil {
		return
	}
	for _, v := range tmp_advice {
		pre = append(pre, &models.PrescripDetails{
			Drugname:     v.AdviceName,
			SingleDosage: config.ToString(v.SingleDose) + v.SingleDoseUnit,
			Usage:        v.DeliveryWay,
			Frequency:    v.ExecutionFrequency,
			Days:         "-",
			Total:        config.ToString(v.PrescribingNumber) + v.PrescribingNumberUnit,
			UnitPrice:    "-",
			Remarks:      v.Remark,
		})
	}
	return
}

//查询病人的his id
func GetHisID(prescription_id, orgid int64) (id int64) {
	var tmp models.HisPrintPrescription
	XTReadDB().Model(&models.HisPrintPrescription{}).Where("id = ?", prescription_id).Find(&tmp)
	var fin models.HisPrescriptionInfoTwo
	XTReadDB().Model(&models.HisPrescriptionInfoTwo{}).Where("prescription_number = ? and user_org_id = ?", tmp.PrescriptionNumber, orgid).Find(&fin)
	return fin.ID
}

//根据药品id获取药品信息
func GetDrugNameTX(id int64, tx *gorm.DB) (tmp models.SpBaseDrug, err error) {
	err = tx.Model(&models.SpBaseDrug{}).Where("id = ? and status = 1", id).Find(&tmp).Error
	return
}
func GetXtManufacturer(id int64, tx *gorm.DB) (name string, err error) {
	var tmp models.Manufacturer
	err = tx.Model(&models.Manufacturer{}).Where("id = ? and status = 1", id).Find(&tmp).Error
	name = tmp.ManufacturerName
	return
}

//查询药品（使用keyword）
func GetManyDrugs(orgid int64, keyword string) (map[int64]models.PharmacyBaseDrug, error) {
	var tmp []*models.PharmacyBaseDrug
	tt := make(map[int64]models.PharmacyBaseDrug)
	err := XTReadDB().Model(&models.PharmacyBaseDrug{}).Where(" org_id = ? ", orgid).Where(" drug_name like ? ", "%"+keyword+"%").Find(&tmp).Error
	for _, v := range tmp {
		tt[v.ID] = *v
	}
	return tt, err
}

//查询(
func GetTodayMedicine(stime, etime, orgid, is_medicine int64, keyword string) (finlly []*models.ListOfDrugs, err error) {
	InitDrugidIsNil(orgid, stime, etime)
	var tmp []*models.TmpLLL
	if is_medicine == 0 {
		if keyword != "" {
			keyword = "%" + keyword + "%"
			err = XTReadDB().Raw("select distinct drug_id from his_doctor_advice_info where "+
				"status = 1 and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
				"drug_id in (select id from xt_base_drug where org_id = ? and drug_name like ? and is_pharmacy = 1) "+
				"union "+
				"select distinct drug_id from xt_doctor_advice where "+
				"status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
				"drug_id in (select id from xt_base_drug where org_id = ? and drug_name like ? and is_pharmacy = 1)",
				stime, etime, orgid, is_medicine, orgid, keyword, stime, etime, orgid, is_medicine, orgid, keyword).Scan(&tmp).Error
		} else {
			err = XTReadDB().Raw("select distinct drug_id from his_doctor_advice_info where "+
				"status = 1 and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
				"drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1) "+
				"union "+
				"select distinct drug_id from xt_doctor_advice where "+
				"status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
				"drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1) ",
				stime, etime, orgid, is_medicine, orgid, stime, etime, orgid, is_medicine, orgid).Scan(&tmp).Error
		}
		if err != nil {
			return
		}
	} else {
		if keyword != "" {
			keyword = "%" + keyword + "%"
			err = XTReadDB().Raw("select distinct drug_id from his_doctor_advice_info where "+
				"status = 1 and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
				"drug_id in (select id from xt_base_drug where org_id = ? and drug_name like ? and is_pharmacy = 1) "+
				"union "+
				"select distinct drug_id from xt_doctor_advice where "+
				"status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
				"drug_id in (select id from xt_base_drug where org_id = ? and drug_name like ? and is_pharmacy = 1)",
				stime, etime, orgid, is_medicine, orgid, keyword, stime, etime, orgid, is_medicine, orgid, keyword).Scan(&tmp).Error
		} else {
			err = XTReadDB().Raw("select distinct drug_id from his_doctor_advice_info where "+
				"status = 1 and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
				"drug_id in (select id from xt_base_drug where org_id = ? and status = 1) "+
				"union "+
				"select distinct drug_id from xt_doctor_advice where "+
				"status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and user_org_id = ? and is_medicine = ? and "+
				"drug_id in (select id from xt_base_drug where org_id = ? and status = 1) ",
				stime, etime, orgid, is_medicine, orgid, stime, etime, orgid, is_medicine, orgid).Scan(&tmp).Error
		}
		if err != nil {
			return
		}
	}

	for _, v := range tmp {
		name, specifications := FindDrugSpecifications(v.DrugId)
		number, errs := GetInventoryQuantity(orgid, v.DrugId)
		if errs != nil {
			err = errs
			return
		}
		finlly = append(finlly, &models.ListOfDrugs{
			ID:             v.DrugId,
			Name:           name,
			Specifications: specifications,
			Stock:          number,
		})
	}
	return
}

//根据药品id获取药品规格(
func FindDrugSpecifications(id int64) (name, specifications string) {
	var tmp models.PharmacyBaseDrug
	XTReadDB().Model(&models.PharmacyBaseDrug{}).Where("id = ?", id).Find(&tmp)
	name = tmp.DrugName
	specifications = config.ToString(tmp.Dose) + tmp.DoseUnit + "*" + config.ToString(tmp.MinNumber) + tmp.MinUnit + "/" + config.ToString(tmp.MaxUnit)
	return
}

//根据药品id获取当前药品出库仓库的库存数量
func GetInventoryQuantity(orgid, drugid int64) (number string, err error) {
	//获取药品拆零数量
	var phar models.PharmacyBaseDrug
	XTReadDB().Model(&models.PharmacyBaseDrug{}).Where("id = ?", drugid).Find(&phar)
	min_number := phar.MinNumber
	if min_number == 0 {
		err = fmt.Errorf("药品拆零数量不能为零！")
		return
	}
	storeconfig, _ := FindStorehouseConfig(orgid)
	var tmp []models.SpDrugWarehouseInfo
	XTReadDB().Model(&models.SpDrugWarehouseInfo{}).Where("org_id = ? and drug_id = ? and storehouse_id = ? and status = 1", orgid, drugid, storeconfig.DrugStorehouseOut).Find(&tmp)
	max, min := int64(0), int64(0)
	for _, v := range tmp {
		max += v.StockMaxNumber
		min += v.StockMinNumber
	}
	max += min / min_number
	min = min % min_number
	if max != 0 {
		number = config.ToString(max) + phar.MaxUnit
	}
	if min != 0 {
		number = number + config.ToString(min) + phar.MinUnit
	}
	if number == "" {
		number = "0"
	}
	//number = config.ToString(max)+phar.MaxUnit+config.ToString(min)+phar.MinUnit
	return
}

//获取该药品的病人信息(
func FindMedicationList(orgid, drug_id, stime, etime, is_medicine int64) (pp []*models.PatientInformation, err error) { ///////////////
	InitDrugidIsNil(orgid, stime, etime)
	var tmp []*models.HisDoctorAdviceInfoL
	err = XTReadDB().Model(&models.HisDoctorAdviceInfoL{}).Where(
		"status = 1 and created_time >= ? and created_time <= ? and user_org_id = ? and drug_id = ? and is_medicine = ?", stime, etime, orgid, drug_id, is_medicine).Find(&tmp).Error
	if err != nil {
		return pp, err
	}
	for _, v := range tmp {
		pp = append(pp, &models.PatientInformation{
			Id:           "h" + config.ToString(v.ID),
			Name:         FindUserName(v.PatientId),
			SingleDosage: config.ToString(v.SingleDose) + v.SingleDoseUnit,
			Usage:        v.DeliveryWay,
			Frequency:    v.ExecutionFrequency,
			Days:         config.ToString(v.Day) + "天",
			Total:        config.ToString(v.PrescribingNumber) + v.PrescribingNumberUnit,
			DataSources:  "his处方",
			People:       GetUserAdminName(v.People, orgid), //领药人！！！！！！！！！！！！！！！！！！！！！！
		})
	}

	var tmp_advice []*models.XtDoctorAdviceL
	err = XTReadDB().Model(&models.XtDoctorAdviceL{}).Where(
		"status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and user_org_id = ? and drug_id = ? and is_medicine = ?", stime, etime, orgid, drug_id, is_medicine).Find(&tmp_advice).Error
	if err != nil {
		return pp, err
	}
	for _, v := range tmp_advice {
		pp = append(pp, &models.PatientInformation{
			Id:           "x" + config.ToString(v.ID),
			Name:         FindUserName(v.PatientId),
			SingleDosage: config.ToString(v.SingleDose) + v.SingleDoseUnit,
			Usage:        v.DeliveryWay,
			Frequency:    v.ExecutionFrequency,
			Days:         "",
			Total:        config.ToString(v.PrescribingNumber) + v.PrescribingNumberUnit,
			DataSources:  "临时医嘱",
			People:       GetUserAdminName(v.People, orgid), //领药人
		})
	}
	return
}

//患者发药按钮点击（
func DispensingMedicine(orgid, patient_id, stime, etime, creater int64) (err error) {
	//开事务
	tx := XTWriteDB().Begin()
	defer func() {
		if err != nil {
			utils.ErrorLog("事务失败，原因为: %v", err)
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	time_now := time.Now().Unix()
	var hids []*models.TmpID
	var xids []*models.TmpID
	err = tx.Raw("select id from his_doctor_advice_info where status = 1 and created_time >= ? and created_time <= ? "+
		"and user_org_id = ? and patient_id = ? and is_medicine = 0 and drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1) ", stime, etime, orgid, patient_id, orgid).Scan(&hids).Error
	if err != nil {
		return
	}
	hid := make([]int64, 0)
	for _, v := range hids {
		hid = append(hid, v.Id)
	}
	var advice_info []*models.HisDoctorAdviceInfo
	err = tx.Model(&models.HisDoctorAdviceInfo{}).Where("id in (?) and status = 1", hid).Find(&advice_info).Error
	if err != nil {
		return
	}
	for _, v := range advice_info {
		tmp_bool := IsPharmacyConfig(orgid)
		if tmp_bool {
			if PettyCash(v.DrugId) {
				continue
			}
			kou := FenDrugInventory(v, orgid)
			if !kou {
				err = fmt.Errorf(FindDrugsName(v.DrugId) + "库存不足")
				return
			}
			//扣减库存
			err = FenStock(orgid, creater, v)
			if err != nil {
				err = fmt.Errorf("!:%v", err)
				return
			}
		}
	}
	//修改状态
	errs := XTWriteDB().Model(&models.HisDoctorAdviceInfoL{}).Where("id in (?)", hid).Updates(map[string]interface{}{
		"is_medicine":     1,
		"people":          0,
		"dispensing_time": time_now,
		"updated_time":    time.Now().Unix(),
	}).Error
	if errs != nil {
		return errs
	}
	err1 := ChangeHisPrescription(hid)
	if err1 != nil {
		return err1
	}

	err = tx.Raw("select id from xt_doctor_advice where status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and "+
		"user_org_id = ? and patient_id = ? and is_medicine = 0 and drug_id in (select id from xt_base_drug where org_id = ? and is_pharmacy = 1)", stime, etime, orgid, patient_id, orgid).Scan(&xids).Error
	if err != nil {
		return
	}
	xid := make([]int64, 0)
	for _, v := range xids {
		xid = append(xid, v.Id)
	}
	var advice []*models.HisDoctorAdviceInfo
	err = tx.Raw("select * from xt_doctor_advice where id in (?) and status = 1", xid).Scan(&advice).Error
	if err != nil {
		return
	}
	for _, v := range advice {
		tmp_bool := IsPharmacyConfig(orgid)
		if tmp_bool {
			if PettyCash(v.DrugId) {
				continue
			}
			kou := FenDrugInventory(v, orgid)
			if !kou {
				err = fmt.Errorf(FindDrugsName(v.DrugId) + "库存不足")
				return
			}
			//扣减库存
			err = FenStock(orgid, creater, v)
			if err != nil {
				err = fmt.Errorf("!:%v", err)
				return
			}
		}
	}
	//修改状态
	errs1 := XTWriteDB().Model(&models.XtDoctorAdviceL{}).Where("id in (?)", xid).Updates(map[string]interface{}{
		"is_medicine":     1,
		"people":          0,
		"dispensing_time": time_now,
		"updated_time":    time.Now().Unix(),
	}).Error
	if errs1 != nil {
		return errs1
	}

	//生成明细记录
	tmp_ph := models.Pharmary{
		UserOrgId:  orgid,
		PatientId:  patient_id,
		Ctime:      time.Now().Unix(),
		Mtime:      time.Now().Unix(),
		Status:     1,
		RecordDate: time_now,
	}
	err = tx.Create(&tmp_ph).Error

	return
}

//患者退药按钮点击
func DrugWithdrawal(orgid, patient_id, stime, etime, creater int64) (err error) {
	//开事务
	tx := XTWriteDB().Begin()
	defer func() {
		if err != nil {
			utils.ErrorLog("事务失败，原因为: %v", err)
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	map_time := make(map[int64]int64)
	var hids []*models.TmpID
	var xids []*models.TmpID
	//var hid,xid []int64//查询已发药的药品
	err = tx.Raw("select id,dispensing_time from his_doctor_advice_info where status = 1 and created_time >= ? and created_time <= ? "+
		"and user_org_id = ? and patient_id = ? and is_medicine = 1 and drug_id in (select id from xt_base_drug where org_id = ? and status = 1)", stime, etime, orgid, patient_id, orgid).Scan(&hids).Error
	if err != nil {
		return
	}
	hid := make([]int64, 0)
	for _, v := range hids {
		hid = append(hid, v.Id)
		map_time[v.DispensingTime] = v.DispensingTime
	}
	//修改状态
	errs := XTWriteDB().Model(&models.HisDoctorAdviceInfoL{}).Where("id in (?)", hid).Updates(map[string]interface{}{
		"is_medicine":     0,
		"people":          creater,
		"dispensing_time": 0,
		"updated_time":    time.Now().Unix(),
	}).Error
	if errs != nil {
		return errs
	}
	err1 := ChangeHisPrescriptionT(hid)
	if err1 != nil {
		return err1
	}
	var advice_info []*models.HisDoctorAdviceInfo
	err = tx.Model(&models.HisDoctorAdviceInfo{}).Where("id in (?) and status = 1", hid).Find(&advice_info).Error
	if err != nil {
		return
	}
	for _, v := range advice_info {
		//扣减库存
		if !IsPharmacyDelivery(v.DrugId, orgid) {
			continue
		}
		err = DrugAutoAddCancelInfo(v, creater)
		if err != nil {
			err = fmt.Errorf("!:%v", err)
			return
		}
		drug, _ := FindBaseDrugLibRecordSeven(orgid, v.DrugId)
		//查询默认仓库
		storeHouseConfig, _ := GetAllStoreHouseConfig(orgid)
		//查询默认仓库剩余多少库存
		var sum_count int64
		stockInfo, _ := GetDrugAllStockInfo(storeHouseConfig.DrugStorehouseOut, orgid, v.DrugId)
		for _, its := range stockInfo {
			sum_count += its.StockMaxNumber*drug.MinNumber + its.StockMinNumber
		}
		UpdateBaseDrugSumTwo(v.DrugId, sum_count, orgid)
	}

	err = tx.Raw("select id,dispensing_time from xt_doctor_advice where status = 1 and (advice_type = 2 or advice_type = 3) and created_time >= ? and created_time <= ? and "+
		"user_org_id = ? and patient_id = ? and is_medicine = 1 and drug_id in (select id from xt_base_drug where org_id = ? and status = 1)", stime, etime, orgid, patient_id, orgid).Scan(&xids).Error
	if err != nil {
		return
	}
	xid := make([]int64, 0)
	for _, v := range xids {
		xid = append(xid, v.Id)
		map_time[v.DispensingTime] = v.DispensingTime
	}
	//修改状态
	errs1 := XTWriteDB().Model(&models.XtDoctorAdviceL{}).Where("id in (?)", xid).Updates(map[string]interface{}{
		"is_medicine":     0,
		"people":          creater,
		"dispensing_time": 0,
		"updated_time":    time.Now().Unix(),
	}).Error
	if errs1 != nil {
		return errs1
	}
	var advice []*models.HisDoctorAdviceInfo
	err = tx.Raw("select * from xt_doctor_advice where id in (?) and status = 1", xid).Scan(&advice).Error
	if err != nil {
		return
	}
	for _, v := range advice {
		//扣减库存
		if !IsPharmacyDelivery(v.DrugId, orgid) {
			continue
		}
		err = DrugAutoAddCancelInfo(v, creater)
		if err != nil {
			err = fmt.Errorf("!:%v", err)
			return
		}
		drug, _ := FindBaseDrugLibRecordSeven(orgid, v.DrugId)
		//查询默认仓库
		storeHouseConfig, _ := GetAllStoreHouseConfig(orgid)
		//查询默认仓库剩余多少库存
		var sum_count int64
		stockInfo, _ := GetDrugAllStockInfo(storeHouseConfig.DrugStorehouseOut, orgid, v.DrugId)
		for _, its := range stockInfo {
			sum_count += its.StockMaxNumber*drug.MinNumber + its.StockMinNumber
		}
		UpdateBaseDrugSumTwo(v.DrugId, sum_count, orgid)
	}

	//删除掉发药明细
	for k, _ := range map_time {
		err = tx.Model(&models.Pharmary{}).Where("user_org_id = ? and record_date = ? and patient_id = ? ", orgid, k, patient_id).Updates(map[string]interface{}{
			"status": 0,
			"mtime":  time.Now().Unix(),
		}).Error
		if err != nil {
			return
		}
	}
	return
}

//获取患者名称
func FindUserName(patient_id int64) (name string) {
	var tmp models.GetHisName
	XTReadDB().Model(&models.GetHisName{}).Where("id = ?", patient_id).Find(&tmp)
	name = tmp.Name
	return
}

//获取药品名称
func FindDrugsName(drug_id int64) (name string) {
	var tmp models.Drug
	XTReadDB().Model(&models.Drug{}).Where("id = ?", drug_id).Find(&tmp)
	name = tmp.DrugName
	return
}

//药品发药按钮点击(
func MedicineDeparture(ids string, creater, orgid int64) (err error) {
	//开事务
	tx := XTWriteDB().Begin()
	defer func() {
		if err != nil {
			utils.ErrorLog("事务失败，原因为: %v", err)
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	//处理下字符串
	t_ids := ""
	if ids[len(ids)-1] == 44 {
		t_ids = ids[:len(ids)-1]
	} else {
		t_ids = ids
	}
	time_now := time.Now().Unix()
	tmp_id := strings.Split(t_ids, ",")
	var parameter string //测试
	patient_id := make(map[int64]int64)
	for _, v := range tmp_id {
		front := v[:1]
		after := v[1:]
		if front == "h" {
			var advice_info []*models.HisDoctorAdviceInfo
			err = tx.Model(&models.HisDoctorAdviceInfo{}).Where("id = ? and status = 1", after).Find(&advice_info).Error
			if err != nil {
				return
			}
			for _, v := range advice_info {
				if _, ok := patient_id[v.PatientId]; !ok {
					patient_id[v.PatientId] = v.PatientId
				}
				tmp_bool := IsPharmacyConfig(orgid)
				if tmp_bool {
					if PettyCash(v.DrugId) {
						continue
					}
					kou := FenDrugInventory(v, orgid)
					if !kou {
						err = fmt.Errorf(FindDrugsName(v.DrugId) + "库存不足")
						tmp := models.XtErrs{
							OrgId:     orgid,
							Route:     "creater:" + config.ToString(creater),
							Parameter: parameter,
							Text_err:  err.Error(),
						}
						XTWriteDB().Create(&tmp)
						return
					} else {
						tmps, _ := json.Marshal(advice_info) //
						parameter = parameter + string(tmps) //
					}
					//扣减库存
					err = FenStock(orgid, creater, v)
					if err != nil {
						err = fmt.Errorf("!:%v", err)
						return
					}
				}
			}

			//修改状态
			errs := XTWriteDB().Model(&models.HisDoctorAdviceInfoL{}).Where("id = ?", after).Updates(map[string]interface{}{
				"is_medicine":     1,
				"people":          creater,
				"dispensing_time": time_now,
				"updated_time":    time.Now().Unix(),
			}).Error
			if errs != nil {
				return errs
			}
			err1 := ChangeHisPrescriptionid(after)
			if err1 != nil {
				return err1
			}
		} else {
			var advice []*models.HisDoctorAdviceInfo
			err = tx.Raw("select * from xt_doctor_advice where id = ? and status = 1 and (advice_type = 2 or advice_type = 3)", after).Scan(&advice).Error
			if err != nil {
				return
			}
			for _, v := range advice {
				if _, ok := patient_id[v.PatientId]; !ok {
					patient_id[v.PatientId] = v.PatientId
				}
				tmp_bool := IsPharmacyConfig(orgid)
				if tmp_bool {
					if PettyCash(v.DrugId) {
						continue
					}
					kou := FenDrugInventory(v, orgid)
					if !kou {
						err = fmt.Errorf(FindDrugsName(v.DrugId) + "库存不足")
						tmp := models.XtErrs{
							OrgId:     orgid,
							Route:     "creater:" + config.ToString(creater),
							Parameter: parameter,
							Text_err:  err.Error(),
						}
						XTWriteDB().Create(&tmp)
						return
					} else {
						tmps, _ := json.Marshal(advice)      //
						parameter = parameter + string(tmps) //
					}

					//扣减库存
					err = FenStock(orgid, creater, v)
					if err != nil {
						err = fmt.Errorf("!:%v", err)
						return
					}
				}
			}
			//修改状态
			errs1 := XTWriteDB().Model(&models.XtDoctorAdviceL{}).Where("id = ?", after).Updates(map[string]interface{}{
				"is_medicine":     1,
				"people":          creater,
				"dispensing_time": time_now,
				"updated_time":    time.Now().Unix(),
			}).Error
			if errs1 != nil {
				return errs1
			}
		}
	}

	for _, v := range patient_id {
		//生成明细记录
		tmp_ph := models.Pharmary{
			UserOrgId:  orgid,
			PatientId:  v,
			Ctime:      time.Now().Unix(),
			Mtime:      time.Now().Unix(),
			Status:     1,
			RecordDate: time_now,
		}
		err = tx.Create(&tmp_ph).Error
		if err != nil {
			return err
		}
	}

	return
}

//获取领药人姓名（
func GetUserAdminName(id, orgID int64) string {
	var tmp models.XTSgjUserAdminRole
	XTReadDB().Model(&models.XTSgjUserAdminRole{}).Where("admin_user_id = ? and org_id = ?", id, orgID).Find(&tmp)
	return tmp.UserName
}

//根据id查询是否已发药,true已发药，false未发药
func GiveTheMedicine(id int64) bool {
	var xue models.PharmacyDoctorAdvice
	XTReadDB().Model(&models.PharmacyDoctorAdvice{}).Where("id = ?", id).Find(&xue)
	if xue.IsMedicine == 1 {
		return true
	}
	return false
}

//查询改组中的药品是否包含已发药的，true已发药，false未发药
func GiveGroupMedicine(orgid, groupNo int64) bool {
	var total int
	XTReadDB().Model(&models.DoctorAdvice{}).Where("user_org_id = ? and groupno = ? and status = 1 and is_medicine = 1", orgid, groupNo).Count(&total)
	if total > 0 {
		return true
	}
	return false
}

//查询处方中是否包含已发药的
func GiveChuMedicine(id int64) bool {
	var total int
	XTReadDB().Model(&models.HisDoctorAdviceInfoL{}).Where("prescription_id = ? and status = 1 and is_medicine = 1", id).Count(&total)
	if total > 0 {
		return true
	}
	return false
}

//根据处方id查找该处方中是否存在已发药的药品
func IsChuIssuedDrugs(prescription_id int64) bool {
	var total int
	XTReadDB().Model(&models.HisDoctorAdviceInfoL{}).Where("prescription_id = ? and status = 1 and is_medicine = 1", prescription_id).Count(&total)
	if total > 0 {
		return true
	}
	return false
}

//判断该药品是否通过药房管理出库，true是，false否
//id 药品id,org_id 机构id
func IsPharmacyDelivery(id, org_id int64) bool {
	//判断药品是否通过药房管理
	var total01 int
	XTReadDB().Model(&models.PharmacyBaseDrug{}).Where("id = ? and is_pharmacy = 1", id).Count(&total01)
	//判断该机构是否通过药房管理出库
	var total02 int
	XTReadDB().Model(&models.PharmacyConfig{}).Where("user_org_id = ? and is_open = 1", org_id).Count(&total02)
	if total01 > 0 && total02 > 0 {
		return true
	}
	return false
}

//判断机构是否通过药房管理出库
func IsPharmacyConfig(orgid int64) (bo bool) {
	var total int
	XTReadDB().Model(&models.PharmacyConfig{}).Where("user_org_id = ? and is_open = 1 and status = 1", orgid).Count(&total)
	if total > 0 {
		return true
	}
	return false
}

//根据患者id和发药时间，获取医生的id和姓名
func GetDoctorIds(id, recordtime, orgid int64) (doctor_id int64, doctor_name string, err error) {
	var tmp []*models.TmpAdviceDoctor
	//var tmp []int64
	err = XTReadDB().Raw("select distinct advice_doctor from his_doctor_advice_info where "+
		"status = 1 and dispensing_time = ? and user_org_id = ? and is_medicine = 1 and patient_id = ? and drug_id in (select id from xt_base_drug where org_id = ? and status = 1) "+
		"union "+
		"select distinct advice_doctor from xt_doctor_advice where "+
		"status = 1 and (advice_type = 2 or advice_type = 3) and dispensing_time = ? and user_org_id = ? and is_medicine = 1 and patient_id = ? and drug_id in (select id from xt_base_drug where org_id = ? and status = 1) ",
		recordtime, orgid, id, orgid, recordtime, orgid, id, orgid).Scan(&tmp).Error
	if err != nil || len(tmp) == 0 {
		return
	}
	doctor_id = tmp[0].AdviceDoctor
	doctor_name = GetUserAdminName(doctor_id, orgid)
	return
}

func MapToJson(param map[string]interface{}) string {
	dataType, _ := json.Marshal(param)
	dataString := string(dataType)
	return dataString
}

//封装扣减库存
func FenStock(orgid, creater int64, v *models.HisDoctorAdviceInfo) (err error) {

	err = HisDrugsDelivery(orgid, creater, v)
	if err != nil {
		err = fmt.Errorf("!:%v", err)
		return
	}
	drug, _ := FindBaseDrugLibRecordSeven(orgid, v.DrugId)
	//查询默认仓库
	storeHouseConfig, _ := GetAllStoreHouseConfig(orgid)
	//查询默认仓库剩余多少库存
	var sum_count int64
	stockInfo, _ := GetDrugAllStockInfo(storeHouseConfig.DrugStorehouseOut, orgid, v.DrugId)
	for _, its := range stockInfo {
		sum_count += its.StockMaxNumber*drug.MinNumber + its.StockMinNumber
	}
	UpdateBaseDrugSumTwo(v.DrugId, sum_count, orgid)
	return
}

//封装查询药品库存是否足够
func FenDrugInventory(item *models.HisDoctorAdviceInfo, orgid int64) bool {
	var total int64
	var prescribing_number_total int64
	houseConfig, _ := GetAllStoreHouseConfig(orgid)
	////查询该药品是否有库存
	list, _ := GetDrugTotalCountTwenty(item.DrugId, item.UserOrgId, houseConfig.DrugStorehouseOut)
	////查询改药品信息
	medical, _ := GetBaseDrugMedical(item.DrugId)
	////判断单位是否相等
	if medical.MaxUnit == item.PrescribingNumberUnit {
		prescribingNumber_temp := strconv.FormatFloat(math.Abs(item.PrescribingNumber), 'f', 0, 64)
		count, _ := strconv.ParseInt(prescribingNumber_temp, 10, 64)
		//转化为最小单位
		total = list.Count*medical.MinNumber + list.StockMinNumber
		prescribing_number_total = count * medical.MinNumber
	}
	if medical.MinUnit == item.PrescribingNumberUnit {
		prescribingNumber_temp := strconv.FormatFloat(math.Abs(item.PrescribingNumber), 'f', 0, 64)
		count, _ := strconv.ParseInt(prescribingNumber_temp, 10, 64)
		total = list.Count*medical.MinNumber + list.StockMinNumber
		prescribing_number_total = count
	}
	if prescribing_number_total <= total {
		//可以扣减
		return true
	} else {
		//不可扣减
		return false
	}

}
func GetAdviceIds1(ids []string, orgid, execution_staff int64, thetime time.Time) (tmp []string, err error) {
	var advice []*models.DoctorAdvice
	err = readDb.Model(&models.DoctorAdvice{}).Where("id IN (?) AND status = 1", ids).Find(&advice).Error
	if err != nil {
		return
	}
	for _, v := range advice {
		if !IsPharmacyDelivery(v.DrugId, orgid) {
			tmp = append(tmp, config.ToString(v.ID))
		} else {
			err = XTWriteDB().Model(&models.DoctorAdvice{}).Where("id = ? ", v.ID).Updates(map[string]interface{}{
				"execution_staff": execution_staff,
				"execution_time":  thetime.Unix(),
				"updated_time":    time.Now().Unix(),
			}).Error
			if err != nil {
				return
			}
		}
	}
	return
}
func GetAdviceIds2(ids []string, orgid, execution_staff int64, thetime time.Time) (tmp []string, err error) {
	var advice []*models.HisDoctorAdviceInfoL
	err = readDb.Model(&models.HisDoctorAdviceInfoL{}).Where("id IN (?) AND status = 1", ids).Find(&advice).Error
	if err != nil {
		return
	}
	for _, v := range advice {
		if !IsPharmacyDelivery(v.DrugId, orgid) {
			tmp = append(tmp, config.ToString(v.ID))
		} else {
			err = XTWriteDB().Model(&models.HisDoctorAdviceInfoL{}).Where("id = ? ", v.ID).Updates(map[string]interface{}{
				"execution_staff": execution_staff,
				"execution_time":  thetime.Unix(),
				"updated_time":    time.Now().Unix(),
			}).Error
			if err != nil {
				return
			}
		}
	}
	return
}
func GetAdviceId1(id, orgid, execution_staff int64, thetime time.Time) (bo bool, err error) {
	var advice models.DoctorAdvice
	err = readDb.Model(&models.DoctorAdvice{}).Where("id = ? AND status = 1", id).Find(&advice).Error
	if err != nil {
		return false, err
	}
	if IsPharmacyDelivery(advice.DrugId, orgid) {
		err = XTWriteDB().Model(&models.DoctorAdvice{}).Where("id = ? ", id).Updates(map[string]interface{}{
			"execution_staff": execution_staff,
			"execution_time":  thetime.Unix(),
			"updated_time":    time.Now().Unix(),
		}).Error
		if err != nil {
			return false, err
		}
		return true, err
	}
	return false, err
}
func GetAdviceId2(id, orgid, execution_staff int64, thetime time.Time) (bo bool, err error) {
	var advice models.HisDoctorAdviceInfoL
	err = readDb.Model(&models.HisDoctorAdviceInfoL{}).Where("id = ? AND status = 1", id).Find(&advice).Error
	if err != nil {
		return false, err
	}
	if IsPharmacyDelivery(advice.DrugId, orgid) {
		err = XTWriteDB().Model(&models.HisDoctorAdviceInfoL{}).Where("id = ? ", id).Updates(map[string]interface{}{
			"execution_staff": execution_staff,
			"execution_time":  thetime.Unix(),
			"updated_time":    time.Now().Unix(),
		}).Error
		if err != nil {
			return false, err
		}
		return true, err
	}
	return false, err
}

//判断药品是否零用
func PettyCash(id int64) bool {
	drug := models.XtBaseDrug{}
	XTReadDB().Model(&drug).Where("id = ? and status = 1", id).Find(&drug)
	if drug.IsUse == 1 {
		return true
	}
	return false
}

//初始化
func InitDrugidIsNil(orgid, stime, etime int64) {
	var advice []*models.DoctorAdvice
	XTReadDB().Model(&models.DoctorAdvice{}).Where("drug_id = 0 and user_org_id = ? and status = 1 and created_time >= ? and created_time <= ?", orgid, stime, etime).Find(&advice)
	for _, v := range advice {
		XTWriteDB().Exec("update xt_doctor_advice set drug_id = (select id from xt_base_drug where drug_name = ? and org_id = ?) where id = ?", v.AdviceName, v.UserOrgId, v.ID)
	}
}

//改变处方状态(发药
func ChangeHisPrescription(tmp []int64) (err error) {
	var advice_info []*models.HisDoctorAdviceInfo
	err = XTReadDB().Model(&models.HisDoctorAdviceInfo{}).Where("id in (?) and status = 1", tmp).Find(&advice_info).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil
		}
		return
	}

	tmp_id := make(map[int64]int64)
	for _, v := range advice_info {
		tmp_id[v.PrescriptionId] = v.PrescriptionId
	}
	for k, _ := range tmp_id {
		err = XTWriteDB().Model(&models.HisPrintPrescription{}).Where("id = ?", k).Updates(map[string]interface{}{
			"is_medicine": 1,
			"mtime":       time.Now().Unix(),
		}).Error
		if err != nil {
			return
		}
	}
	return
}

//改变处方状态(退药
func ChangeHisPrescriptionT(tmp []int64) (err error) {
	var advice_info []*models.HisDoctorAdviceInfo
	err = XTReadDB().Model(&models.HisDoctorAdviceInfo{}).Where("id in (?) and status = 1", tmp).Find(&advice_info).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil
		}
		return
	}

	tmp_id := make(map[int64]int64)
	for _, v := range advice_info {
		tmp_id[v.PrescriptionId] = v.PrescriptionId
	}
	for k, _ := range tmp_id {
		var total int
		//查询退药的
		XTReadDB().Model(&models.HisDoctorAdviceInfo{}).Where("prescription_id = ? and status = 1 and is_medicine = 1", k).Count(&total)
		if total == 0 {
			err = XTWriteDB().Model(&models.HisPrintPrescription{}).Where("id = ?", k).Updates(map[string]interface{}{
				"is_medicine": 0,
				"mtime":       time.Now().Unix(),
			}).Error
			if err != nil {
				return
			}
		}
	}
	return
}

//改变处方状态
func ChangeHisPrescriptionid(id string) (err error) {
	var advice models.HisDoctorAdviceInfo
	err = XTReadDB().Model(&models.HisDoctorAdviceInfo{}).Where("id = ? and status = 1", id).Find(&advice).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil
		}
		return
	}
	err = XTWriteDB().Model(&models.HisPrintPrescription{}).Where("id = ?", advice.PrescriptionId).Updates(map[string]interface{}{
		"is_medicine": 1,
		"mtime":       time.Now().Unix(),
	}).Error
	if err != nil {
		return
	}
	return
}
