package controllers

import (
	"Xcx_New/enums"
	"Xcx_New/models"
	"Xcx_New/service"
	"Xcx_New/utils"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"reflect"
	"strconv"
	"strings"
	"time"
)

type StockDrugApiController struct {
	BaseAuthAPIController
}

func DrugStockManagerApiRegistRouters() {

	//入库管理和其他入库管理相关接口
	beego.Router("/api/drugwarehouse/create", &StockDrugApiController{}, "post:CreateDrugWarehouse")
	beego.Router("/api/drugwarehouse/list", &StockDrugApiController{}, "get:GetDrugWarehouseList")
	beego.Router("/api/drugwarehouse/delete", &StockDrugApiController{}, "post:DeleteDrugWarehouse")
	beego.Router("/api/drugwarehouseinfo/delete", &StockDrugApiController{}, "post:DeleteDrugWarehouseInfo")
	beego.Router("/api/drugwarehouseinfo/list", &StockDrugApiController{}, "get:GetDrugWarehouseInfoList")
	beego.Router("/api/drugwarehouse/edit", &StockDrugApiController{}, "post:EditDrugWarehouse")

	//退货管理和其他退货管理相关接口
	beego.Router("/api/drugsalesreturn/create", &StockDrugApiController{}, "post:CreateDrugSalesReturn")
	beego.Router("/api/drugsalesreturn/delete", &StockDrugApiController{}, "post:DeleteDrugSalesReturn")
	beego.Router("/api/drugsalesreturninfo/delete", &StockDrugApiController{}, "post:DeleteDrugSalesReturnInfo")
	beego.Router("/api/drugsalesreturninfo/list", &StockDrugApiController{}, "get:GetDrugSalesReturnInfoList")
	beego.Router("/api/drugsalesreturn/list", &StockDrugApiController{}, "get:GetDrugSalesReturnList")
	beego.Router("/api/drugsalesreturn/edit", &StockDrugApiController{}, "post:EditDrugReturnInfo")

	//出库管理和其他出库管理相关接口
	beego.Router("/api/drugwarehouseout/create", &StockDrugApiController{}, "post:CreateDrugWarehouseOut")
	beego.Router("/api/drugwarehouseout/delete", &StockDrugApiController{}, "post:DeleteDrugWarehouseOut")
	beego.Router("/api/drugwarehouseoutinfo/delete", &StockDrugApiController{}, "post:DeleteDrugWarehouseOutInfo")
	beego.Router("/api/drugwarehouseout/list", &StockDrugApiController{}, "get:GetDrugWarehouseOutList")
	beego.Router("/api/drugwarehouseout/edit", &StockDrugApiController{}, "post:EditDrugWarehouseOut")
	beego.Router("/api/drugwarehouseout/info", &StockDrugApiController{}, "get:GetDrugWarehouseOutInfoList")

	//出库退库管理和其他出库退库管理相关接口
	beego.Router("/api/drugcancelstock/create", &StockDrugApiController{}, "post:CreateDrugCancelStock")
	beego.Router("/api/drugcancelstock/list", &StockDrugApiController{}, "get:GetDrugCancelStockList")
	beego.Router("/api/drugcancelstock/info", &StockDrugApiController{}, "get:GetDrugCancelStockInfoList")
	beego.Router("/api/drugcancelstock/delete", &StockDrugApiController{}, "post:DeleteDrugCancelStock")
	beego.Router("/api/drugcancelstockinfo/delete", &StockDrugApiController{}, "post:DeleteDrugCancelStockInfo")
	beego.Router("/api/drugcancelstockinfo/edit", &StockDrugApiController{}, "post:EditDrugCancelStock")
	//beego.Router("/api/drugcancelstockinfo/config", &StockDrugApiController{}, "get:GetDrugCancelStockConfig")

	////库存相关全局配置
	beego.Router("/api/drugstock/config", &StockDrugApiController{}, "get:GetAllConfig")
	//beego.Router("/api/drugreturn/config", &StockDrugApiController{}, "get:GetAllSalesReturnConfig")
	//
	////库存查询
	beego.Router("/api/drugstock/query", &StockDrugApiController{}, "get:GetDrugQueryInfo")
	//
	//beego.Router("/api/drugstock/detail", &StockDrugApiController{}, "get:GetDetailInfo")
	//
	beego.Router("/api/drugwarehouseout/user", &StockDrugApiController{}, "get:GetUserDetailInfo")

	beego.Router("/api/drugstock/get", &StockDrugApiController{}, "get:GetAllDrugStock")

	beego.Router("/api/drug/getcanceldrugorderprint", &StockDrugApiController{}, "get:GetCancelDrugOrderPrint")
	beego.Router("/api/drug/drugcancelexportlist", &StockDrugApiController{}, "get:GetDrugCancelExportList")
	beego.Router("/api/drug/getdrugwarehouseinfoprint", &StockDrugApiController{}, "get:GetDrugWarehouseInfoPrint")
	beego.Router("/api/drug/getdrugoutorderprint", &StockDrugApiController{}, "get:GetDrugOutOrderPrint")

}

