package controllers

import (
	"XT_New/enums"
	"XT_New/models"
	"XT_New/service"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/jinzhu/gorm"
	"strconv"
	"strings"
	"time"
)

type SelfDrugApiController struct {
	BaseAuthAPIController
}

func SelfDrugRouters() {

	beego.Router("/api/drug/getcurrentpatient", &SelfDrugApiController{}, "Get:GetCurrentPatient")
	beego.Router("/api/drug/getalldrugname", &SelfDrugApiController{}, "Get:GetAllDrugName")
	beego.Router("/api/drug/savedrugname", &SelfDrugApiController{}, "Get:SaveDrugName")
	beego.Router("/api/drug/getdrugnamelist", &SelfDrugApiController{}, "Get:GetDrugNameList")
	beego.Router("/api/drug/getrullename", &SelfDrugApiController{}, "Get:GetRulleName")
	beego.Router("/api/drug/getunitbybaseid", &SelfDrugApiController{}, "Get:GetUnitByBaseId")
	beego.Router("/api/drug/saverullename", &SelfDrugApiController{}, "Get:SaveRulleName")
	beego.Router("/api/drug/editrullername", &SelfDrugApiController{}, "Get:EditRullerName")
	beego.Router("/api/drug/updatedrullername", &SelfDrugApiController{}, "Get:UpdatedRullerName")
	beego.Router("/api/drug/getalldrugnamelist", &SelfDrugApiController{}, "Get:GetAllDrugNameList")
	beego.Router("/api/drug/getrulllistbydrugname", &SelfDrugApiController{}, "Get:GetRullerListByDrugName")
	beego.Router("/api/drug/saveselfmedicines", &SelfDrugApiController{}, "Post:SaveSelfMedicines")
	beego.Router("/api/drug/getcurrentorgallstaff", &SelfDrugApiController{}, "Get:GetCurrentOrgAllStaff")
	beego.Router("/api/drug/savestock", &SelfDrugApiController{}, "Post:SaveStock")
	beego.Router("/api/drug/saveoutstock", &SelfDrugApiController{}, "Post:SaveOutStock")
	beego.Router("/api/drug/deletedrugbyid", &SelfDrugApiController{}, "Get:DeleteDrugById")
	beego.Router("/api/drug/saveradio", &SelfDrugApiController{}, "Get:SaveRadio")
	beego.Router("/api/drug/deletedrugstand", &SelfDrugApiController{}, "Get:DeleteDrugStand")
	beego.Router("/api/drug/getstocklist", &SelfDrugApiController{}, "Get:GetStockList")
	beego.Router("/api/drug/deletedrugname", &SelfDrugApiController{}, "Get:DeleteDrugName")
	beego.Router("/api/drug/getdrugdetail", &SelfDrugApiController{}, "Get:GetDrugDetail")
	beego.Router("/api/drug/getallpatientstocklist", &SelfDrugApiController{}, "Get:GetAllPatientStockList")
	beego.Router("/api/drug/getdrugdatabypatientid", &SelfDrugApiController{}, "Get:GetDrugDataByPatientId")
	beego.Router("/api/drug/getselfmedicallist", &SelfDrugApiController{}, "Get:GetSelfMedicalList")
	beego.Router("/api/drug/getdrugdescbydrugname", &SelfDrugApiController{}, "Get:GetDrugDescByDrugName")
	beego.Router("/api/drug/getdrugset", &SelfDrugApiController{}, "Get:GetDrugSet")
	beego.Router("/api/drug/getallmedicallist", &SelfDrugApiController{}, "Get:GetAllMedicalList")
	beego.Router("/api/drug/getstandname", &SelfDrugApiController{}, "Get:GetStandName")
	beego.Router("/api/drug/getrullerlist", &SelfDrugApiController{}, "Get:GetRullerList")
	beego.Router("/api/drug/deleteDrugNamebyid", &SelfDrugApiController{}, "Get:DeleteDrugNameById")
	beego.Router("/api/drug/getpatientdetail", &SelfDrugApiController{}, "Get:GetPatientDetail")
	//beego.Router("/api/drug/getpatientdetail",&SelfDrugApiController{},"Get:ToPatientDetail")
}

func (this *SelfDrugApiController) GetCurrentPatient() {

	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	patient, err := service.GetCurrentPatient(orgId)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"patient": patient,
	})
}

