package controllers

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

type PharmacyApiController struct {
	BaseAuthAPIController
}

func PharmacyApiControllersRegisterRouters() {

	//获取设置为药房发药的药品数据
	beego.Router("/api/advice/gettodayadvicelist", &PharmacyApiController{}, "Get:GetTodayAdviceList")
	//获取今日未发药的数据
	beego.Router("api/advice/getpharmacybasedrug", &PharmacyApiController{}, "Get:GetPharyMacyBaseDrug")
	//发药
	beego.Router("/api/advice/updatepharmacybasedrug", &PharmacyApiController{}, "Get:UpdatePharmacyBaseDrug")

	//获取今日已发药的数据
	beego.Router("/api/advice/getpharmacybasedruglist", &PharmacyApiController{}, "Get:GetPharmacyBaseDrugList")
	//退药流程
	beego.Router("/api/advice/getreturnpharmacybasedrug", &PharmacyApiController{}, "Get:GetReturnPharmacyBaseDrug")

	//设置
	beego.Router("/api/advice/savesetting", &PharmacyApiController{}, "Get:SaveSetting")

	beego.Router("/api/advice/getpharmacyconfig", &PharmacyApiController{}, "Get:GetPharmacyConfig")

}

func (this *PharmacyApiController) GetTodayAdviceList() {

	orgId := this.GetAdminUserInfo().CurrentOrgId
	//获取药房发药药品库数据
	appId := this.GetAdminUserInfo().CurrentAppId
	doctorlist, err := service.GetAllDoctorSix(orgId, appId)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"doctorlist": doctorlist,
		})
	} else {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}

func (this *PharmacyApiController) GetPharyMacyBaseDrug() {

	start_time := this.GetString("start_time")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	var theStartTime int64
	if len(start_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
		}
		theStartTime = theTime.Unix()
	}

	drug_id, _ := this.GetInt64("drug_id")

	orgId := this.GetAdminUserInfo().CurrentOrgId
	//获取血透医嘱
	advicelist, _ := service.GetBloodAdviceList(theStartTime, drug_id, orgId)

	//获取医保医嘱
	hisAdviceList, err := service.GetHisAdviceList(theStartTime, drug_id, orgId)

	patient, _ := service.GetAllPatientListSix(orgId)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"advicelist":    advicelist,
			"hisAdviceList": hisAdviceList,
			"patient":       patient,
		})
	} else {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}