func (c *StockDrugApiController) CreateDrugWarehouse() {

	warehousing_time := c.GetString("warehousing_time")

	types, _ := c.GetInt64("type", 0)

	ctime := time.Now().Unix()
	adminUserInfo := c.GetAdminUserInfo()

	warehousingDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", warehousing_time)
	if parseDateErr != nil {
		c.ErrorLog("日期(%v)解析错误：%v", warehousingDate, parseDateErr)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	timeStr := time.Now().Format("2006-01-02")
	timeArr := strings.Split(timeStr, "-")
	total, _ := service.FindAllWarehouseTotalOne(adminUserInfo.CurrentOrgId)
	total = total + 1
	fmt.Println("total2323232323232", total)
	warehousing_order := "YPRKD" + strconv.FormatInt(adminUserInfo.CurrentOrgId, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000" + strconv.FormatInt(total, 10)
	fmt.Println("r入库单据好  2323232322223", warehousing_order)
	operation_time := time.Now().Unix()
	creater := adminUserInfo.AdminUser.Id
	warehousing := models.DrugWarehouse{
		WarehousingOrder: warehousing_order,
		OperationTime:    operation_time,
		OrgId:            adminUserInfo.CurrentOrgId,
		Creater:          creater,
		Ctime:            ctime,
		Status:           1,
		WarehousingTime:  warehousingDate.Unix(),
		Type:             types,
	}
	service.AddSigleDrugWarehouse(&warehousing)
	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	var warehousingInfo []*models.DrugWarehouseInfo
	var drugFlow []*models.DrugFlow
	if dataBody["stockIn"] != nil && reflect.TypeOf(dataBody["stockIn"]).String() == "[]interface {}" {
		thisStockIn, _ := dataBody["stockIn"].([]interface{})
		if len(thisStockIn) > 0 {
			for _, item := range thisStockIn {
				items := item.(map[string]interface{})

				if items["drug_id"] == nil || reflect.TypeOf(items["drug_id"]).String() != "float64" {
					utils.ErrorLog("drug_id")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				drug_id := int64(items["drug_id"].(float64))

				if items["warehousing_count"] == nil || reflect.TypeOf(items["warehousing_count"]).String() != "string" {
					utils.ErrorLog("warehousing_count")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}

				warehousing_count, _ := strconv.ParseInt(items["warehousing_count"].(string), 10, 64)

				if items["last_price"] == nil || reflect.TypeOf(items["last_price"]).String() != "string" {
					utils.ErrorLog("last_price")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				last_price, _ := strconv.ParseFloat(items["last_price"].(string), 64)
				total := float64(warehousing_count) * last_price

				retail_price_total := float64(warehousing_count) * last_price

				var productDates int64
				var expiryDates int64

				if items["expiry_date"] == nil || reflect.TypeOf(items["expiry_date"]).String() != "string" {
					expiryDates = 0
				} else {
					if len(items["expiry_date"].(string)) == 0 {
						expiryDates = 0

					} else {
						expiryDate, _ := items["expiry_date"].(string)
						expiry_date, _ := utils.ParseTimeStringToTime("2006-01-02", expiryDate)
						expiryDates = expiry_date.Unix()

					}

				}
				if items["product_date"] == nil || reflect.TypeOf(items["product_date"]).String() != "string" {
					productDates = 0
				} else {
					if len(items["product_date"].(string)) == 0 {
						productDates = 0

					} else {
						productDate, _ := items["product_date"].(string)
						product_date, _ := utils.ParseTimeStringToTime("2006-01-02", productDate)
						productDates = product_date.Unix()
					}

				}

				number, _ := items["number"].(string)

				batch_number, _ := items["batch_number"].(string)

				if items["max_unit"] == nil || reflect.TypeOf(items["max_unit"]).String() != "string" {
					utils.ErrorLog("max_unit")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				max_unit, _ := items["max_unit"].(string)

				if items["min_unit"] == nil || reflect.TypeOf(items["min_unit"]).String() != "string" {
					utils.ErrorLog("min_unit")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				min_unit, _ := items["min_unit"].(string)

				var remark string
				if items["remark"] == nil || reflect.TypeOf(items["remark"]).String() != "string" {
					remark = ""
				} else {
					remark = items["remark"].(string)
				}

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

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

				warehouseInfo := &models.DrugWarehouseInfo{
					WarehousingOrder: warehousing.WarehousingOrder,
					WarehousingId:    warehousing.ID,
					DrugId:           drug_id,
					Number:           number,
					ProductDate:      productDates,
					ExpiryDate:       expiryDates,
					WarehousingCount: warehousing_count,
					Price:            last_price,
					TotalPrice:       total,
					Status:           1,
					Ctime:            ctime,
					Remark:           remark,
					OrgId:            adminUserInfo.CurrentOrgId,
					Type:             types,
					Manufacturer:     manufacturer,
					Dealer:           dealer,
					StockMaxNumber:   warehousing_count,
					RetailTotalPrice: retail_price_total,
					BatchNumber:      batch_number,
					MaxUnit:          max_unit,
					MinUnit:          min_unit,
				}
				warehousingInfo = append(warehousingInfo, warehouseInfo)

				drugflow := &models.DrugFlow{
					WarehousingOrder: warehousing.WarehousingOrder,
					WarehousingId:    warehousing.ID,
					DrugId:           drug_id,
					Number:           number,
					ProductDate:      productDates,
					ExpireDate:       expiryDates,
					Count:            warehousing_count,
					Price:            last_price,
					Status:           1,
					Ctime:            ctime,
					UserOrgId:        adminUserInfo.CurrentOrgId,
					Manufacturer:     manufacturer,
					Dealer:           dealer,
					BatchNumber:      batch_number,
					MaxUnit:          max_unit,
					MinUnit:          min_unit,
					ConsumableType:   1,
					IsEdit:           1,
					Creator:          adminUserInfo.AdminUser.Id,
					IsSys:            0,
				}

				drugFlow = append(drugFlow, drugflow)

			}
		}
	}
	//创建入库单
	errs := service.CreateDrugWarehousingInfo(warehousingInfo)
	if errs == nil {
		//更改库存
		var total float64
		var min_number int64
		for _, item := range warehousingInfo {
			//查询刚入库耗材的库存
			wareseInfo, _ := service.FindDrugWaresingCount(item.DrugId, item.OrgId)
			//更新药品库的总量
			info, _ := service.FindeDrugInfo(item.DrugId)

			min_number = wareseInfo.StockMaxNumber * info.MinNumber
			str := strconv.FormatInt(min_number, 10)
			minFloat, _ := strconv.ParseFloat(str, 64)
			total = info.Total + minFloat
			lib := models.BaseDrugLib{
				Total: total,
			}
			service.UpdateBaseDrug(&lib, item.DrugId)
		}
	}
	//创建流水单
	service.CreateDrugFlow(drugFlow)

	info, _ := service.FindLastDrugWarehousingInfo(warehousing.WarehousingOrder)

	if errs != nil {
		utils.ErrorLog(errs.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateStockInFail)
		return
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"msg":               "入库成功",
		"warehousing_order": warehousing_order,
		"info":              info,
	})

}
func (c *StockDrugApiController) GetDrugWarehouseList() {
	page, _ := c.GetInt64("page", -1)
	limit, _ := c.GetInt64("limit", -1)
	start_time := c.GetString("start_time")
	end_time := c.GetString("end_time")
	types, _ := c.GetInt64("type", 0)
	keywords := c.GetString("keywords")

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	var startTime int64
	if len(start_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
		if err != nil {
			fmt.Println(err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	var endTime int64
	if len(end_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}

	adminUserInfo := c.GetAdminUserInfo()
	fmt.Println("hhh2h3h23h2h32h3h2h32h32h3h2h3", keywords)
	//按药品名称搜索
	var ids []int64
	var idArray []int64
	list, _ := service.GetDrugNameByKeyword(keywords, adminUserInfo.CurrentOrgId)
	for _, item := range list {
		ids = append(ids, item.ID)
	}

	//查找入库单详情
	if len(ids) > 0 {
		info, _ := service.GetDrugWarehouseOrderDetailTwo(ids, adminUserInfo.CurrentOrgId, startTime, endTime)
		for _, it := range info {
			idArray = append(idArray, it.WarehousingId)
		}
	}

	warehouseList, total, err := service.FindAllDrugWarehousingListOne(adminUserInfo.CurrentOrgId, page, limit, startTime, endTime, types, keywords, idArray)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"list":  warehouseList,
			"total": total,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}
func (c *StockDrugApiController) GetDrugWarehouseInfoList() {
	id, _ := c.GetInt64("id", 0)

	if id <= 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	admin := c.GetAdminUserInfo()

	warehousing, err := service.FindDrugWarehousingById(id, admin.CurrentOrgId)

	manufacturerList, _ := service.GetAllManufacturerList(admin.CurrentOrgId)
	dealerList, _ := service.GetAllDealerList(admin.CurrentOrgId)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}

	if warehousing.ID <= 0 {
		return
	}

	warehousingInfo, err := service.FindDrugWarehousingInfoByIdThree(id, admin.CurrentOrgId)

	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"info":             warehousingInfo,
			"warehousing":      warehousing,
			"manufacturerList": manufacturerList,
			"dealerList":       dealerList,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}

func (c *StockDrugApiController) EditDrugWarehouse() {

	warehousing_time := c.GetString("warehousing_time")
	id, _ := c.GetInt64("id", 0)
	types, _ := c.GetInt64("type", 0)

	if id == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	ctime := time.Now().Unix()
	mtime := time.Now().Unix()
	adminUserInfo := c.GetAdminUserInfo()

	warehousingDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", warehousing_time)
	if parseDateErr != nil {
		c.ErrorLog("日期(%v)解析错误：%v", warehousingDate, parseDateErr)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	warehouse, _ := service.FindDrugWarehousingById(id, adminUserInfo.CurrentOrgId)

	warehousing := models.DrugWarehouse{
		WarehousingOrder: warehouse.WarehousingOrder,
		OrgId:            adminUserInfo.CurrentOrgId,
		Modifier:         adminUserInfo.AdminUser.Id,
		Mtime:            mtime,
		Status:           1,
		WarehousingTime:  warehousingDate.Unix(),
		Type:             warehouse.Type,
	}

	service.EditDrugWarehousingOne(warehousing, id)

	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	var warehousingInfo []*models.DrugWarehouseInfo
	var upDateWarehousingInfo []*models.DrugWarehouseInfo
	var drugFlow []*models.DrugFlow
	if dataBody["stockIn"] != nil && reflect.TypeOf(dataBody["stockIn"]).String() == "[]interface {}" {
		thisStockIn, _ := dataBody["stockIn"].([]interface{})

		if len(thisStockIn) > 0 {
			for _, item := range thisStockIn {
				items := item.(map[string]interface{})

				if items["drug_id"] == nil || reflect.TypeOf(items["drug_id"]).String() != "float64" {
					utils.ErrorLog("drug_id")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				drug_id := int64(items["drug_id"].(float64))

				if items["warehousing_count"] == nil || reflect.TypeOf(items["warehousing_count"]).String() != "string" {
					utils.ErrorLog("warehousing_count")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}

				warehousing_count, _ := strconv.ParseInt(items["warehousing_count"].(string), 10, 64)

				if items["price"] == nil || reflect.TypeOf(items["price"]).String() != "string" {
					utils.ErrorLog("price")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				price, _ := strconv.ParseFloat(items["price"].(string), 64)
				total := float64(warehousing_count) * price

				if items["last_price"] == nil || reflect.TypeOf(items["last_price"]).String() != "string" {
					utils.ErrorLog("last_price")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				last_price, _ := strconv.ParseFloat(items["last_price"].(string), 64)

				retail_price_total := float64(warehousing_count) * last_price

				var productDates int64
				var expiryDates int64

				if items["expiry_date"] == nil || reflect.TypeOf(items["expiry_date"]).String() != "string" {
					expiryDates = 0
				} else {
					if len(items["expiry_date"].(string)) == 0 {
						expiryDates = 0

					} else {
						expiryDate, _ := items["expiry_date"].(string)
						expiry_date, _ := utils.ParseTimeStringToTime("2006-01-02", expiryDate)
						expiryDates = expiry_date.Unix()

					}
				}

				if items["product_date"] == nil || reflect.TypeOf(items["product_date"]).String() != "string" {
					productDates = 0
				} else {
					if len(items["product_date"].(string)) == 0 {
						productDates = 0

					} else {
						productDate, _ := items["product_date"].(string)
						product_date, _ := utils.ParseTimeStringToTime("2006-01-02", productDate)
						productDates = product_date.Unix()
					}

				}

				number, _ := items["number"].(string)

				batch_number, _ := items["batch_number"].(string)

				max_unit, _ := items["max_unit"].(string)

				min_unit, _ := items["min_unit"].(string)

				var remark string
				if items["remark"] == nil || reflect.TypeOf(items["remark"]).String() != "string" {
					remark = ""
				} else {
					remark = items["remark"].(string)
				}

				if items["id"] == nil || reflect.TypeOf(items["id"]).String() != "float64" {
					utils.ErrorLog("id")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				id := int64(items["id"].(float64))

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

				dealer := int64(items["dealer"].(float64))
				if id == 0 {
					warehouseInfo := &models.DrugWarehouseInfo{
						WarehousingOrder: warehouse.WarehousingOrder,
						WarehousingId:    warehouse.ID,
						DrugId:           drug_id,
						Number:           number,
						ProductDate:      productDates,
						ExpiryDate:       expiryDates,
						WarehousingCount: warehousing_count,
						Price:            price,
						TotalPrice:       total,
						Status:           1,
						Ctime:            ctime,
						Remark:           remark,
						OrgId:            adminUserInfo.CurrentOrgId,
						Type:             types,
						Manufacturer:     manufacturer,
						Dealer:           dealer,
						RetailPrice:      last_price,
						RetailTotalPrice: retail_price_total,
						BatchNumber:      batch_number,
						MaxUnit:          max_unit,
						MinUnit:          min_unit,
						StockMaxNumber:   warehousing_count,
					}
					warehousingInfo = append(warehousingInfo, warehouseInfo)

				} else {
					warehouseInfo := &models.DrugWarehouseInfo{
						ID:               id,
						WarehousingOrder: warehouse.WarehousingOrder,
						WarehousingId:    warehouse.ID,
						DrugId:           drug_id,
						Number:           number,
						ProductDate:      productDates,
						ExpiryDate:       expiryDates,
						WarehousingCount: warehousing_count,
						Price:            price,
						TotalPrice:       total,
						Status:           1,
						Ctime:            ctime,
						Remark:           remark,
						OrgId:            adminUserInfo.CurrentOrgId,
						Type:             types,
						Manufacturer:     manufacturer,
						Dealer:           dealer,
						RetailPrice:      last_price,
						RetailTotalPrice: retail_price_total,
						MaxUnit:          max_unit,
						MinUnit:          min_unit,
						BatchNumber:      batch_number,
					}
					upDateWarehousingInfo = append(upDateWarehousingInfo, warehouseInfo)

					drugflow := &models.DrugFlow{
						WarehousingOrder: warehousing.WarehousingOrder,
						WarehousingId:    id,
						DrugId:           drug_id,
						Number:           number,
						ProductDate:      productDates,
						ExpireDate:       expiryDates,
						Count:            warehousing_count,
						Price:            last_price,
						Status:           1,
						Ctime:            ctime,
						UserOrgId:        adminUserInfo.CurrentOrgId,
						Manufacturer:     manufacturer,
						Dealer:           dealer,
						BatchNumber:      batch_number,
						MaxUnit:          max_unit,
						MinUnit:          min_unit,
						ConsumableType:   1,
						IsEdit:           1,
						Creator:          adminUserInfo.AdminUser.Id,
						IsSys:            0,
					}

					drugFlow = append(drugFlow, drugflow)
				}
			}
		}
	}
	var errs error
	if len(warehousingInfo) > 0 {

		errs = service.CreateDrugWarehousingInfo(warehousingInfo)
		if errs == nil {
			service.CreateDrugFlow(drugFlow)
			//更改库存
			service.UpdateDrugInfo(warehousingInfo)

		}

	}

	if len(upDateWarehousingInfo) > 0 {
		var total int64
		var minNumber float64
		var allTotal int64
		for _, item := range upDateWarehousingInfo {
			//查询修改的记录
			orderInfo, _ := service.GetDrugWarehouseOrderOne(id, item.DrugId)

			info, _ := service.FindeDrugInfo(item.DrugId)

			total = orderInfo.StockMaxNumber * info.MinNumber

			allTotal = item.WarehousingCount*info.MinNumber - total

			str := strconv.FormatInt(allTotal, 10)
			minFloat, _ := strconv.ParseFloat(str, 64)

			minNumber = info.Total + minFloat

			lib := models.BaseDrugLib{
				Total: minNumber,
			}
			service.UpdateBaseDrug(&lib, item.DrugId)
			warehouseInfo, _ := service.FindeLastWarehouseInfo(item.ID)
			fmt.Println("hhhhh23hh32h232332323223", warehouseInfo)
			var total int64
			//比较大小(加)
			if item.WarehousingCount > warehouseInfo.WarehousingCount {
				total = item.WarehousingCount - warehouseInfo.WarehousingCount
			}
			item.StockMaxNumber = warehouseInfo.StockMaxNumber + total
			if item.WarehousingCount < warehouseInfo.WarehousingCount {
				total = warehouseInfo.WarehousingCount - item.WarehousingCount
			}
			item.StockMaxNumber = warehouseInfo.StockMaxNumber - total
			if item.WarehousingCount == warehouseInfo.StockMaxNumber {

				item.StockMaxNumber = item.WarehousingCount
			}
			errs = service.UpDateDrugWarehousingInfo(item)

		}
	}

	if len(drugFlow) > 0 {
		for _, item := range drugFlow {
			flow := models.DrugFlow{
				Count: item.Count,
			}
			parseDateErr := service.UpdateDrugFlow(flow, item.DrugId, item.WarehousingId)
			fmt.Println(parseDateErr)
		}
	}

	if errs != nil {
		utils.ErrorLog(errs.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateStockInFail)
		return
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"msg": "编辑成功",
	})

}
func (c *StockDrugApiController) DeleteDrugWarehouse() {
	ids := c.GetString("ids")

	if len(ids) == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	idArray := strings.Split(ids, ",")
	err := service.DeleteDrugWarehouse(idArray)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDeleteFail)
	} else {
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "删除成功",
		})
	}
}
func (c *StockDrugApiController) DeleteDrugWarehouseInfo() {
	id, _ := c.GetInt64("id", 0)

	if id == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	err := service.UpDateDrugWarehouseStatus(id)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDeleteFail)
	} else {
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "删除成功",
		})
	}

}

func (c *StockDrugApiController) CreateDrugSalesReturn() {
	dealer_id, _ := c.GetInt64("dealer_id", 0)
	manufacturer_id, _ := c.GetInt64("manufacturer_id", 0)
	sales_return_time := c.GetString("time")
	types, _ := c.GetInt64("type", 0)

	salesReturnDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", sales_return_time)
	if parseDateErr != nil {
		c.ErrorLog("日期(%v)解析错误：%v", salesReturnDate, parseDateErr)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	adminUserInfo := c.GetAdminUserInfo()
	operation_time := time.Now().Unix()
	creater := adminUserInfo.AdminUser.Id
	ctime := time.Now().Unix()

	timeStr := time.Now().Format("2006-01-02")
	timeArr := strings.Split(timeStr, "-")
	total, _ := service.FindAllSalesReturnTotal(adminUserInfo.CurrentOrgId)
	total = total + 1
	orderNumber := "YPTHD" + strconv.FormatInt(adminUserInfo.CurrentOrgId, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000" + strconv.FormatInt(total, 10)

	salesReturn := models.DrugSalesReturn{
		OrderNumber:  orderNumber,
		OperaTime:    operation_time,
		OrgId:        adminUserInfo.CurrentOrgId,
		Creater:      creater,
		Ctime:        ctime,
		Status:       1,
		ReturnTime:   salesReturnDate.Unix(),
		Dealer:       dealer_id,
		Manufacturer: manufacturer_id,
		Type:         types,
	}

	service.AddSigleDrugSalesReturn(&salesReturn)

	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	var salesReturnInfos []*models.DrugSalesReturnInfo

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

				if items["drug_id"] == nil || reflect.TypeOf(items["drug_id"]).String() != "float64" {
					utils.ErrorLog("drug_id")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				drug_id := int64(items["drug_id"].(float64))

				return_count, _ := items["return_count"].(string)
				if len(return_count) == 0 {
					utils.ErrorLog("len(return_count) == 0")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)

					return
				}
				count, _ := strconv.ParseInt(return_count, 10, 64)

				if items["price"] == nil || reflect.TypeOf(items["price"]).String() != "string" {
					utils.ErrorLog("price")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				price, _ := strconv.ParseFloat(items["price"].(string), 64)
				total := float64(count) * price

				if items["retail_price"] == nil || reflect.TypeOf(items["retail_price"]).String() != "string" {
					utils.ErrorLog("retail_price")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				retail_price, _ := strconv.ParseFloat(items["retail_price"].(string), 64)
				retail_price_total := float64(count) * retail_price

				salesReturnInfo := &models.DrugSalesReturnInfo{
					OrderNumber:      salesReturn.OrderNumber,
					SalesReturnId:    salesReturn.ID,
					DrugId:           drug_id,
					Count:            count,
					Price:            price,
					Total:            total,
					Status:           1,
					Ctime:            ctime,
					OrgId:            adminUserInfo.CurrentOrgId,
					Type:             types,
					Manufacturer:     manufacturer_id,
					Dealer:           dealer_id,
					RetailPrice:      retail_price,
					RetailTotalPrice: retail_price_total,
				}

				salesReturnInfos = append(salesReturnInfos, salesReturnInfo)

			}
		}
	}
	errs := service.CreateDrugSalesReturnInfo(salesReturnInfos)
	if errs != nil {
		utils.ErrorLog(errs.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateReturnFail)
		return
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"msg": "退货成功",
	})

}
func (c *StockDrugApiController) GetDrugSalesReturnList() {
	page, _ := c.GetInt64("page", -1)
	limit, _ := c.GetInt64("limit", -1)
	start_time := c.GetString("start_time")
	end_time := c.GetString("end_time")
	types, _ := c.GetInt64("type", 0)
	keywords := c.GetString("keywords")

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	var startTime int64
	if len(start_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	var endTime int64
	if len(end_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}

	adminUserInfo := c.GetAdminUserInfo()
	returnList, total, err := service.FindAllDrugReturnList(adminUserInfo.CurrentOrgId, page, limit, startTime, endTime, types, keywords)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"list":  returnList,
			"total": total,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}

}
func (this *StockDrugApiController) DeleteDrugSalesReturn() {
	ids := this.GetString("ids")

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

	idArray := strings.Split(ids, ",")
	err := service.DeleteDrugSalesReturn(idArray)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDeleteFail)
	} else {
		this.ServeSuccessJSON(map[string]interface{}{
			"msg": "删除成功",
		})
	}
}
func (this *StockDrugApiController) DeleteDrugSalesReturnInfo() {
	id, _ := this.GetInt64("id", 0)
	fmt.Println(id)
	if id == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	err := service.UpDateDrugSaleReturnStatus(id)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDeleteFail)
	} else {
		this.ServeSuccessJSON(map[string]interface{}{
			"msg": "删除成功",
		})
	}

}
func (this *StockDrugApiController) GetDrugSalesReturnInfoList() {
	id, _ := this.GetInt64("id", 0)
	adminUserInfo := this.GetAdminUserInfo()

	list, _ := service.FindAllDrugSalesReturnInfoById(id, adminUserInfo.CurrentOrgId)
	salesReturn, _ := service.FindAllDrugSalesReturnById(id, adminUserInfo.CurrentOrgId)

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

}
func (c *StockDrugApiController) EditDrugReturnInfo() {
	return_time := c.GetString("return_time")
	id, _ := c.GetInt64("id", 0)
	types, _ := c.GetInt64("type", 0)
	manufacturer_id, _ := c.GetInt64("manufacturer_id", 0)
	dealer_id, _ := c.GetInt64("dealer_id", 0)

	if id == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	ctime := time.Now().Unix()
	mtime := time.Now().Unix()
	adminUserInfo := c.GetAdminUserInfo()

	returnDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", return_time)
	if parseDateErr != nil {
		c.ErrorLog("日期(%v)解析错误：%v", returnDate, parseDateErr)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	salesReturns, _ := service.FindDrugSalesReturnById(id)

	sales := models.DrugSalesReturn{
		ID:           salesReturns.ID,
		Mtime:        mtime,
		ReturnTime:   returnDate.Unix(),
		Manufacturer: manufacturer_id,
		Dealer:       dealer_id,
	}

	service.EditDrugSaleReturn(sales)

	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	var returnInfos []*models.DrugSalesReturnInfo
	var upDateReturnInfos []*models.DrugSalesReturnInfo

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

				if items["drug_id"] == nil || reflect.TypeOf(items["drug_id"]).String() != "float64" {
					utils.ErrorLog("drug_id")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				drug_id := int64(items["drug_id"].(float64))

				if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
					utils.ErrorLog("count")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}

				count, _ := strconv.ParseInt(items["count"].(string), 10, 64)

				if items["id"] == nil || reflect.TypeOf(items["id"]).String() != "float64" {
					utils.ErrorLog("id")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				id := int64(items["id"].(float64))

				if items["price"] == nil || reflect.TypeOf(items["price"]).String() != "string" {
					utils.ErrorLog("price")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}

				price, _ := strconv.ParseFloat(items["price"].(string), 64)
				total := float64(count) * price

				if items["retail_price"] == nil || reflect.TypeOf(items["retail_price"]).String() != "string" {
					utils.ErrorLog("retail_price")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				retail_price, _ := strconv.ParseFloat(items["retail_price"].(string), 64)
				retail_price_total := float64(count) * retail_price

				if id == 0 {
					returnInfo := &models.DrugSalesReturnInfo{
						DrugId:           drug_id,
						Count:            count,
						Status:           1,
						Ctime:            ctime,
						OrgId:            adminUserInfo.CurrentOrgId,
						OrderNumber:      sales.OrderNumber,
						SalesReturnId:    sales.ID,
						Mtime:            time.Now().Unix(),
						Type:             types,
						Manufacturer:     manufacturer_id,
						Dealer:           dealer_id,
						RetailPrice:      retail_price,
						RetailTotalPrice: retail_price_total,
						Total:            total,
						Price:            price,
					}
					returnInfos = append(returnInfos, returnInfo)

				} else {
					returnInfo := &models.DrugSalesReturnInfo{
						ID:               id,
						DrugId:           drug_id,
						Count:            count,
						Status:           1,
						Ctime:            ctime,
						OrgId:            adminUserInfo.CurrentOrgId,
						OrderNumber:      sales.OrderNumber,
						SalesReturnId:    sales.ID,
						Mtime:            time.Now().Unix(),
						Type:             types,
						Manufacturer:     manufacturer_id,
						Dealer:           dealer_id,
						RetailPrice:      retail_price,
						RetailTotalPrice: retail_price_total,
						Total:            total,
						Price:            price,
					}
					upDateReturnInfos = append(upDateReturnInfos, returnInfo)
				}
			}
		}
	}
	var errs error
	if len(returnInfos) > 0 {
		errs = service.CreateDrugSalesReturnInfo(returnInfos)
	}

	if len(upDateReturnInfos) > 0 {
		for _, item := range upDateReturnInfos {
			errs = service.UpDateDrugSalesReturnInfo(item)
		}
	}

	if errs != nil {
		utils.ErrorLog(errs.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateReturnFail)
		return
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"msg": "编辑成功",
	})

}