func (this *SelfDrugApiController) GetAllDrugName() {

	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId

	//查询药品库是否开启
	//configStock, _ := service.GetDrugStockConfig(orgId)
	//if configStock.IsOpen == 1 {
	//
	//}

	drugName, err := service.GetAllDrugName(orgId)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "查寻成功")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"drugName": drugName,
	})

}

func (this *SelfDrugApiController) SaveDrugName() {

	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	drug_name := this.GetString("drug_name")
	id, _ := this.GetInt64("id")
	//fmt.Println("drug_name", drug_name)
	drugName := models.XtDrugName{
		UserOrgId:   orgId,
		DrugName:    drug_name,
		Status:      1,
		CreatedTime: time.Now().Unix(),
		DrugId:      id,
	}
	_, errcode := service.GetDrugName(drug_name, orgId)
	if errcode == gorm.ErrRecordNotFound {
		err := service.SaveDrugName(&drugName)
		if err != nil {
			this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
			return
		}
		this.ServeSuccessJSON(map[string]interface{}{
			"drugName": drugName,
		})
	} else {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
		return
	}
}

func (this *SelfDrugApiController) GetDrugNameList() {

	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	list, err := service.GetDrugNameList(orgId)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": list,
	})
}

func (this *SelfDrugApiController) GetRulleName() {

	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	id, _ := this.GetInt64("id")
	drugId, _ := service.GetDrugId(id)
	rullerList, err := service.GetRulleList(orgId, drugId.DrugId)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"rullerList": rullerList,
	})
}

func (this *SelfDrugApiController) GetUnitByBaseId() {

	id, _ := this.GetInt64("id")
	baseList, err := service.GetUnitByBaseId(id)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"baseList": baseList,
	})
}

func (this *SelfDrugApiController) SaveRulleName() {
	drug_name := this.GetString("drug_name")
	drug_spec := this.GetString("drug_spec")
	drug_stock_limit := this.GetString("drug_stock_limit")
	drug_name_id, _ := this.GetInt64("drug_name_id")
	drug_id, _ := this.GetInt64("drug_id")
	price, _ := this.GetInt64("price")
	prices := strconv.FormatInt(price, 10)
	durg_price, _ := strconv.ParseFloat(prices, 64)
	unit := this.GetString("unit")
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	fmt.Println(drug_name, drug_stock_limit, unit, price, drug_spec, orgId)
	drugSpecName := models.XtStandName{
		DrugName:       drug_name,
		DrugSpec:       drug_spec,
		DrugStockLimit: drug_stock_limit,
		DrugNameId:     drug_name_id,
		Price:          durg_price,
		MinUnit:        unit,
		UserOrgId:      orgId,
		Status:         1,
		CreatedTime:    time.Now().Unix(),
		DrugId:         drug_id,
	}

	//查询该机构下药品规格名称是否存在
	_, errcode := service.IsExistStandName(drug_name, drug_spec, adminUserInfo.CurrentOrgId)

	if errcode == gorm.ErrRecordNotFound {
		err := service.SaveRulleName(&drugSpecName)
		if err != nil {
			this.ServeFailJsonSend(enums.ErrorCodeDataException, "创建规格失败")
			return
		}
		this.ServeSuccessJSON(map[string]interface{}{
			"RullerName": drugSpecName,
		})
	} else if errcode == nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "规格已存在")
		return
	}

}

func (this *SelfDrugApiController) EditRullerName() {

	id, _ := this.GetInt64("id")
	rullerDetail, err := service.GetRullerNameDetail(id)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"rullerDetail": rullerDetail,
	})
}

func (this *SelfDrugApiController) UpdatedRullerName() {

	id, _ := this.GetInt64("id")
	drug_name := this.GetString("drug_name")
	drug_stock_limit := this.GetString("drug_stock_limit")
	price, _ := this.GetInt64("price")
	prices := strconv.FormatInt(price, 10)
	durg_price, _ := strconv.ParseFloat(prices, 64)

	drug_spec := this.GetString("drug_spec")
	unit := this.GetString("unit")
	drug_name_id, _ := this.GetInt64("drug_name_id")
	drug_id, _ := this.GetInt64("drug_id")

	RullerName := models.XtStandName{
		DrugName:       drug_name,
		DrugStockLimit: drug_stock_limit,
		Price:          durg_price,
		DrugSpec:       drug_spec,
		MinUnit:        unit,
		DrugNameId:     drug_name_id,
		DrugId:         drug_id,
	}
	_, errcode := service.GetIsExit(drug_name, drug_spec, id)
	if errcode == gorm.ErrRecordNotFound {
		err := service.UpdatedRullerName(id, &RullerName)
		if err != nil {
			this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
			return
		}
		this.ServeSuccessJSON(map[string]interface{}{
			"RullerName": RullerName,
		})
	} else if errcode == nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
		return
	}

}

