package controllers

import (
	"XT_New/enums"
	"XT_New/models"
	"XT_New/service"
	"XT_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")

}

func (c *StockDrugApiController) CreateDrugWarehouse() {

	warehousing_time := c.GetString("warehousing_time")
	dealer_id, _ := c.GetInt64("dealer_id", 0)
	manufacturer_id, _ := c.GetInt64("manufacturer_id", 0)

	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.FindAllWarehouseTotal(adminUserInfo.CurrentOrgId)
	total = total + 1
	warehousing_order := "YPRKD" + strconv.FormatInt(adminUserInfo.CurrentOrgId, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000" + strconv.FormatInt(total, 10)
	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(),
		Dealer:           dealer_id,
		Manufacturer:     manufacturer_id,
		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

	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["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(warehousing_count) * retail_price

				var productDates int64
				var expiryDates int64

				fmt.Println()

				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 items["number"] == nil || reflect.TypeOf(items["number"]).String() != "string" {
					utils.ErrorLog("number")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				number, _ := items["number"].(string)

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

				warehouseInfo := &models.DrugWarehouseInfo{
					WarehousingOrder: warehousing.WarehousingOrder,
					WarehousingId:    warehousing.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_id,
					Dealer:           dealer_id,
					RetailPrice:      retail_price,
					RetailTotalPrice: retail_price_total,
				}
				warehousingInfo = append(warehousingInfo, warehouseInfo)

			}
		}
	}
	errs := service.CreateDrugWarehousingInfo(warehousingInfo)
	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,
	})
	//}

	//else {
	//	warehouse, err1 := service.FindWareHouseByOrderNumber(warehousing_order)
	//	if (err1 != nil) {
	//		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
	//		return
	//	}
	//
	//	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.WarehousingInfo
	//
	//	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["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
	//					utils.ErrorLog("good_id")
	//					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
	//					return
	//				}
	//				good_id := int64(items["good_id"].(float64))
	//
	//				if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
	//					utils.ErrorLog("good_type_id")
	//					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
	//					return
	//				}
	//				good_type_id := int64(items["good_type_id"].(float64))
	//
	//				if items["warehousing_count"] == nil || reflect.TypeOf(items["warehousing_count"]).String() != "string" {
	//					utils.ErrorLog("warehousing_count")
	//					c.ServeFailJSONWithSGJErrorCod  Fe(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["expiry_date"] == nil || reflect.TypeOf(items["expiry_date"]).String() != "string" {
	//					utils.ErrorLog("expiry_date")
	//					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
	//					return
	//				}
	//
	//				expiryDate, _ := items["expiry_date"].(string)
	//				if len(expiryDate) == 0 {
	//					utils.ErrorLog("len(expiry_date) == 0")
	//					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
	//
	//					return
	//				}
	//
	//				expiry_date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", expiryDate)
	//				if parseDateErr != nil {
	//					c.ErrorLog("日期(%v)解析错误：%v", expiry_date, parseDateErr)
	//				}
	//
	//				var productDates int64
	//
	//				if items["product_date"] == nil || reflect.TypeOf(items["product_date"]).String() != "string" {
	//					productDates = 0;
	//				} else {
	//					productDate, _ := items["product_date"].(string)
	//					product_date, _ := utils.ParseTimeStringToTime("2006-01-02", productDate)
	//					productDates = product_date.Unix()
	//
	//				}
	//
	//				if items["number"] == nil || reflect.TypeOf(items["number"]).String() != "string" {
	//					utils.ErrorLog("number")
	//					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
	//					return
	//				}
	//				number, _ := items["number"].(string)
	//
	//				var remark string
	//				if items["number"] == nil || reflect.TypeOf(items["number"]).String() != "string" {
	//					remark = ""
	//				} else {
	//					remark = items["remark"].(string)
	//				}
	//
	//				warehouseInfo := &models.WarehousingInfo{
	//					WarehousingOrder: warehousing_order,
	//					WarehousingId:    warehouse.ID,
	//					GoodId:           good_id,
	//					Number:           number,
	//					GoodTypeId:       good_type_id,
	//					ProductDate:      productDates,
	//					ExpiryDate:       expiry_date.Unix(),
	//					WarehousingCount: warehousing_count,
	//					Price:            price,
	//					TotalPrice:       total,
	//					Status:           1,
	//					Ctime:            ctime,
	//					Remark:           remark,
	//					OrgId:            adminUserInfo.CurrentOrgId,
	//				}
	//				warehousingInfo = append(warehousingInfo, warehouseInfo)
	//
	//			}
	//		}
	//	}
	//	errs := service.CreateWarehousingInfo(warehousingInfo)
	//	info, _ := service.FindLastWarehousingInfo(warehousing_order)
	//
	//	if (errs != nil) {
	//		utils.ErrorLog(errs.Error())
	//		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateStockInFail)
	//		return
	//	}
	//
	//	c.ServeSuccessJSON(map[string]interface{}{
	//		"msg":  "入库成功",
	//		"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")

	fmt.Println(start_time)
	fmt.Println(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()
	warehouseList, total, err := service.FindAllDrugWarehousingList(adminUserInfo.CurrentOrgId, page, limit, startTime, endTime, types, keywords)
	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)

	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}

	if warehousing.ID <= 0 {
		return
	}

	warehousingInfo, err := service.FindDrugWarehousingInfoById(id, admin.CurrentOrgId)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"info":        warehousingInfo,
			"warehousing": warehousing,
		})
	} 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)
	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()

	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,
		Dealer:           dealer_id,
		Manufacturer:     manufacturer_id,
	}

	service.EditDrugWarehousing(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 upDateWarehousingInfo []*models.DrugWarehouseInfo

	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["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(warehousing_count) * retail_price

				var productDates int64
				var expiryDates int64

				fmt.Println()

				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 items["number"] == nil || reflect.TypeOf(items["number"]).String() != "string" {
					utils.ErrorLog("number")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				number, _ := items["number"].(string)

				var remark string
				if items["number"] == nil || reflect.TypeOf(items["number"]).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))

				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_id,
						Dealer:           dealer_id,
						RetailPrice:      retail_price,
						RetailTotalPrice: retail_price_total,
					}
					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_id,
						Dealer:           dealer_id,
						RetailPrice:      retail_price,
						RetailTotalPrice: retail_price_total,
					}
					upDateWarehousingInfo = append(upDateWarehousingInfo, warehouseInfo)
				}
			}
		}
	}
	var errs error
	if len(warehousingInfo) > 0 {
		errs = service.CreateDrugWarehousingInfo(warehousingInfo)
	}

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

	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() {
	dealer_id, _ := c.GetInt64("dealer_id", 0)
	manufacturer_id, _ := c.GetInt64("manufacturer_id", 0)
	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(),
		Dealer:                  dealer_id,
		Manufacturer:            manufacturer_id,
		Type:                    types,
	}
	service.AddSigleDrugWarehouseOut(&warehouseOut)
	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

	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["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)

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

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

				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_id,
					Dealer:                  dealer_id,
					RetailPrice:             retail_price,
					RetailTotalPrice:        retail_price_total,
				}
				warehousingOutInfo = append(warehousingOutInfo, warehouseOutInfo)

			}
		}
	}
	errs := service.CreateDrugWarehousingOutInfo(warehousingOutInfo)
	info, _ := service.FindLastDrugWarehousingOutInfo(warehouseOut.WarehouseOutOrderNumber)
	if errs != nil {
		utils.ErrorLog(errs.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateStockOutFail)
		return
	}

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

}
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()
	warehouseOutList, total, err := service.FindAllDrugWarehouseOutList(adminUserInfo.CurrentOrgId, page, limit, startTime, endTime, types, keywords)
	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)
	c.ServeSuccessJSON(map[string]interface{}{
		"list": warehouseOutInfo,
		"info": warehouseOut,
	})

}
func (c *StockDrugApiController) EditDrugWarehouseOut() {
	warehouse_out_time := c.GetString("warehouse_out_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()

	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(),
		Manufacturer:     manufacturer_id,
		Dealer:           dealer_id,
	}

	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

	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)

				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))

				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_id,
						Dealer:                  dealer_id,
						IsSys:                   0,
						SysRecordTime:           0,
						RetailPrice:             retail_price,
						RetailTotalPrice:        retail_price_total,
					}
					warehousingOutInfo = append(warehousingOutInfo, warehouseOutInfo)

				} 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_id,
						Dealer:                  dealer_id,
						IsSys:                   is_sys,
						SysRecordTime:           sys_record_time,
						RetailPrice:             retail_price,
						RetailTotalPrice:        retail_price_total,
					}
					upDateWarehouseOutInfos = append(upDateWarehouseOutInfos, warehouseOutInfo)
				}
			}
		}
	}
	var errs error
	if len(warehousingOutInfo) > 0 {
		errs = service.CreateDrugWarehousingOutInfo(warehousingOutInfo)
	}

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

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

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

}

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
	}

	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)
	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

	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

				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_id,
					Dealer:           dealer_id,
					Total:            total,
					RetailPrice:      retail_price,
					RetailTotalPrice: retail_price_total,
					Price:            price,
				}
				cancelStockInfos = append(cancelStockInfos, cancelStockInfo)

			}
		}
	}
	errs := service.CreateDrugCancelStockInfo(cancelStockInfos)
	if errs != nil {
		utils.ErrorLog(errs.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCancelStockFail)
		return
	}

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

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

	cancelStockInfoList, _ := service.FindDrugCancelStockInfoById(id, adminUserInfo.CurrentOrgId)
	info, _ := service.FindCancelStockById(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

	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)

				//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

				if items["id"] == nil || reflect.TypeOf(items["id"]).String() != "float64" {
					utils.ErrorLog("id")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				id := int64(items["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,
						Manufacturer:     manufacturer_id,
						Dealer:           dealer_id,
						RetailPrice:      retail_price,
						RetailTotalPrice: retail_price_total,
						Price:            price,
						Total:            total,
					}
					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,
						Manufacturer:     manufacturer_id,
						Dealer:           dealer_id,
						RetailPrice:      retail_price,
						RetailTotalPrice: retail_price_total,
						Price:            price,
						Total:            total,
					}
					upDateCancelStockInfos = append(upDateCancelStockInfos, cancelStockInfo)
				}
			}
		}
	}
	var errs error
	if len(cancelStockInfos) > 0 {
		errs = service.CreateDrugCancelStockInfo(cancelStockInfos)
	}

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

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

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

}

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")

	adminUserInfo := c.GetAdminUserInfo()
	list, total, err := service.FindAllDrugStockInfo(adminUserInfo.CurrentOrgId, page, limit, keyword)
	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
	}

}