func (c *StockDrugApiController) CreateDrugWarehouseOut() {

	types, _ := c.GetInt64("type", 0)

	ctime := time.Now().Unix()
	adminUserInfo := c.GetAdminUserInfo()

	warehousing_out_time := c.GetString("warehousing_out_time")
	warehousingOutDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", warehousing_out_time)
	if parseDateErr != nil {
		c.ErrorLog("日期(%v)解析错误：%v", warehousingOutDate, parseDateErr)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	timeStr := time.Now().Format("2006-01-02")
	timeArr := strings.Split(timeStr, "-")
	total, _ := service.FindAllDrugWarehouseOut(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 = "YPCKD" + strconv.FormatInt(number, 10)
	operation_time := time.Now().Unix()
	creater := adminUserInfo.AdminUser.Id

	warehouseOut := models.DrugWarehouseOut{
		WarehouseOutOrderNumber: warehousing_out_order,
		OperationTime:           operation_time,
		OrgId:                   adminUserInfo.CurrentOrgId,
		Creater:                 creater,
		Ctime:                   ctime,
		Status:                  1,
		WarehouseOutTime:        warehousingOutDate.Unix(),
		Type:                    types,
	}

	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	var warehousingOutInfo []*models.DrugWarehouseOutInfo

	var drugFlow []*models.DrugFlow

	if dataBody["stockOut"] != nil && reflect.TypeOf(dataBody["stockOut"]).String() == "[]interface {}" {
		thisStockIn, _ := dataBody["stockOut"].([]interface{})

		if len(thisStockIn) > 0 {
			for _, item := range thisStockIn {

				items := item.(map[string]interface{})

				if items["drug_id"] == nil || reflect.TypeOf(items["drug_id"]).String() != "float64" {
					utils.ErrorLog("drug_id")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				drug_id := int64(items["drug_id"].(float64))

				if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
					utils.ErrorLog("count")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}

				if items["price"] == nil || reflect.TypeOf(items["price"]).String() != "string" {
					utils.ErrorLog("price")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				price, _ := strconv.ParseFloat(items["price"].(string), 64)

				//if items["last_price"] == nil || reflect.TypeOf(items["last_price"]).String() != "string" {
				//	utils.ErrorLog("last_price")
				//	c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
				//	return
				//}
				//last_price, _ := strconv.ParseFloat(items["last_price"].(string), 64)
				//fmt.Println(last_price)
				count, _ := strconv.ParseInt(items["count"].(string), 10, 64)

				total := float64(count) * price
				retail_price_total := float64(count) * price
				remark := items["remark"].(string)
				max_unit := items["max_unit"].(string)
				dealer := int64(items["dealer"].(float64))

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

				number := items["number"].(string)
				batch_number := items["batch_number"].(string)

				warehouse_info_id := int64(items["warehouse_info_id"].(float64))
				var productDates int64
				var expiryDates int64
				if items["expiry_date"] == nil || reflect.TypeOf(items["expiry_date"]).String() != "string" {
					expiryDates = 0
				} else {
					if len(items["expiry_date"].(string)) == 0 {
						expiryDates = 0

					} else {
						expiryDate, _ := items["expiry_date"].(string)
						expiry_date, _ := utils.ParseTimeStringToTime("2006-01-02", expiryDate)
						expiryDates = expiry_date.Unix()

					}

				}
				if items["product_date"] == nil || reflect.TypeOf(items["product_date"]).String() != "string" {
					productDates = 0
				} else {
					if len(items["product_date"].(string)) == 0 {
						productDates = 0

					} else {
						productDate, _ := items["product_date"].(string)
						product_date, _ := utils.ParseTimeStringToTime("2006-01-02", productDate)
						productDates = product_date.Unix()
					}

				}

				warehouseOutInfo := &models.DrugWarehouseOutInfo{
					WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
					WarehouseOutId:          warehouseOut.ID,
					DrugId:                  drug_id,
					Count:                   count,
					Price:                   price,
					TotalPrice:              total,
					Status:                  1,
					Ctime:                   ctime,
					Remark:                  remark,
					OrgId:                   adminUserInfo.CurrentOrgId,
					Type:                    types,
					Manufacturer:            manufacturer,
					Dealer:                  dealer,
					RetailPrice:             price,
					RetailTotalPrice:        retail_price_total,
					CountUnit:               max_unit,
					ExpiryDate:              expiryDates,
					ProductDate:             productDates,
					Number:                  number,
					BatchNumber:             batch_number,
					IsSys:                   0,
					WarehouseInfoId:         warehouse_info_id,
				}
				warehousingOutInfo = append(warehousingOutInfo, warehouseOutInfo)

				drugflow := &models.DrugFlow{
					WarehouseOutId:          warehouseOut.ID,
					WarehouseOutOrderNumber: warehousing_out_order,
					DrugId:                  drug_id,
					Number:                  number,
					ProductDate:             productDates,
					ExpireDate:              expiryDates,
					Count:                   count,
					Price:                   price,
					Status:                  1,
					Ctime:                   ctime,
					UserOrgId:               adminUserInfo.CurrentOrgId,
					Manufacturer:            manufacturer,
					Dealer:                  dealer,
					BatchNumber:             batch_number,
					MaxUnit:                 max_unit,
					ConsumableType:          2,
					IsEdit:                  1,
					Creator:                 adminUserInfo.AdminUser.Id,
					IsSys:                   0,
				}
				drugFlow = append(drugFlow, drugflow)
			}
		}
	}
	var total_count int64
	var prescribing_number_total int64
	//调用出库逻辑
	for _, item := range warehousingOutInfo {
		//获取药品库存
		info, _ := service.GetDrugTotalCountOne(item.DrugId, item.OrgId, item.WarehouseInfoId)
		//查询改药品信息
		medical, _ := service.GetBaseDrugMedical(item.DrugId)
		total_count = info.StockMaxNumber*medical.MinNumber + info.StockMinNumber
		//for _, it := range info{
		//  if medical.MaxUnit == it.MaxUnit{
		//    it.Count = it.StockMaxNumber * medical.MinNumber
		//  }
		//  if medical.MinUnit == it.MinUnit{
		//    it.Count = it.StockMinNumber
		//  }
		//  total_count += it.Count
		//}
		fmt.Println("总库存23232323232232332232332223", total_count)
		//判断单位是否相等
		if medical.MaxUnit == item.CountUnit {
			//转化为最小单位
			prescribing_number_total = item.Count * medical.MinNumber
		}
		if medical.MinUnit == item.CountUnit {
			prescribing_number_total = item.Count
		}

		fmt.Println("数量一", prescribing_number_total)
		fmt.Println("数量二", total_count)
		//判断单位
		if total_count == 0 {
			goodObj, _ := service.GetDrugByGoodId(item.DrugId)
			c.ServeSuccessJSON(map[string]interface{}{
				"msg":        "1",
				"drug_name":  goodObj.DrugName,
				"dose":       goodObj.Dose,
				"dose_unit":  goodObj.DoseUnit,
				"min_number": goodObj.MinNumber,
				"min_unit":   goodObj.MinUnit,
				"max_unit":   goodObj.MaxUnit,
			})
			return
		}
		if prescribing_number_total > total_count {

			goodObj, _ := service.GetDrugByGoodId(item.DrugId)
			c.ServeSuccessJSON(map[string]interface{}{
				"msg":        "1",
				"drug_name":  goodObj.DrugName,
				"dose":       goodObj.Dose,
				"dose_unit":  goodObj.DoseUnit,
				"min_number": goodObj.MinNumber,
				"min_unit":   goodObj.MinUnit,
				"max_unit":   goodObj.MaxUnit,
			})
			return
		} else {
			service.AddSigleDrugWarehouseOut(&warehouseOut)
			service.CreateDrugFlow(drugFlow)
			// 出库流程
			// 1.查询改药品在药品库的规格信息，并将处方里的规格进行换算（尽量将拆零单位转换成包装单位）
			drup, _ := service.FindBaseDrugLibRecord(item.OrgId, item.DrugId)
			if drup.ID > 0 {
				prescribingNumber := item.Count
				service.AutoDrugDeliverInfo(item.OrgId, prescribingNumber, &warehouseOut, &drup, item)
			}
		}

	}

	c.ServeSuccessJSON(map[string]interface{}{
		"msg":        "2",
		"drug_name":  "",
		"dose":       "",
		"dose_unit":  "",
		"min_number": "",
		"min_unit":   "",
		"max_unit":   "",
	})

}
func (c *StockDrugApiController) GetDrugWarehouseOutList() {
	page, _ := c.GetInt64("page", -1)
	limit, _ := c.GetInt64("limit", -1)
	start_time := c.GetString("start_time")
	end_time := c.GetString("end_time")
	types, _ := c.GetInt64("type", 0)
	keywords := c.GetString("keywords")

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	var startTime int64
	if len(start_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	var endTime int64
	if len(end_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}

	adminUserInfo := c.GetAdminUserInfo()

	var ids []int64
	var goodids []int64
	if len(keywords) > 0 {
		//查询商品名称
		list, _ := service.GetDrugNameByKeyword(keywords, adminUserInfo.CurrentOrgId)
		for _, item := range list {
			goodids = append(goodids, item.ID)
		}

		if len(goodids) > 0 {
			//出库详情但里面查询
			info, _ := service.GetDrugWarehouseOrderDetail(goodids, adminUserInfo.CurrentOrgId, startTime, endTime)
			for _, it := range info {
				ids = append(ids, it.WarehouseOutId)
			}
		}

	}

	warehouseOutList, total, err := service.FindAllDrugWarehouseOutListOne(adminUserInfo.CurrentOrgId, page, limit, startTime, endTime, types, keywords, ids)
	fmt.Println(err)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"list":  warehouseOutList,
			"total": total,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}
func (c *StockDrugApiController) DeleteDrugWarehouseOut() {
	ids := c.GetString("ids")

	if len(ids) == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	idArray := strings.Split(ids, ",")
	err := service.DeleteDrugWarehouseOut(idArray)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDeleteFail)
	} else {
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "删除成功",
		})
	}
}
func (this *StockDrugApiController) DeleteDrugWarehouseOutInfo() {
	id, _ := this.GetInt64("id", 0)
	fmt.Println(id)
	if id == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	err := service.UpDateDrugWarehouseOutStatus(id)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDeleteFail)
	} else {
		this.ServeSuccessJSON(map[string]interface{}{
			"msg": "删除成功",
		})
	}

}
func (c *StockDrugApiController) GetDrugWarehouseOutInfoList() {
	id, _ := c.GetInt64("id", 0)
	adminInfo := c.GetAdminUserInfo()
	warehouseOutInfo, _ := service.FindDrugWarehouseOutInfoById(id, adminInfo.CurrentOrgId)
	warehouseOut, _ := service.FindDrugWareHouseOutById(id, adminInfo.CurrentOrgId)
	manulist, _ := service.GetAllManufacturerList(adminInfo.CurrentOrgId)
	dealerList, _ := service.GetAllDealerList(adminInfo.CurrentOrgId)
	c.ServeSuccessJSON(map[string]interface{}{
		"list":       warehouseOutInfo,
		"info":       warehouseOut,
		"manulist":   manulist,
		"dealerList": dealerList,
	})

}
func (c *StockDrugApiController) EditDrugWarehouseOut() {
	warehouse_out_time := c.GetString("warehouse_out_time")
	id, _ := c.GetInt64("id", 0)
	types, _ := c.GetInt64("type", 0)

	if id == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	ctime := time.Now().Unix()
	mtime := time.Now().Unix()
	adminUserInfo := c.GetAdminUserInfo()

	warehouseOutDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", warehouse_out_time)
	if parseDateErr != nil {
		c.ErrorLog("日期(%v)解析错误：%v", warehouseOutDate, parseDateErr)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	warehouseOut, _ := service.FindDrugWareHouseOutById(id, adminUserInfo.CurrentOrgId)

	tempWarehouseOut := models.DrugWarehouseOut{
		ID:               warehouseOut.ID,
		Mtime:            mtime,
		WarehouseOutTime: warehouseOutDate.Unix(),
	}

	service.EditDrugWarehouseOut(tempWarehouseOut)

	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	var warehousingOutInfo []*models.DrugWarehouseOutInfo
	var upDateWarehouseOutInfos []*models.DrugWarehouseOutInfo

	var drugFlow []*models.DrugFlow
	if dataBody["stockOut"] != nil && reflect.TypeOf(dataBody["stockOut"]).String() == "[]interface {}" {
		thisStockOut, _ := dataBody["stockOut"].([]interface{})
		if len(thisStockOut) > 0 {
			for _, item := range thisStockOut {
				items := item.(map[string]interface{})

				if items["drug_id"] == nil || reflect.TypeOf(items["drug_id"]).String() != "float64" {
					utils.ErrorLog("drug_id")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				drug_id := int64(items["drug_id"].(float64))

				if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
					utils.ErrorLog("count")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}

				count, _ := strconv.ParseInt(items["count"].(string), 10, 64)

				count_unit, _ := items["count_unit"].(string)

				if items["price"] == nil || reflect.TypeOf(items["price"]).String() != "string" {
					utils.ErrorLog("price")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				price, _ := strconv.ParseFloat(items["price"].(string), 64)

				if items["retail_price"] == nil || reflect.TypeOf(items["retail_price"]).String() != "string" {
					utils.ErrorLog("retail_price")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				retail_price, _ := strconv.ParseFloat(items["retail_price"].(string), 64)

				total := float64(count) * price
				retail_price_total := float64(count) * retail_price

				remark := items["remark"].(string)

				if items["id"] == nil || reflect.TypeOf(items["id"]).String() != "float64" {
					utils.ErrorLog("id")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				id := int64(items["id"].(float64))

				dealer := int64(items["dealer"].(float64))
				manufacturer := int64(items["manufacturer"].(float64))

				batch_number := items["batch_number"].(string)
				number := items["number"].(string)
				max_unit := items["count_unit"].(string)
				warehouse_info_id := int64(items["warehouse_info_id"].(float64))
				var productDates int64
				var expiryDates int64
				if items["expiry_date"] == nil || reflect.TypeOf(items["expiry_date"]).String() != "string" {
					expiryDates = 0
				} else {
					if len(items["expiry_date"].(string)) == 0 {
						expiryDates = 0

					} else {
						expiryDate, _ := items["expiry_date"].(string)
						expiry_date, _ := utils.ParseTimeStringToTime("2006-01-02", expiryDate)
						expiryDates = expiry_date.Unix()

					}

				}
				if items["product_date"] == nil || reflect.TypeOf(items["product_date"]).String() != "string" {
					productDates = 0
				} else {
					if len(items["product_date"].(string)) == 0 {
						productDates = 0

					} else {
						productDate, _ := items["product_date"].(string)
						product_date, _ := utils.ParseTimeStringToTime("2006-01-02", productDate)
						productDates = product_date.Unix()
					}

				}

				if id == 0 {
					warehouseOutInfo := &models.DrugWarehouseOutInfo{
						WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
						WarehouseOutId:          warehouseOut.ID,
						DrugId:                  drug_id,
						Count:                   count,
						Price:                   price,
						TotalPrice:              total,
						Status:                  1,
						Ctime:                   ctime,
						Remark:                  remark,
						OrgId:                   adminUserInfo.CurrentOrgId,
						Type:                    types,
						Manufacturer:            manufacturer,
						Dealer:                  dealer,
						IsSys:                   0,
						SysRecordTime:           0,
						RetailPrice:             retail_price,
						RetailTotalPrice:        retail_price_total,
						BatchNumber:             batch_number,
						Number:                  number,
						ProductDate:             productDates,
						ExpiryDate:              expiryDates,
						CountUnit:               count_unit,
						WarehouseInfoId:         warehouse_info_id,
					}
					warehousingOutInfo = append(warehousingOutInfo, warehouseOutInfo)

					drugflow := &models.DrugFlow{
						WarehousingOrder:        "",
						WarehousingId:           0,
						DrugId:                  drug_id,
						Number:                  number,
						ProductDate:             productDates,
						ExpireDate:              expiryDates,
						Count:                   count,
						Price:                   price,
						Status:                  1,
						Ctime:                   ctime,
						UserOrgId:               adminUserInfo.CurrentOrgId,
						Manufacturer:            manufacturer,
						Dealer:                  dealer,
						BatchNumber:             batch_number,
						MaxUnit:                 max_unit,
						ConsumableType:          1,
						IsEdit:                  1,
						Creator:                 adminUserInfo.AdminUser.Id,
						IsSys:                   0,
						WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
						WarehouseOutId:          id,
					}

					drugFlow = append(drugFlow, drugflow)

				} else {
					if items["is_sys"] == nil || reflect.TypeOf(items["is_sys"]).String() != "float64" {
						utils.ErrorLog("is_sys")
						c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
						return
					}
					is_sys := int64(items["is_sys"].(float64))

					if items["sys_record_time"] == nil || reflect.TypeOf(items["sys_record_time"]).String() != "float64" {
						utils.ErrorLog("sys_record_time")
						c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
						return
					}
					sys_record_time := int64(items["sys_record_time"].(float64))

					warehouseOutInfo := &models.DrugWarehouseOutInfo{
						ID:                      id,
						WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
						WarehouseOutId:          warehouseOut.ID,
						DrugId:                  drug_id,
						Count:                   count,
						Price:                   price,
						TotalPrice:              total,
						Status:                  1,
						Ctime:                   ctime,
						Remark:                  remark,
						OrgId:                   adminUserInfo.CurrentOrgId,
						Mtime:                   time.Now().Unix(),
						Type:                    types,
						Manufacturer:            manufacturer,
						Dealer:                  dealer,
						IsSys:                   is_sys,
						SysRecordTime:           sys_record_time,
						RetailPrice:             retail_price,
						RetailTotalPrice:        retail_price_total,
						BatchNumber:             batch_number,
						Number:                  number,
						ProductDate:             productDates,
						ExpiryDate:              expiryDates,
						CountUnit:               count_unit,
						WarehouseInfoId:         warehouse_info_id,
					}
					upDateWarehouseOutInfos = append(upDateWarehouseOutInfos, warehouseOutInfo)

					drugflow := &models.DrugFlow{
						WarehousingOrder:        "",
						WarehousingId:           0,
						DrugId:                  drug_id,
						Number:                  number,
						ProductDate:             productDates,
						ExpireDate:              expiryDates,
						Count:                   count,
						Price:                   price,
						Status:                  1,
						Ctime:                   ctime,
						UserOrgId:               adminUserInfo.CurrentOrgId,
						Manufacturer:            manufacturer,
						Dealer:                  dealer,
						BatchNumber:             batch_number,
						MaxUnit:                 max_unit,
						ConsumableType:          1,
						IsEdit:                  1,
						Creator:                 adminUserInfo.AdminUser.Id,
						IsSys:                   0,
						WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
						WarehouseOutId:          warehouseOut.ID,
					}

					drugFlow = append(drugFlow, drugflow)
				}
			}
		}
	}
	var errs error
	if len(warehousingOutInfo) > 0 {

		var total_count int64
		var prescribing_number_total int64
		//调用出库逻辑
		for _, item := range warehousingOutInfo {
			//获取药品库存
			info, _ := service.GetDrugTotalCount(item.DrugId, item.OrgId)
			//查询改药品信息
			medical, _ := service.GetBaseDrugMedical(item.DrugId)
			//判断单位是否相等
			if medical.MaxUnit == item.CountUnit {
				//转化为最小单位
				total_count = info.Count * medical.MinNumber
				prescribing_number_total = item.Count * medical.MinNumber
			}
			if medical.MinUnit == item.CountUnit {
				total_count = info.Count
				prescribing_number_total = item.Count
			}

			fmt.Println("数量一", prescribing_number_total)
			fmt.Println("数量二", total_count)
			//判断单位
			if total_count == 0 {
				goodObj, _ := service.GetDrugByGoodId(item.DrugId)
				c.ServeSuccessJSON(map[string]interface{}{
					"msg":        "1",
					"drug_name":  goodObj.DrugName,
					"dose":       goodObj.Dose,
					"dose_unit":  goodObj.DoseUnit,
					"min_number": goodObj.MinNumber,
					"min_unit":   goodObj.MinUnit,
					"max_unit":   goodObj.MaxUnit,
				})
				return
			}
			if prescribing_number_total > total_count {

				goodObj, _ := service.GetDrugByGoodId(item.DrugId)
				c.ServeSuccessJSON(map[string]interface{}{
					"msg":        "1",
					"drug_name":  goodObj.DrugName,
					"dose":       goodObj.Dose,
					"dose_unit":  goodObj.DoseUnit,
					"min_number": goodObj.MinNumber,
					"min_unit":   goodObj.MinUnit,
					"max_unit":   goodObj.MaxUnit,
				})
				return
			} else {
				errs = service.CreateDrugWarehousingOutInfo(warehousingOutInfo)
				service.CreateDrugFlow(drugFlow)
				// 出库流程
				// 1.查询改药品在药品库的规格信息，并将处方里的规格进行换算（尽量将拆零单位转换成包装单位）
				drup, _ := service.FindBaseDrugLibRecord(item.OrgId, item.DrugId)
				if drup.ID > 0 {
					prescribingNumber := item.Count
					service.AutoDrugDeliverInfo(item.OrgId, prescribingNumber, &tempWarehouseOut, &drup, item)
				}
			}

		}
	}

	if len(upDateWarehouseOutInfos) > 0 {
		for _, item := range upDateWarehouseOutInfos {
			//获取药品库存
			info, _ := service.GetDrugTotalCount(item.DrugId, item.OrgId)
			//查询改药品信息
			medical, _ := service.GetBaseDrugMedical(item.DrugId)
			//查询最后一次出库记录
			outInfo, _ := service.GetLastDrugWarehouseOutInfo(item.DrugId, item.WarehouseOutId, item.OrgId)
			var min_number int64 //最后一次库存
			var max_number int64 //当前库存
			var all_number int64 //总库存
			var cha_number int64 //库存差
			var maxNumber int64
			var minNumber int64

			if medical.MaxUnit == outInfo.CountUnit {
				//转为最小单位
				min_number = outInfo.Count * medical.MinNumber
			}

			if medical.MinUnit == outInfo.CountUnit {
				min_number = outInfo.Count
			}

			fmt.Println("单位1", medical.MaxUnit)
			fmt.Println("单位2", item.CountUnit)
			if medical.MaxUnit == item.CountUnit {
				max_number = item.Count * medical.MinNumber
			}

			if medical.MinUnit == item.CountUnit {
				max_number = item.Count
			}

			all_number = info.Count*medical.MinNumber + info.StockMinNumber
			fmt.Println("总库存223232", all_number)
			fmt.Println("当前库存00000000000000000000000000000000000000000", max_number)
			////比较当前出库数量 和 最后一次出库数量,正常出库
			if max_number <= min_number {
				errs = service.UpDateDrugWarehouseOutInfo(item)
				cha_number = min_number - max_number
				fmt.Println("差库存", cha_number)
				fmt.Println("最后一次库存0000000000000000000000000000000000000000", min_number)
				if item.CountUnit == medical.MaxUnit {
					maxNumber = cha_number / medical.MinNumber
					parseDateErr := service.UpdateWarehouseInfo(maxNumber, item.DrugId, item.OrgId)
					if parseDateErr != nil {
						utils.ErrorLog(errs.Error())
						c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateStockOutFail)
						return
					}

					c.ServeSuccessJSON(map[string]interface{}{
						"msg":        "2",
						"drug_name":  "",
						"dose":       "",
						"dose_unit":  "",
						"min_number": "",
						"min_unit":   "",
						"max_unit":   "",
					})
					minNumber = cha_number % medical.MinNumber
					parseDateErr = service.UpdateWarehouseInfoOne(minNumber, item.DrugId, item.OrgId)
					if parseDateErr != nil {
						utils.ErrorLog(errs.Error())
						c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateStockOutFail)
						return
					}

					c.ServeSuccessJSON(map[string]interface{}{
						"msg":        "2",
						"drug_name":  "",
						"dose":       "",
						"dose_unit":  "",
						"min_number": "",
						"min_unit":   "",
						"max_unit":   "",
					})
				}
				if item.CountUnit == medical.MinUnit {
					parseDateErr := service.UpdateWarehouseInfoOne(cha_number, item.DrugId, item.OrgId)
					if parseDateErr != nil {
						utils.ErrorLog(errs.Error())
						c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateStockOutFail)
						return
					}

					c.ServeSuccessJSON(map[string]interface{}{
						"msg":        "2",
						"drug_name":  "",
						"dose":       "",
						"dose_unit":  "",
						"min_number": "",
						"min_unit":   "",
						"max_unit":   "",
					})
				}

			}

			fmt.Println("当前出库", max_number)
			fmt.Println("最后一次232233", min_number)
			//退库操作
			if max_number > min_number {

				cha_number = min_number - max_number
				//如果总库存大于差,正常出库
				if all_number >= cha_number {

					errs = service.UpDateDrugWarehouseOutInfo(item)
					fmt.Println("232322332233232", item.CountUnit, medical.MaxUnit)
					if item.CountUnit == medical.MaxUnit {
						maxNumber = cha_number / medical.MinNumber
						fmt.Println("maxNumber232323232323232232", maxNumber)
						parseDateErr := service.UpdateWarehouseInfo(maxNumber, item.DrugId, item.OrgId)
						fmt.Println("parseDateErr9999999999999999999999", parseDateErr)
						if parseDateErr != nil {
							utils.ErrorLog(errs.Error())
							c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateStockOutFail)
							return
						}

						c.ServeSuccessJSON(map[string]interface{}{
							"msg":        "2",
							"drug_name":  "",
							"dose":       "",
							"dose_unit":  "",
							"min_number": "",
							"min_unit":   "",
							"max_unit":   "",
						})
						minNumber = cha_number % medical.MinNumber
						parseDateErr = service.UpdateWarehouseInfoOne(minNumber, item.DrugId, item.OrgId)
						if parseDateErr != nil {
							utils.ErrorLog(errs.Error())
							c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateStockOutFail)
							return
						}

						c.ServeSuccessJSON(map[string]interface{}{
							"msg":        "2",
							"drug_name":  "",
							"dose":       "",
							"dose_unit":  "",
							"min_number": "",
							"min_unit":   "",
							"max_unit":   "",
						})
					}
					if item.CountUnit == medical.MinUnit {
						parseDateErr := service.UpdateWarehouseInfoOne(cha_number, item.DrugId, item.OrgId)
						if parseDateErr != nil {
							utils.ErrorLog(errs.Error())
							c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateStockOutFail)
							return
						}

						c.ServeSuccessJSON(map[string]interface{}{
							"msg":        "2",
							"drug_name":  "",
							"dose":       "",
							"dose_unit":  "",
							"min_number": "",
							"min_unit":   "",
							"max_unit":   "",
						})
					}
				}

				if all_number < cha_number {
					goodObj, _ := service.GetDrugByGoodId(item.DrugId)
					c.ServeSuccessJSON(map[string]interface{}{
						"msg":        "1",
						"drug_name":  goodObj.DrugName,
						"dose":       goodObj.Dose,
						"dose_unit":  goodObj.DoseUnit,
						"min_number": goodObj.MinNumber,
						"min_unit":   goodObj.MinUnit,
						"max_unit":   goodObj.MaxUnit,
					})
					return
				}
			}

		}
	}

	if errs != nil {
		utils.ErrorLog(errs.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateStockOutFail)
		return
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"msg":        "2",
		"drug_name":  "",
		"dose":       "",
		"dose_unit":  "",
		"min_number": "",
		"min_unit":   "",
		"max_unit":   "",
	})

}