func (this *SelfDrugApiController) GetAllDrugNameList() {

	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	rullerName, err := service.GetAllDrugNameList(orgId)

	list, err := service.GetMedicalDrugNameList(orgId)

	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"rullerName": rullerName,
		"list":       list,
	})
}

func (this *SelfDrugApiController) GetRullerListByDrugName() {

	id := this.GetString("id")
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	fmt.Println("orgid", orgId)
	drugName, err := service.GetRullerListByDrugName(id, orgId)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"drugName": drugName,
	})
}

func (this *SelfDrugApiController) SaveSelfMedicines() {

	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
	fmt.Println(err)
	patient_id := int64(dataBody["patient_id"].(float64))
	medicineData, _ := dataBody["medicineData"].([]interface{})
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	for _, item := range medicineData {
		items := item.(map[string]interface{})
		drug_name := items["drug_name"].(string)
		drug_name_id := int64(items["drug_name_id"].(float64))
		drug_spec := items["drug_spec"].(string)
		min_unit := items["min_unit"].(string)
		drug_id := int64(items["drug_id"].(float64))
		//根据drug_id
		drugMedical, _ := service.GetBaseDrugMedical(drug_name_id)
		medical := models.XtSelfMedical{
			DrugName:           drug_name,
			DrugNameId:         drug_name_id,
			DrugSpec:           drug_spec,
			CreatedTime:        time.Now().Unix(),
			Status:             1,
			UserOrgId:          orgId,
			PatientId:          patient_id,
			MinUnit:            min_unit,
			ExecutionFrequency: drugMedical.ExecutionFrequency,
			PrescribingNumber:  drugMedical.PrescribingNumber,
			DeliveryWay:        drugMedical.DeliveryWay,
			SingleDose:         drugMedical.SingleDose,
			DrugId:             drug_id,
		}
		//查询同个病人同个药品同个规格是否已存在
		_, errcode := service.GetSelfMedicalByDrugName(drug_name, drug_spec, patient_id)

		if errcode == gorm.ErrRecordNotFound {
			err := service.CreateSelfMedical(&medical)
			fmt.Println(err)
		} else if errcode == nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
			return
		}

	}
	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "ok"
	this.ServeSuccessJSON(returnData)
	return
}

func (this *SelfDrugApiController) GetCurrentOrgAllStaff() {

	adminUserInfo := this.GetAdminUserInfo()
	orgid := adminUserInfo.CurrentOrgId
	//fmt.Println(orgid)
	appId := adminUserInfo.CurrentAppId
	staff, err := service.GetCurrentOrgAllStaff(orgid, appId)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"staff": staff,
	})
}