func (this *PharmacyApiController) UpdatePharmacyBaseDrug() {

	bloodStr := this.GetString("bloodStr")

	hisStr := this.GetString("hisStr")

	admin_user_id, _ := this.GetInt64("admin_user_id")
	if len(bloodStr) == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	idArray := strings.Split(bloodStr, ",")

	if len(hisStr) == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	idArrayOne := strings.Split(hisStr, ",")

	fmt.Println("idArray23332233223", idArray)
	fmt.Println("idArrayOne23332233223", idArrayOne)

	orgId := this.GetAdminUserInfo().CurrentOrgId
	service.UpdatePharmacyAdviceBaseDrug(idArray, orgId)
	service.UpdatePharmacyHisAdviceBaseDrug(idArray, orgId)

	//出库逻辑
	adviceList, _ := service.GetPharmacyAdviceList(idArray, orgId)

	hisAdviceList, _ := service.GetPharmacyHisAdviceList(idArray, orgId)

	//查询是否通过药房出库
	pharmacyConfig, _ := service.FindPharmacyConfig(orgId)
	if pharmacyConfig.IsOpen == 1 {
		var total int64
		var prescribing_number_total int64
		//创建流水
		timeStr := time.Now().Format("2006-01-02")
		timeArr := strings.Split(timeStr, "-")
		totals, _ := service.FindAllPharmacyDrugWarehouseOut(orgId)
		totals = totals + 1
		warehousing_out_order := strconv.FormatInt(orgId, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
		number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
		number = number + totals
		warehousing_out_order = "FY" + strconv.FormatInt(number, 10)

		//血透
		for _, item := range adviceList {

			pharmacy := models.Pharmacy{
				UserOrgId:      item.UserOrgId,
				PatientId:      item.PatientId,
				PrescriptionId: 0,
				XtAdviceId:     item.ID,
				HisOrXt:        1,
				Ctime:          time.Now().Unix(),
				Mtime:          0,
				Status:         1,
				HisAdviceId:    0,
				DrugId:         item.DrugId,
				RecordDate:     item.AdviceDate,
				OrdreNumber:    warehousing_out_order,
				Creater:        admin_user_id,
			}

			service.CreatePharmacy(pharmacy)

			lastPharmacy, _ := service.GetLastPharmary(item.UserOrgId, item.ID, item.AdviceDate)

			houseConfig, _ := service.GetAllStoreHouseConfig(orgId)
			////查询该药品是否有库存
			list, _ := service.GetDrugTotalCountTwenty(item.DrugId, item.UserOrgId, houseConfig.DrugStorehouseOut)
			//
			////查询改药品信息
			medical, _ := service.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 (list.Count*medical.MinNumber + list.StockMinNumber) == 0 {
				this.ServeSuccessJSON(map[string]interface{}{
					"msg":     "3",
					"medical": medical,
				})
				return
			}
			if prescribing_number_total > total {
				this.ServeSuccessJSON(map[string]interface{}{
					"msg":     "2",
					"medical": medical,
				})
				return
			}

			if prescribing_number_total <= total {

				//查询是否门诊处方和临时医嘱同步到透析医嘱的开关是否开启
				adviceSetting, _ := service.FindAdviceSettingById(item.UserOrgId)
				if adviceSetting.IsAdviceOpen == 1 {
					if medical.IsUse == 2 {
						service.PharmacyDrugsDelivery(item.UserOrgId, item.ExecutionStaff, item, lastPharmacy.ID)
						//查询默认仓库
						houseConfig, _ := service.GetAllStoreHouseConfig(item.UserOrgId)
						//查询默认仓库剩余多少库存
						list, _ := service.GetDrugSumCountByStorehouseId(houseConfig.DrugStorehouseOut, item.UserOrgId, item.DrugId)
						var sum_count int64
						var sum_in_count int64
						for _, it := range list {
							baseDrug, _ := service.GetBaseDrugMedical(it.DrugId)
							if it.MaxUnit == baseDrug.MaxUnit {
								it.StockMaxNumber = it.StockMaxNumber * baseDrug.MinNumber
								it.WarehousingCount = it.WarehousingCount * baseDrug.MinNumber
							}
							sum_count += it.StockMaxNumber + it.StockMinNumber
							sum_in_count += it.WarehousingCount
						}
						service.UpdateMedicalSumCount(item.DrugId, sum_count, sum_in_count, item.UserOrgId)
						break
						this.ServeSuccessJSON(map[string]interface{}{
							"msg":     "1",
							"medical": medical,
						})
						return
					}
					if medical.IsUse == 1 {
						this.ServeSuccessJSON(map[string]interface{}{
							"msg": "1",
						})
						return
					}

				} else {
					if medical.IsUse == 2 {
						service.PharmacyDrugsDelivery(item.UserOrgId, item.ExecutionStaff, item, lastPharmacy.ID)
						//查询默认仓库
						houseConfig, _ := service.GetAllStoreHouseConfig(item.UserOrgId)
						//查询默认仓库剩余多少库存
						list, _ := service.GetDrugSumCountByStorehouseId(houseConfig.DrugStorehouseOut, item.UserOrgId, item.DrugId)
						var sum_count int64
						var sum_in_count int64
						for _, it := range list {
							baseDrug, _ := service.GetBaseDrugMedical(it.DrugId)
							if it.MaxUnit == baseDrug.MaxUnit {
								it.StockMaxNumber = it.StockMaxNumber * baseDrug.MinNumber
								it.WarehousingCount = it.WarehousingCount * baseDrug.MinNumber
							}
							sum_count += it.StockMaxNumber + it.StockMinNumber
							sum_in_count += it.WarehousingCount
						}
						service.UpdateMedicalSumCount(item.DrugId, sum_count, sum_in_count, item.UserOrgId)
						this.ServeSuccessJSON(map[string]interface{}{
							"msg":     "1",
							"medical": medical,
						})
						return
					}
					if medical.IsUse == 1 {
						this.ServeSuccessJSON(map[string]interface{}{
							"msg":     "1",
							"medical": medical,
						})
						return
					}
				}
			}
		}

		//血透
		for _, item := range hisAdviceList {

			pharmacy := models.Pharmacy{
				UserOrgId:      item.UserOrgId,
				PatientId:      item.PatientId,
				PrescriptionId: 0,
				XtAdviceId:     0,
				HisOrXt:        2,
				Ctime:          time.Now().Unix(),
				Mtime:          0,
				Status:         1,
				HisAdviceId:    item.ID,
				DrugId:         item.DrugId,
				RecordDate:     item.AdviceDate,
				OrdreNumber:    warehousing_out_order,
				Creater:        admin_user_id,
			}

			service.CreatePharmacy(pharmacy)

			lastPharmary, _ := service.GetLastHisPharmary(item.UserOrgId, item.ID, item.AdviceDate)

			houseConfig, _ := service.GetAllStoreHouseConfig(orgId)
			////查询该药品是否有库存
			list, _ := service.GetDrugTotalCountTwenty(item.DrugId, item.UserOrgId, houseConfig.DrugStorehouseOut)
			//
			////查询改药品信息
			medical, _ := service.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 (list.Count*medical.MinNumber + list.StockMinNumber) == 0 {
				this.ServeSuccessJSON(map[string]interface{}{
					"msg":     "3",
					"medical": medical,
				})
				return
			}
			if prescribing_number_total > total {
				this.ServeSuccessJSON(map[string]interface{}{
					"msg":     "2",
					"medical": medical,
				})
				return
			}

			if prescribing_number_total <= total {

				//查询是否门诊处方和临时医嘱同步到透析医嘱的开关是否开启
				adviceSetting, _ := service.FindAdviceSettingById(item.UserOrgId)
				if adviceSetting.IsAdviceOpen == 1 {
					if medical.IsUse == 2 {
						service.PharmacyHisDrugsDelivery(item.UserOrgId, item.ExecutionStaff, item, lastPharmary.ID)
						//查询默认仓库
						houseConfig, _ := service.GetAllStoreHouseConfig(item.UserOrgId)
						//查询默认仓库剩余多少库存
						list, _ := service.GetDrugSumCountByStorehouseId(houseConfig.DrugStorehouseOut, item.UserOrgId, item.DrugId)
						var sum_count int64
						var sum_in_count int64
						for _, it := range list {
							baseDrug, _ := service.GetBaseDrugMedical(it.DrugId)
							if it.MaxUnit == baseDrug.MaxUnit {
								it.StockMaxNumber = it.StockMaxNumber * baseDrug.MinNumber
								it.WarehousingCount = it.WarehousingCount * baseDrug.MinNumber
							}
							sum_count += it.StockMaxNumber + it.StockMinNumber
							sum_in_count += it.WarehousingCount
						}
						service.UpdateMedicalSumCount(item.DrugId, sum_count, sum_in_count, item.UserOrgId)
						break
						this.ServeSuccessJSON(map[string]interface{}{
							"msg":     "1",
							"medical": medical,
						})
						return
					}
					if medical.IsUse == 1 {
						this.ServeSuccessJSON(map[string]interface{}{
							"msg": "1",
						})
						return
					}

				} else {
					if medical.IsUse == 2 {
						service.PharmacyHisDrugsDelivery(item.UserOrgId, item.ExecutionStaff, item, lastPharmary.ID)
						//查询默认仓库
						houseConfig, _ := service.GetAllStoreHouseConfig(item.UserOrgId)
						//查询默认仓库剩余多少库存
						list, _ := service.GetDrugSumCountByStorehouseId(houseConfig.DrugStorehouseOut, item.UserOrgId, item.DrugId)
						var sum_count int64
						var sum_in_count int64
						for _, it := range list {
							baseDrug, _ := service.GetBaseDrugMedical(it.DrugId)
							if it.MaxUnit == baseDrug.MaxUnit {
								it.StockMaxNumber = it.StockMaxNumber * baseDrug.MinNumber
								it.WarehousingCount = it.WarehousingCount * baseDrug.MinNumber
							}
							sum_count += it.StockMaxNumber + it.StockMinNumber
							sum_in_count += it.WarehousingCount
						}
						service.UpdateMedicalSumCount(item.DrugId, sum_count, sum_in_count, item.UserOrgId)
						this.ServeSuccessJSON(map[string]interface{}{
							"msg":     "1",
							"medical": medical,
						})
						return
					}
					if medical.IsUse == 1 {
						this.ServeSuccessJSON(map[string]interface{}{
							"msg":     "1",
							"medical": medical,
						})
						return
					}
				}
			}
		}
	}
}

func (this *PharmacyApiController) GetPharmacyBaseDrugList() {

	start_time := this.GetString("start_time")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	var theStartTime int64
	if len(start_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
		}
		theStartTime = theTime.Unix()
	}

	drug_id, _ := this.GetInt64("drug_id")

	orgId := this.GetAdminUserInfo().CurrentOrgId
	//获取血透医嘱
	advicelist, _ := service.GetUseredBloodAdviceList(theStartTime, drug_id, orgId)

	//获取医保医嘱
	hisAdviceList, err := service.GetUseredHisAdviceList(theStartTime, drug_id, orgId)

	patient, _ := service.GetAllPatientListSix(orgId)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"advicelist":    advicelist,
			"hisAdviceList": hisAdviceList,
			"patient":       patient,
		})
	} else {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}