func (c *StockDrugApiController) CreateDrugCancelStock() {
	dealer_id, _ := c.GetInt64("dealer_id", 0)
	manufacturer_id, _ := c.GetInt64("manufacturer_id", 0)
	cancel_stock_time := c.GetString("time")
	types, _ := c.GetInt64("type", 0)

	cancelStockDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", cancel_stock_time)
	if parseDateErr != nil {
		c.ErrorLog("日期(%v)解析错误：%v", cancelStockDate, parseDateErr)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	fmt.Println("cancelStockDate232323223233223", cancelStockDate.Unix())

	adminUserInfo := c.GetAdminUserInfo()
	operation_time := time.Now().Unix()
	creater := adminUserInfo.AdminUser.Id

	ctime := time.Now().Unix()
	timeStr := time.Now().Format("2006-01-02")
	timeArr := strings.Split(timeStr, "-")
	total, _ := service.FindAllDrugCancelStockTotal(adminUserInfo.CurrentOrgId)
	total = total + 1
	orderNumber := "CKTKD" + strconv.FormatInt(adminUserInfo.CurrentOrgId, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000" + strconv.FormatInt(total, 10)

	cancelStock := models.DrugCancelStock{
		OrderNumber:  orderNumber,
		OperaTime:    operation_time,
		OrgId:        adminUserInfo.CurrentOrgId,
		Creater:      creater,
		Ctime:        ctime,
		Status:       1,
		ReturnTime:   cancelStockDate.Unix(),
		Dealer:       dealer_id,
		Manufacturer: manufacturer_id,
		Type:         types,
	}
	service.AddSigleDrugCancelStock(&cancelStock)
	fmt.Println("hh232323232323232323232323232322332", parseDateErr)
	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	var cancelStockInfos []*models.DrugCancelStockInfo
	var drugFlow []*models.DrugFlow

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

				if items["drug_id"] == nil || reflect.TypeOf(items["drug_id"]).String() != "float64" {
					utils.ErrorLog("drug_id")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				drug_id := int64(items["drug_id"].(float64))

				return_count, _ := items["return_count"].(string)
				if len(return_count) == 0 {
					utils.ErrorLog("len(return_count) == 0")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)

					return
				}

				count, _ := strconv.ParseInt(return_count, 10, 64)

				if items["price"] == nil || reflect.TypeOf(items["price"]).String() != "string" {
					utils.ErrorLog("price")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				price, _ := strconv.ParseFloat(items["price"].(string), 64)
				total := float64(count) * price

				if items["retail_price"] == nil || reflect.TypeOf(items["retail_price"]).String() != "string" {
					utils.ErrorLog("retail_price")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				retail_price, _ := strconv.ParseFloat(items["retail_price"].(string), 64)
				retail_price_total := float64(count) * retail_price

				register_account, _ := items["register_account"].(string)

				remark, _ := items["remark"].(string)

				var productDates int64
				var expiryDates int64

				if items["expiry_date"] == nil || reflect.TypeOf(items["expiry_date"]).String() != "string" {
					expiryDates = 0
				} else {
					if len(items["expiry_date"].(string)) == 0 {
						expiryDates = 0

					} else {
						expiryDate, _ := items["expiry_date"].(string)
						expiry_date, _ := utils.ParseTimeStringToTime("2006-01-02", expiryDate)
						expiryDates = expiry_date.Unix()

					}

				}
				if items["product_date"] == nil || reflect.TypeOf(items["product_date"]).String() != "string" {
					productDates = 0
				} else {
					if len(items["product_date"].(string)) == 0 {
						productDates = 0

					} else {
						productDate, _ := items["product_date"].(string)
						product_date, _ := utils.ParseTimeStringToTime("2006-01-02", productDate)
						productDates = product_date.Unix()
					}

				}

				manufacturer, _ := items["manufacturer"].(string)

				dealer, _ := items["dealer"].(string)

				batch_number := items["batch_number"].(string)
				max_unit := items["max_unit"].(string)
				batch_number_id := int64(items["batch_number_id"].(float64))

				fmt.Println("99999999999999999999", batch_number_id)
				cancelStockInfo := &models.DrugCancelStockInfo{
					OrderNumber:      cancelStock.OrderNumber,
					CancelStockId:    cancelStock.ID,
					DrugId:           drug_id,
					Count:            count,
					Status:           1,
					Ctime:            ctime,
					OrgId:            adminUserInfo.CurrentOrgId,
					Type:             types,
					Manufacturer:     manufacturer,
					Dealer:           dealer,
					Total:            total,
					RetailPrice:      retail_price,
					RetailTotalPrice: retail_price_total,
					Price:            price,
					RegisterAccount:  register_account,
					Remark:           remark,
					BatchNumber:      batch_number,
					MaxUnit:          max_unit,
					ProductDate:      productDates,
					ExpiryDate:       expiryDates,
					BatchNumberId:    batch_number_id,
				}
				cancelStockInfos = append(cancelStockInfos, cancelStockInfo)

				flow := &models.DrugFlow{
					WarehousingId:           0,
					DrugId:                  drug_id,
					Number:                  "",
					BatchNumber:             batch_number,
					Count:                   count,
					UserOrgId:               adminUserInfo.CurrentOrgId,
					PatientId:               0,
					SystemTime:              ctime,
					ConsumableType:          4,
					IsSys:                   0,
					WarehousingOrder:        "",
					WarehouseOutId:          0,
					WarehouseOutOrderNumber: "",
					IsEdit:                  0,
					CancelStockId:           cancelStock.ID,
					CancelOrderNumber:       cancelStock.OrderNumber,
					Manufacturer:            0,
					Dealer:                  0,
					Creator:                 adminUserInfo.AdminUser.Id,
					UpdateCreator:           0,
					Status:                  1,
					Ctime:                   time.Now().Unix(),
					Mtime:                   0,
					Price:                   price,
					WarehousingDetailId:     0,
					WarehouseOutDetailId:    0,
					CancelOutDetailId:       0,
					ExpireDate:              expiryDates,
					ProductDate:             productDates,
					MaxUnit:                 max_unit,
					MinUnit:                 "",
				}
				drugFlow = append(drugFlow, flow)
			}
		}
	}
	//扣减库存逻辑
	for _, item := range cancelStockInfos {
		var total_number int64
		var out_number int64
		var can_number int64
		medical, _ := service.GetBaseDrugMedical(item.DrugId)
		//将当前退库数转为最小单位
		if item.MaxUnit == medical.MaxUnit {
			total_number = item.Count * medical.MinNumber
		}
		if item.MaxUnit == medical.MinUnit {
			total_number = item.Count
		}
		fmt.Println("当前库存", total_number)
		//查询当前药品退库的批次号的总入库数
		infoWareInfo, _ := service.GetDrugWarehouseInfo(item.BatchNumberId)
		fmt.Println("hhh2h3h2hh3233", item.MaxUnit, medical.MaxUnit, infoWareInfo.StockMaxNumber, infoWareInfo.StockMinNumber)
		var total_count int64
		total_count = infoWareInfo.StockMaxNumber*medical.MinNumber + infoWareInfo.StockMinNumber
		fmt.Println("当前批次总库存", total_count)

		//查询该批次的出库数量
		outInfo, _ := service.GetDrugWarehouseOutInfo(item.BatchNumberId, item.DrugId)
		//查询该批次总的退库数量

		canInfo, _ := service.GetCancelDrugStockOutInfo(item.BatchNumberId, item.DrugId)
		for _, item := range canInfo {
			if item.MaxUnit == medical.MaxUnit {
				item.Count = item.Count * medical.MinNumber
			}
			if item.MaxUnit == medical.MinUnit {
				item.Count = item.Count
			}
		}
		for _, item := range canInfo {
			can_number += item.Count
		}

		for _, item := range outInfo {
			if item.CountUnit == medical.MaxUnit {
				item.Count = item.Count * medical.MinNumber
			}
			if item.CountUnit == medical.MinUnit {
				item.Count = item.Count
			}
		}
		for _, item := range outInfo {
			out_number += item.Count
		}
		fmt.Println("出库数量23232232323222332", out_number)
		if out_number == 0 {
			c.ServeSuccessJSON(map[string]interface{}{
				"msg": "2",
			})
			return
		}
		//判断退库数量是否大于总入库数量
		if total_number > out_number {
			service.UpdateDrugCancel(item.CancelStockId)
			c.ServeSuccessJSON(map[string]interface{}{
				"msg": "4",
			})
			return
		}

		//判断总退库数量是否大于出库数量
		fmt.Println("hhhhhhhhhhh", can_number+total_number)
		if can_number+total_number > out_number {
			service.UpdateDrugCancel(item.CancelStockId)
			c.ServeSuccessJSON(map[string]interface{}{
				"msg": "2",
			})
			return
		}

		//正常退库
		if total_number <= out_number {
			//创建退库详情
			errs := service.CreateDrugCancelStockInfo(cancelStockInfos)
			//创建库存明细
			errs = service.CreateDrugFlow(drugFlow)

			var total int64
			////退库到当前批次,获取当前退库批次的库存
			//info, _ := service.GetDrugWarehouseInfoById(item.BatchNumberId)

			if medical.MaxUnit == item.MaxUnit {
				total = item.Count

				warehouseInfo := models.XtDrugWarehouseInfo{
					StockMaxNumber: total,
				}
				errs = service.UpdateDrugWarehouseInfo(&warehouseInfo, item.BatchNumberId)
				if errs != nil {
					utils.ErrorLog(errs.Error())
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCancelStockFail)
					return
				}

				c.ServeSuccessJSON(map[string]interface{}{
					"msg": "1",
				})
			}
			if medical.MinUnit == item.MaxUnit {
				fmt.Println("hhhhhh2323323232322332232332999999999进来", item.Count)
				total = item.Count
				warehouseInfo := models.XtDrugWarehouseInfo{
					StockMinNumber: total,
				}

				errs = service.UpdateDrugWarehouseInfoOne(&warehouseInfo, item.BatchNumberId)
				if errs != nil {
					utils.ErrorLog(errs.Error())
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCancelStockFail)
					return
				}

				c.ServeSuccessJSON(map[string]interface{}{
					"msg": "1",
				})
			}
			if errs != nil {
				utils.ErrorLog(errs.Error())
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCancelStockFail)
				return
			}

			c.ServeSuccessJSON(map[string]interface{}{
				"msg": "1",
			})
		}
	}
}
func (c *StockDrugApiController) GetDrugCancelStockInfoList() {
	id, _ := c.GetInt64("id", 0)
	adminUserInfo := c.GetAdminUserInfo()

	cancelStockInfoList, _ := service.FindDrugCancelStockInfoById(id, adminUserInfo.CurrentOrgId)

	info, _ := service.FindCancelDrugById(id, adminUserInfo.CurrentOrgId)
	c.ServeSuccessJSON(map[string]interface{}{
		"list": cancelStockInfoList,
		"info": info,
	})

}
func (c *StockDrugApiController) GetDrugCancelStockList() {
	page, _ := c.GetInt64("page", -1)
	limit, _ := c.GetInt64("limit", -1)
	start_time := c.GetString("start_time")
	end_time := c.GetString("end_time")
	types, _ := c.GetInt64("type", 0)
	keywords := c.GetString("keywords")

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	var startTime int64
	if len(start_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	var endTime int64
	if len(end_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}

	adminUserInfo := c.GetAdminUserInfo()
	returnList, total, err := service.FindAllDrugCancelList(adminUserInfo.CurrentOrgId, page, limit, startTime, endTime, types, keywords)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"list":  returnList,
			"total": total,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}

}
func (this *StockDrugApiController) DeleteDrugCancelStock() {
	ids := this.GetString("ids")

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

	idArray := strings.Split(ids, ",")
	err := service.DeleteDrugCancelStock(idArray)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDeleteFail)
	} else {
		this.ServeSuccessJSON(map[string]interface{}{
			"msg": "删除成功",
		})
	}
}
func (this *StockDrugApiController) DeleteDrugCancelStockInfo() {
	id, _ := this.GetInt64("id", 0)
	fmt.Println(id)
	if id == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	err := service.UpDateDrugCancleStockStatus(id)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDeleteFail)
	} else {
		this.ServeSuccessJSON(map[string]interface{}{
			"msg": "删除成功",
		})
	}

}
func (c *StockDrugApiController) EditDrugCancelStock() {
	cancel_time := c.GetString("cancel_time")
	id, _ := c.GetInt64("id", 0)
	types, _ := c.GetInt64("type", 0)
	manufacturer_id, _ := c.GetInt64("manufacturer_id", 0)
	dealer_id, _ := c.GetInt64("dealer_id", 0)

	if id == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	ctime := time.Now().Unix()
	mtime := time.Now().Unix()
	adminUserInfo := c.GetAdminUserInfo()

	cancelDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", cancel_time)
	if parseDateErr != nil {
		c.ErrorLog("日期(%v)解析错误：%v", cancelDate, parseDateErr)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	cancelStock, _ := service.FindDrugCancelStockById(id)

	tempCancelStock := models.DrugCancelStock{
		ID:           cancelStock.ID,
		Mtime:        mtime,
		ReturnTime:   cancelDate.Unix(),
		Manufacturer: manufacturer_id,
		Dealer:       dealer_id,
	}

	service.EditDrugCancelStock(tempCancelStock)

	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	var cancelStockInfos []*models.DrugCancelStockInfo
	var upDateCancelStockInfos []*models.DrugCancelStockInfo
	var drugFlow []*models.DrugFlow
	if dataBody["cancelStock"] != nil && reflect.TypeOf(dataBody["cancelStock"]).String() == "[]interface {}" {
		thisCancelStock, _ := dataBody["cancelStock"].([]interface{})
		if len(thisCancelStock) > 0 {
			for _, item := range thisCancelStock {
				items := item.(map[string]interface{})

				if items["drug_id"] == nil || reflect.TypeOf(items["drug_id"]).String() != "float64" {
					utils.ErrorLog("drug_id")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				drug_id := int64(items["drug_id"].(float64))

				if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
					utils.ErrorLog("count")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}

				count, _ := strconv.ParseInt(items["count"].(string), 10, 64)

				if items["price"] == nil || reflect.TypeOf(items["price"]).String() != "string" {
					utils.ErrorLog("price")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				price, _ := strconv.ParseFloat(items["price"].(string), 64)
				total := float64(count) * price

				if items["retail_price"] == nil || reflect.TypeOf(items["retail_price"]).String() != "string" {
					utils.ErrorLog("retail_price")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				retail_price, _ := strconv.ParseFloat(items["retail_price"].(string), 64)
				retail_price_total := float64(count) * retail_price

				if items["id"] == nil || reflect.TypeOf(items["id"]).String() != "float64" {
					utils.ErrorLog("id")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				id := int64(items["id"].(float64))

				max_unit := items["max_unit"].(string)
				batch_number := items["batch_number"].(string)

				register_account := items["register_account"].(string)

				remark := items["remark"].(string)

				manufacturer := items["manufacturer"].(string)

				dealer := items["dealer"].(string)

				var productDates int64
				var expiryDates int64

				if items["expiry_date"] == nil || reflect.TypeOf(items["expiry_date"]).String() != "string" {
					expiryDates = 0
				} else {
					if len(items["expiry_date"].(string)) == 0 {
						expiryDates = 0

					} else {
						expiryDate, _ := items["expiry_date"].(string)
						expiry_date, _ := utils.ParseTimeStringToTime("2006-01-02", expiryDate)
						expiryDates = expiry_date.Unix()

					}

				}
				if items["product_date"] == nil || reflect.TypeOf(items["product_date"]).String() != "string" {
					productDates = 0
				} else {
					if len(items["product_date"].(string)) == 0 {
						productDates = 0

					} else {
						productDate, _ := items["product_date"].(string)
						product_date, _ := utils.ParseTimeStringToTime("2006-01-02", productDate)
						productDates = product_date.Unix()
					}

				}

				batch_number_id := int64(items["batch_number_id"].(float64))
				if id == 0 {
					cancelStockInfo := &models.DrugCancelStockInfo{
						DrugId:           drug_id,
						Count:            count,
						Status:           1,
						Ctime:            ctime,
						OrgId:            adminUserInfo.CurrentOrgId,
						OrderNumber:      cancelStock.OrderNumber,
						CancelStockId:    cancelStock.ID,
						Mtime:            time.Now().Unix(),
						Type:             types,
						RetailPrice:      retail_price,
						RetailTotalPrice: retail_price_total,
						Price:            price,
						Total:            total,
						Manufacturer:     manufacturer,
						Dealer:           dealer,
						RegisterAccount:  register_account,
						MaxUnit:          max_unit,
						BatchNumber:      batch_number,
						Remark:           remark,
						ProductDate:      productDates,
						ExpiryDate:       expiryDates,
						BatchNumberId:    batch_number_id,
					}
					cancelStockInfos = append(cancelStockInfos, cancelStockInfo)

				} else {
					cancelStockInfo := &models.DrugCancelStockInfo{
						ID:               id,
						DrugId:           drug_id,
						Count:            count,
						Status:           1,
						Ctime:            ctime,
						OrgId:            adminUserInfo.CurrentOrgId,
						OrderNumber:      cancelStock.OrderNumber,
						CancelStockId:    cancelStock.ID,
						Mtime:            time.Now().Unix(),
						Type:             types,
						RetailPrice:      retail_price,
						RetailTotalPrice: retail_price_total,
						Price:            price,
						Total:            total,
						Manufacturer:     manufacturer,
						Dealer:           dealer,
						RegisterAccount:  register_account,
						MaxUnit:          max_unit,
						BatchNumber:      batch_number,
						Remark:           remark,
						ProductDate:      productDates,
						ExpiryDate:       expiryDates,
						BatchNumberId:    batch_number_id,
					}
					upDateCancelStockInfos = append(upDateCancelStockInfos, cancelStockInfo)
				}

				flow := &models.DrugFlow{
					WarehousingId:           0,
					DrugId:                  drug_id,
					Number:                  "",
					BatchNumber:             batch_number,
					Count:                   count,
					UserOrgId:               adminUserInfo.CurrentOrgId,
					PatientId:               0,
					SystemTime:              time.Now().Unix(),
					ConsumableType:          4,
					IsSys:                   0,
					WarehousingOrder:        "",
					WarehouseOutId:          0,
					WarehouseOutOrderNumber: "",
					IsEdit:                  0,
					CancelStockId:           cancelStock.ID,
					CancelOrderNumber:       cancelStock.OrderNumber,
					Manufacturer:            0,
					Dealer:                  0,
					Creator:                 adminUserInfo.AdminUser.Id,
					UpdateCreator:           adminUserInfo.AdminUser.Id,
					Status:                  1,
					Ctime:                   time.Now().Unix(),
					Mtime:                   0,
					Price:                   price,
					WarehousingDetailId:     0,
					WarehouseOutDetailId:    0,
					CancelOutDetailId:       0,
					ExpireDate:              expiryDates,
					ProductDate:             productDates,
					MaxUnit:                 max_unit,
					MinUnit:                 "",
				}
				drugFlow = append(drugFlow, flow)
			}
		}
	}
	fmt.Println("cancelStockInfos232323223323223322323223", cancelStockInfos)
	fmt.Println("cancelStockInfos232323223323223322323223", upDateCancelStockInfos)

	var errs error
	if len(cancelStockInfos) > 0 {

		//扣减库存逻辑
		for _, item := range cancelStockInfos {
			medical, _ := service.GetBaseDrugMedical(item.DrugId)
			//查询当前药品退库的批次号的总入库数
			infoWareInfo, _ := service.GetDrugWarehouseInfo(item.BatchNumberId)
			fmt.Println("hhh2h3h2hh3233", item.MaxUnit, medical.MaxUnit)
			var total_count int64
			var cancel_count int64
			var out_count int64
			total_count = infoWareInfo.StockMaxNumber*medical.MinNumber + infoWareInfo.StockMinNumber
			//转化为最小单位
			var total_number int64
			if item.MaxUnit == medical.MaxUnit {
				total_number = item.Count * medical.MinNumber
			}
			if item.MaxUnit == medical.MinUnit {
				total_number = item.Count
			}

			//统计该批次的总出库数
			outInfo, _ := service.GetDrugWarehouseOutInfo(item.BatchNumberId, item.DrugId)
			for _, item := range outInfo {
				if item.CountUnit == medical.MaxUnit {
					item.Count = item.Count * medical.MinNumber
				}
				if item.CountUnit == medical.MinUnit {
					item.Count = item.Count
				}
			}

			for _, item := range outInfo {
				out_count += item.Count
			}
			fmt.Println("out_count232233332232323223", out_count)

			//判断退库数量是否大于出库数量
			cancelInfo, _ := service.GetCancelDrugStockOutInfo(item.BatchNumberId, item.DrugId)
			for _, item := range cancelInfo {
				if item.MaxUnit == medical.MaxUnit {
					item.Count = item.Count * medical.MinNumber
				}
				if item.MaxUnit == medical.MinUnit {
					item.Count = item.Count
				}
			}

			for _, item := range cancelInfo {
				cancel_count += item.Count
			}
			fmt.Println("cancel_count", cancel_count)
			fmt.Println("hhhhhh23h2h332322323232", total_number+cancel_count)
			if total_number+cancel_count > out_count {
				c.ServeSuccessJSON(map[string]interface{}{
					"msg": "4",
				})
				return
			}

			//判断退库数量是否大于总入库数量
			if total_number > total_count {
				c.ServeSuccessJSON(map[string]interface{}{
					"msg": "2",
				})
				return
			}

			//正常退库
			if total_number <= total_count {
				//创建退库详情
				errs := service.CreateDrugCancelStockInfo(cancelStockInfos)
				//创建库存明细
				errs = service.CreateDrugFlow(drugFlow)

				//获取该批次最后一条退库详情
				lastCancel, _ := service.GetLastCancelStockInfo(id)
				var cancel_number int64
				if lastCancel.MaxUnit == medical.MaxUnit {
					cancel_number = lastCancel.Count * medical.MinNumber
				}

				if lastCancel.MaxUnit == medical.MinUnit {
					cancel_number = lastCancel.Count
				}
				fmt.Println("999999232323232232232323232323", lastCancel)
				var total int64

				if medical.MaxUnit == item.MaxUnit {
					total = item.Count - cancel_number

					warehouseInfo := models.XtDrugWarehouseInfo{
						StockMaxNumber: total,
					}
					errs = service.UpdateDrugWarehouseInfo(&warehouseInfo, item.BatchNumberId)
					if errs != nil {
						utils.ErrorLog(errs.Error())
						c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCancelStockFail)
						return
					}

					c.ServeSuccessJSON(map[string]interface{}{
						"msg": "1",
					})
				}
				if medical.MinUnit == item.MaxUnit {
					total = item.Count - cancel_number
					warehouseInfo := models.XtDrugWarehouseInfo{
						StockMinNumber: total,
					}

					errs = service.UpdateDrugWarehouseInfoOne(&warehouseInfo, item.BatchNumberId)
					if errs != nil {
						utils.ErrorLog(errs.Error())
						c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCancelStockFail)
						return
					}

					c.ServeSuccessJSON(map[string]interface{}{
						"msg": "1",
					})
				}
				if errs != nil {
					utils.ErrorLog(errs.Error())
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCancelStockFail)
					return
				}

				c.ServeSuccessJSON(map[string]interface{}{
					"msg": "1",
				})
			}
		}
	}
	if len(drugFlow) > 0 {
		parseDateErr := service.CreateDrugFlow(drugFlow)
		fmt.Println(parseDateErr)
	}

	if len(upDateCancelStockInfos) > 0 {
		var total int64
		var out_count int64
		for _, item := range upDateCancelStockInfos {
			errs = service.UpDateDrugCancelStockInfo(item)
			//查询该批次最后一条退库记录
			info, _ := service.GetLastCancelStockInfo(id)
			//查询该药品的信息
			medical, _ := service.GetBaseDrugMedical(item.DrugId)
			//统计该批次的总出库数
			outInfo, _ := service.GetDrugWarehouseOutInfo(item.BatchNumberId, item.DrugId)
			for _, item := range outInfo {
				if item.CountUnit == medical.MaxUnit {
					item.Count = item.Count * medical.MinNumber
				}
				if item.CountUnit == medical.MinUnit {
					item.Count = item.Count
				}
			}

			for _, item := range outInfo {
				out_count += item.Count
			}

			fmt.Println("out_count232233332232323223", out_count)

			if item.MaxUnit == medical.MaxUnit {
				item.Count = item.Count * medical.MinNumber
				//更新库存
				total = item.Count - info.Count
				fmt.Println("total232323232323232232323", total)
				service.UpdatedDrugInfo(item.BatchNumberId, total)
				break
			}

			if item.MaxUnit == medical.MinUnit {
				item.Count = item.Count
				total = item.Count - info.Count
				service.UpdatedDrugInfoOne(item.BatchNumberId, total)
				break
			}
		}
	}

	if errs != nil {
		utils.ErrorLog(errs.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateCancelStockFail)
		return
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"msg": "1",
	})

}