func (this *SelfDrugApiController) SaveStock() {

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	start_time := this.GetString("start_time")
	fmt.Println("start_time", start_time)
	admin_user_id, _ := this.GetInt64("admin_user_id")
	fmt.Println("admin_user_id", admin_user_id)
	patient_id, _ := this.GetInt64("patient_id")
	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
	fmt.Println(err)
	stocks, _ := dataBody["stocks"].([]interface{})
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	for _, item := range stocks {
		items := item.(map[string]interface{})
		drug_name := items["drug_name"].(string)
		fmt.Println("drug_name", drug_name)
		drug_name_id := int64(items["drug_name_id"].(float64))
		fmt.Println("parient_id", drug_name_id)
		drug_spec := items["drug_spec"].(string)
		store_number := items["store_number"].(string)
		fmt.Println("store_number", store_number)
		storeNumber, _ := strconv.ParseInt(store_number, 10, 64)
		remarks := items["remarks"].(string)
		min_unit := items["min_unit"].(string)
		medic_id := int64(items["id"].(float64))
		timeStr := time.Now().Format("2006-01-02")
		timeArr := strings.Split(timeStr, "-")
		total, _ := service.FindAllWarehouseOut(adminUserInfo.CurrentOrgId)

		total = total + 1
		warehousing_in_order := strconv.FormatInt(adminUserInfo.CurrentOrgId, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
		number, _ := strconv.ParseInt(warehousing_in_order, 10, 64)
		number = number + total
		warehousing_in_order = "RKD" + strconv.FormatInt(number, 10)

		theTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
		stock := models.XtSelfStock{
			DrugName:      drug_name,
			DrugNameId:    drug_name_id,
			DrugSpec:      drug_spec,
			StoreNumber:   storeNumber,
			Remarks:       remarks,
			AdminUserId:   admin_user_id,
			StorckTime:    theTime.Unix(),
			CreatedTime:   time.Now().Unix(),
			Status:        1,
			UserOrgId:     orgId,
			StockInNumber: warehousing_in_order,
			PatientId:     patient_id,
			MinUnit:       min_unit,
			StorageMode:   1,
			MedicId:       medic_id,
		}
		err := service.CreateStock(&stock)
		fmt.Println("err", err)
	}
	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "ok"
	this.ServeSuccessJSON(returnData)
	return
}

func (this *SelfDrugApiController) SaveOutStock() {

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	start_time := this.GetString("start_time")
	admin_user_id, _ := this.GetInt64("admin_user_id")
	patient_id, _ := this.GetInt64("patient_id")
	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
	fmt.Println(err)
	outStocks, _ := dataBody["outStocks"].([]interface{})
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId

	for _, item := range outStocks {
		items := item.(map[string]interface{})
		drug_name := items["drug_name"].(string)
		drug_name_id := int64(items["drug_name_id"].(float64))
		drug_spec := items["drug_spec"].(string)
		outstore_number := items["outstore_number"].(string)
		outStoreNumber, _ := strconv.ParseInt(outstore_number, 10, 64)
		remarks := items["remarks"].(string)
		medic_id := int64(items["id"].(float64))
		timeStr := time.Now().Format("2006-01-02")
		timeArr := strings.Split(timeStr, "-")
		total, _ := service.FindAllWarehouseOut(adminUserInfo.CurrentOrgId)

		total = total + 1
		warehousing_out_order := strconv.FormatInt(adminUserInfo.CurrentOrgId, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
		number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
		number = number + total
		warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
		fmt.Println(remarks)
		fmt.Println(items)
		theTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
		stock := models.XtSelfOutStock{
			DrugName:       drug_name,
			DrugNameId:     drug_name_id,
			DrugSpec:       drug_spec,
			OutstoreNumber: outStoreNumber,
			Remarks:        remarks,
			AdminUserId:    admin_user_id,
			StorckTime:     theTime.Unix(),
			CreatedTime:    time.Now().Unix(),
			Status:         1,
			UserOrgId:      orgId,
			StockOutNumber: warehousing_out_order,
			PatientId:      patient_id,
			ExitMode:       1,
			MedicId:        medic_id,
		}
		err := service.CreateOutStock(&stock)
		fmt.Println("err", err)
	}
	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "ok"
	this.ServeSuccessJSON(returnData)
	return
}

func (this *SelfDrugApiController) DeleteDrugById() {
	id, _ := this.GetInt64("id")
	drug_name := this.GetString("drug_name")

	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId

	_, errcode := service.GetStandDrugByDrugName(drug_name, orgId)

	if errcode == gorm.ErrRecordNotFound {
		service.DeleteDrugName(id)
		returnData := make(map[string]interface{}, 0)
		returnData["msg"] = "ok"
		this.ServeSuccessJSON(returnData)
	} else if errcode == nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
		return
	}
}

func (this *SelfDrugApiController) SaveRadio() {

	radio, _ := this.GetInt64("radio")
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	drugSet := models.XtDrugSet{
		DrugStart:   radio,
		UserOrgId:   orgId,
		Status:      1,
		CreatedTime: time.Now().Unix(),
	}
	_, errcode := service.GetDrugSetByUserOrgId(orgId)
	if errcode == gorm.ErrRecordNotFound {
		err := service.SaveRadio(&drugSet)
		if err != nil {
			this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
			return
		}
		this.ServeSuccessJSON(map[string]interface{}{
			"drugSet": drugSet,
		})
	} else if errcode == nil {
		err := service.UpdateDrugSet(&drugSet, orgId)
		if err != nil {
			this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
			return
		}
		this.ServeSuccessJSON(map[string]interface{}{
			"drugSet": drugSet,
		})
	}

}

func (this *SelfDrugApiController) DeleteDrugStand() {

	id, _ := this.GetInt64("id")
	name := this.GetString("name")
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId

	_, errcode := service.GetMedicalsByName(orgId, name)
	if errcode == gorm.ErrRecordNotFound {
		err := service.DeleteDrugStand(id)
		fmt.Println(err)
		returnData := make(map[string]interface{}, 0)
		returnData["msg"] = "ok"
		this.ServeSuccessJSON(returnData)
	} else if errcode == nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
		return
	}

}