func (this *PharmacyApiController) GetReturnPharmacyBaseDrug() {

	bloodStr := this.GetString("bloodStr")

	hisStr := this.GetString("hisStr")

	if len(bloodStr) == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	idArray := strings.Split(bloodStr, ",")

	if len(hisStr) == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	idArrayOne := strings.Split(hisStr, ",")

	fmt.Println("idArray23332233223", idArray)
	fmt.Println("idArrayOne23332233223", idArrayOne)

	orgId := this.GetAdminUserInfo().CurrentOrgId
	service.UpdateReturnPharmacyAdviceBaseDrug(idArray, orgId)
	service.UpdateReturnPharmacyHisAdviceBaseDrug(idArray, orgId)
}

func (this *PharmacyApiController) SaveSetting() {
	var err error
	defer func() {
		if err != nil {
			service.SaveErrs(this.GetAdminUserInfo().CurrentOrgId, this.Ctx.Input, err)
		}
	}()
	is_open, _ := this.GetInt64("is_open")

	orgId := this.GetAdminUserInfo().CurrentOrgId
	config := models.PharmacyConfig{
		UserOrgId: orgId,
		IsOpen:    is_open,
		Status:    1,
		Ctime:     time.Now().Unix(),
	}

	//查找是否存在
	_, errcode := service.GetConfigSettingIsExsit(orgId)
	if errcode == gorm.ErrRecordNotFound {
		service.CreatePharmacyConfig(&config)
	} else if errcode == nil {
		service.UpdatePharmacyConfig(orgId, &config)
	}
	if is_open == 2 {
		err = fmt.Errorf("用户关闭药房管理出库")
	} else {
		err = fmt.Errorf("用户开启药房管理出库")
	}

	this.ServeSuccessJSON(map[string]interface{}{
		"config": config,
	})
}

func (this *PharmacyApiController) GetPharmacyConfig() {

	orgId := this.GetAdminUserInfo().CurrentOrgId

	config, err := service.GetPharmacyConfig(orgId)

	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"config": config,
		})
	} else {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}