func (c *StockDrugApiController) GetAllConfig() {
	adminUserInfo := c.GetAdminUserInfo()
	manufacturer, _ := service.FindAllManufacturer(adminUserInfo.CurrentOrgId)
	dealer, _ := service.FindAllDealer(adminUserInfo.CurrentOrgId)
	stockIns, _ := service.FindStockInNumber(adminUserInfo.CurrentOrgId)
	drugs, _ := service.GetDrugs(adminUserInfo.CurrentOrgId)
	c.ServeSuccessJSON(map[string]interface{}{
		"manufacturer": manufacturer,
		"dealer":       dealer,
		"drugs":        drugs,
		"numbers":      stockIns,
	})
}

func (c *StockDrugApiController) GetAllDrugStock() {
	adminUserInfo := c.GetAdminUserInfo()
	manufacturer_id, _ := c.GetInt64("manufacturer_id", 0)
	dealer_id, _ := c.GetInt64("dealer_id", 0)
	drugs, err := service.FindAllDrugByManufactureId(manufacturer_id, dealer_id, adminUserInfo.CurrentOrgId)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"drugs": drugs,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}

func (c *StockDrugApiController) GetDrugQueryInfo() {
	page, _ := c.GetInt64("page", -1)
	limit, _ := c.GetInt64("limit", -1)
	keyword := c.GetString("keyword")
	drug_category, _ := c.GetInt64("drug_category")
	start_time := c.GetString("start_time")
	end_time := c.GetString("end_time")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")

	var startTime int64
	if len(start_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
		if err != nil {
			fmt.Println(err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	var endTime int64
	if len(end_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}
	adminUserInfo := c.GetAdminUserInfo()
	list, total, err := service.FindAllDrugStockInfo(adminUserInfo.CurrentOrgId, page, limit, keyword, drug_category, startTime, endTime)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"list":  list,
			"total": total,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}

func (this *StockDrugApiController) GetUserDetailInfo() {
	order_id, _ := this.GetInt64("id")
	if order_id <= 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	adminUserInfo := this.GetAdminUserInfo()
	userDetails, err, total := service.FindDrugStockUserDetailById(adminUserInfo.CurrentOrgId, order_id)

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

}

func (this *StockDrugApiController) GetCancelDrugOrderPrint() {

	orderId := this.GetString("order_id")
	ids := strings.Split(orderId, ",")
	orgId := this.GetAdminUserInfo().CurrentOrgId
	list, _ := service.GetCancelDrugOrderPrint(ids, orgId)
	this.ServeSuccessJSON(map[string]interface{}{
		"list": list,
	})
}

func (this *StockDrugApiController) GetDrugCancelExportList() {

	orderId := this.GetString("order_id")
	fmt.Println("order_id2323232323223", orderId)
	ids := strings.Split(orderId, ",")
	orgId := this.GetAdminUserInfo().CurrentOrgId
	list, _ := service.GetDrugCancelExportList(ids, orgId)
	this.ServeSuccessJSON(map[string]interface{}{
		"list": list,
	})
}

func (c *StockDrugApiController) GetDrugWarehouseInfoPrint() {

	start_time := c.GetString("start_time")
	end_time := c.GetString("end_time")
	order_type, _ := c.GetInt64("order_type")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")

	var startTime int64
	if len(start_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
		if err != nil {
			fmt.Println(err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	var endTime int64
	if len(end_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}
	adminUserInfo := c.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	if order_type == 1 {
		list, err := service.GetDrugWarehouseInfoPrint(startTime, endTime, orgId)
		if err == nil {
			c.ServeSuccessJSON(map[string]interface{}{
				"list": list,
			})
			return
		}
	}
}

func (c *StockDrugApiController) GetDrugOutOrderPrint() {

	start_time := c.GetString("start_time")
	end_time := c.GetString("end_time")
	order_type, _ := c.GetInt64("order_type")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")

	var startTime int64
	if len(start_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
		if err != nil {
			fmt.Println(err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	var endTime int64
	if len(end_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}
	adminUserInfo := c.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	if order_type == 2 {
		//list, err := service.GetDrugOutOrderPrint(startTime, endTime, orgId)
		list, err := service.GetDrugOutOrderPrintList(startTime, endTime, orgId)
		if err == nil {
			c.ServeSuccessJSON(map[string]interface{}{
				"list": list,
			})
			return
		}
	}

}