func (this *SelfDrugApiController) GetStockList() {

	patientid, _ := this.GetInt64("id")
	start_time := this.GetString("start_time")
	fmt.Println("开始时间", start_time)
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	startimeUnix := theTime.Unix()
	keyword := this.GetString("keyword")
	fmt.Println("keyword", keyword)
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	//获取
	medicalList, _ := service.GetMedicalList(patientid, orgId, keyword)
	//统计总数量
	stocklist, err := service.GetStockList(patientid, startimeUnix, keyword, orgId)
	//统计出库数量
	outStocklist, err := service.GetOutStockList(patientid, startimeUnix, keyword, orgId)

	//统计该病人时间段内出库条数
	outList, err := service.GetTotalOutStockList(patientid, startimeUnix, keyword, orgId)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"medicalList":  medicalList,
		"stocklist":    stocklist,
		"outStocklist": outStocklist,
		"outList":      outList,
	})
}

func (this *SelfDrugApiController) DeleteDrugName() {

	drug_name := this.GetString("drugname")
	patient_id, _ := this.GetInt64("patientid")

	//查询该药品是否出库
	stocklist, _ := service.GetStockOutDetail(drug_name, patient_id)
	if len(stocklist) == 0 {
		//删除该药品
		service.DeleteDrugStockNumber(drug_name, patient_id)
		returnData := make(map[string]interface{}, 0)
		returnData["msg"] = "ok"
		this.ServeSuccessJSON(returnData)
	} else {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
		return
	}
}

func (this *SelfDrugApiController) GetDrugDetail() {

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	drug_name := this.GetString("drug_name")
	drug_spec := this.GetString("drug_spec")
	start_time := this.GetString("start_time")
	startTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	end_time := this.GetString("end_time")
	endTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 00:00:00", loc)
	patient_id, _ := this.GetInt64("patient_id")
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	//查询入库明细
	stockDetail, err := service.GetStockDetail(drug_name, drug_spec, startTime.Unix(), endTime.Unix(), patient_id, orgId)

	//查询出库明细
	outStockDetail, err := service.GetOutStockDetail(drug_name, drug_spec, startTime.Unix(), endTime.Unix(), patient_id, orgId)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"stockDetail":    stockDetail,
		"outStockDetail": outStockDetail,
	})
}

func (this *SelfDrugApiController) GetAllPatientStockList() {

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	drug_name := this.GetString("drug_name")
	drug_spec := this.GetString("drug_spec")
	start_time := this.GetString("start_time")
	theTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	startUnix := theTime.Unix()
	end_time := this.GetString("end_time")
	endTimes, _ := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
	endTimeUnix := endTimes.Unix()
	keywords := this.GetString("search_input")
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId

	//入库
	stocklist, err := service.GetAllPatientStockList(drug_name, drug_spec, startUnix, endTimeUnix, keywords, orgId)

	//出库
	outStockList, err := service.GetAllPatientOutStockList(drug_name, drug_spec, startUnix, endTimeUnix, keywords, orgId)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"stocklist":    stocklist,
		"outStockList": outStockList,
	})
}

func (this *SelfDrugApiController) GetDrugDataByPatientId() {

	patient_id, _ := this.GetInt64("patient_id")
	fmt.Println("patient_id", patient_id)
	medicalList, err := service.GetDrugDataByPatientId(patient_id)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"medicalList": medicalList,
	})
}

func (this *SelfDrugApiController) GetSelfMedicalList() {

	patient_id, _ := this.GetInt64("patient_id")
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	_, drugStockConfig := service.FindDrugStockAutomaticReduceRecordByOrgId(orgId)
	privateDrugConfig, _ := service.GetDrugSetByUserOrgId(orgId)
	drugList, _ := service.GetAllBaseDrugLibList(orgId)
	privateDrugList, _ := service.GetPrivateDrugList(patient_id, orgId)

	this.ServeSuccessJSON(map[string]interface{}{
		"base_drug_config":    drugStockConfig,
		"private_drug_config": privateDrugConfig,
		"base_drug_list":      drugList,
		"private_drug_list":   privateDrugList,
	})
	////查询是否开启药品库
	//config, _ := service.GetDruckStockConfig(orgId)
	//
	//fmt.Println("--------------------------",config.IsOpen)
	////开启
	//if config.IsOpen == 1 {
	//  //查询该机构下的药品库
	//  drugName, _ := service.GetAllDrugName(orgId)
	//
	//  //查询该机构是否开启自备药
	//  medical, _ := service.GetSetSelfMedical(orgId)
	//  fmt.Println("medical+++++++++++++++++",medical.DrugStart)
	//  //开启
	//  if medical.DrugStart == 1 {
	//    list, err := service.GetSelfMedicalList(patient_id)
	//    if err != nil {
	//      this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
	//      return
	//    }
	//    this.ServeSuccessJSON(map[string]interface{}{
	//      "medicalList": list,
	//      "drugName":    drugName,
	//    })
	//  } else {
	//    this.ServeSuccessJSON(map[string]interface{}{
	//      "drugName": drugName,
	//    })
	//  }
	//}
}

func (this *SelfDrugApiController) GetDrugDescByDrugName() {

	drug_name := this.GetString("drug_name")
	patient_id, _ := this.GetInt64("patient_id")
	way, _ := this.GetInt64("way")
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	drug_id, _ := this.GetInt64("id")
	//从基础库查询
	if way == 1 {
		//查询基础库数据
		medcal, err := service.GetBaseMedcal(drug_name, orgId)
		//统计入库数量
		countInfo, err := service.GetTotalBaseMedicalCount(drug_id, orgId)

		//统计出库数量
		countout, err := service.GetTotalBaseMedicalCountOut(drug_id, orgId)
		if err != nil {
			this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
			return
		}
		this.ServeSuccessJSON(map[string]interface{}{
			"drugspec":  medcal,
			"countInfo": countInfo,
			"countout":  countout,
		})
	}
	//从自备药库查询
	if way == 2 {
		drugspec, err := service.GetDrugDescByDrugName(drug_name, patient_id, orgId)
		if err != nil {
			this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
			return
		}
		this.ServeSuccessJSON(map[string]interface{}{
			"drugspec": drugspec,
		})
	}

}

func (this *SelfDrugApiController) GetDrugSet() {

	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	drugSet, err := service.GetDrugSet(orgId)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"drugSet": drugSet,
	})

}

func (this *SelfDrugApiController) GetAllMedicalList() {

	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	list, err := service.GetAllMedicalList(orgId)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"drugName": list,
	})
}

func (this *SelfDrugApiController) GetStandName() {

	name := this.GetString("name")
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	rullerlist, err := service.GetRulleName(orgId, name)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"rullerlist": rullerlist,
	})
}

func (this *SelfDrugApiController) GetRullerList() {
	id, _ := this.GetInt64("id")
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	rullerList, err := service.GetRulleList(orgId, id)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"rullerlist": rullerList,
	})
}

func (this *SelfDrugApiController) DeleteDrugNameById() {

	id, _ := this.GetInt64("id")
	drug_name := this.GetString("drug_name")
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId

	_, errcode := service.GetStandDrugByDrugName(drug_name, orgId)

	if errcode == gorm.ErrRecordNotFound {
		service.DeleteDrugNameById(id)
		returnData := make(map[string]interface{}, 0)
		returnData["msg"] = "ok"
		this.ServeSuccessJSON(returnData)
	} else if errcode == nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
		return
	}
}

func (this *SelfDrugApiController) GetPatientDetail() {

	id, _ := this.GetInt64("id")
	adminUserInfo := this.GetAdminUserInfo()
	patientDetail, err := service.GetPatientDetail(id, adminUserInfo.CurrentOrgId)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"patientDetail": patientDetail,
	})
}

//func (this *SelfDrugApiController) ToPatientDetail()  {
//
//  keyword := this.GetString("keyword")
//  adminUser := this.GetAdminUserInfo()
//  orgId := adminUser.CurrentOrgId
//  patient, err := service.ToSeachPatient(keyword, orgId)
//  if err != nil {
//    this.ServeFailJsonSend(enums.ErrorCodeDataException, "更新设备失败")
//    return
//  }
//  this.ServeSuccessJSON(map[string]interface{}{
//    "patient": patient,
//  })
//}
