package controllers

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

type SecondaryOrderApiController struct {
	BaseAuthAPIController
}

func SecondaryOrderApiRegistRouters() {
	beego.Router("/api/secondary/getcode", &SecondaryOrderApiController{}, "get:GetStoreCode")                      //获取仓库编码
	beego.Router("/api/secondary/updatestatus", &SecondaryOrderApiController{}, "get:UpdateStatus")                 //修改仓库状态
	beego.Router("/api/secondary/deletestorehouse", &SecondaryOrderApiController{}, "get:DeleteStorehouse")         //删除仓库
	beego.Router("/api/secondary/isstorehousename", &SecondaryOrderApiController{}, "get:IsStorehouseName")         //仓库名称是否重复
	beego.Router("/api/secondary/isstorehouseaddress", &SecondaryOrderApiController{}, "get:IsStorehouseAddress")   //仓库地址是否重复
	beego.Router("/api/secondary/storehouselist", &SecondaryOrderApiController{}, "get:StorehouseList")             //分页
	beego.Router("/api/secondary/addstorehouse", &SecondaryOrderApiController{}, "post:AddStorehouse")              //新增仓库
	beego.Router("/api/secondary/updatestorehouse", &SecondaryOrderApiController{}, "post:UpdateStorehouse")        //修改
	beego.Router("/api/secondary/getonestorehouse", &SecondaryOrderApiController{}, "get:GetOneStorehouse")         //查一条仓库的信息
	beego.Router("/api/secondary/getallstorehousename", &SecondaryOrderApiController{}, "get:GetAllStorehouseName") //获取当前机构的所有可用仓库名称
	beego.Router("/api/secondary/findstorehouseconfig", &SecondaryOrderApiController{}, "get:FindStorehouseConfig") //查询该机构的仓库配置
	beego.Router("/api/secondary/updateinfo", &SecondaryOrderApiController{}, "get:UpdateInfo")                     //更改耗材自动入库仓库
	beego.Router("/api/secondary/updateoutinfo", &SecondaryOrderApiController{}, "get:UpdateOutInfo")               //更改耗材自动出库仓库
	beego.Router("/api/secondary/updatedruginfo", &SecondaryOrderApiController{}, "get:UpdateDrugInfo")             //更改药品自动入库仓库
	beego.Router("/api/secondary/updatedrugout", &SecondaryOrderApiController{}, "get:UpdateDrugOut")               //更改药品自动出库仓库
	beego.Router("/api/secondary/getusername", &SecondaryOrderApiController{}, "get:GetuserName")                   //获取仓库管理员信息
	beego.Router("/api/secondary/byliinit", &SecondaryOrderApiController{}, "get:Byliinit")                         //初始化旧数据
	beego.Router("/api/secondary/getcreaterid", &SecondaryOrderApiController{}, "get:GetCreaterId")                 //获取当前登录的人的id

	beego.Router("/api/seconde/getsencondegoodlist", &SecondaryOrderApiController{}, "Get:GetSencondeGoodList")
	beego.Router("/api/senconde/savesencondorder", &SecondaryOrderApiController{}, "Post:SaveSencondOrder")
	beego.Router("/api/senconde/getallsecondeorderlist", &SecondaryOrderApiController{}, "Get:GetAllSecondeOrderList")
	beego.Router("/api/senconde/getsencondorderdetail", &SecondaryOrderApiController{}, "Get:GetSencondOrderDetail")
	beego.Router("/api/senconde/updatesencondorder", &SecondaryOrderApiController{}, "Post:UpdateSencondOrder")
	beego.Router("/api/sencond/getsecondorderbyid", &SecondaryOrderApiController{}, "Get:GetSecondOrderById")
	beego.Router("/api/sencond/checksecondorder", &SecondaryOrderApiController{}, "Get:CheckSecondOrer")
	beego.Router("/api/sencond/deletestorehouselist", &SecondaryOrderApiController{}, "Get:DeleteStorehouseList")
	beego.Router("/api/sencond/returnchecksecondeorder", &SecondaryOrderApiController{}, "Get:ReturnCheckSecondOrder")
	beego.Router("/api/second/getstorehousegoodlist", &SecondaryOrderApiController{}, "Get:GetStoreHouseGoodList")
	beego.Router("/api/second/getsumsecondecount", &SecondaryOrderApiController{}, "Get:GetSumSecondCount")
	beego.Router("/api/second/deletesecondorderinfo", &SecondaryOrderApiController{}, "Get:DeleteSecondOrderInfo")
}

//获取仓库编码
func (this *SecondaryOrderApiController) GetStoreCode() {
	orgId := this.GetAdminUserInfo().CurrentOrgId
	var code string
	for a := true; a == true; {
		code = service.CreateCode()
		tmp := service.FindStorehouseCode(orgId, code)
		//如果没有重复的编码结束循环
		if tmp == false {
			a = false
		}
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": code,
	})
	return
}

//修改仓库状态
func (this *SecondaryOrderApiController) UpdateStatus() {
	orgId := this.GetAdminUserInfo().CurrentOrgId
	check := map[string][]string{
		"id": {"must", "int", "id"},
	}
	_, err := checkParams(this, &check)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	id, _ := this.GetInt64("id")
	//判断该仓库的库存是否为零
	boolean := service.IsStorehouseNil(id, orgId)
	if boolean == false {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "该仓库库存不为0，不支持该操作")
		return
	}
	//判断该仓库是否在仓库配置表中
	boolean = service.IsInConfig(orgId, id)
	if boolean == true {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "当前仓库是自动出入库仓库，请先取消自动出入库之后才能进行此操作")
		return
	}
	//修改仓库状态
	err = service.UpdateStorehouseStatus(id)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": "修改成功",
	})
	return
}

//删除仓库
func (this *SecondaryOrderApiController) DeleteStorehouse() {
	orgId := this.GetAdminUserInfo().CurrentOrgId
	check := map[string][]string{
		"id": {"must", "int", "id"},
	}
	_, err := checkParams(this, &check)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	id, _ := this.GetInt64("id")
	//判断该仓库的库存是否为零
	boolean := service.IsStorehouseNil(id, orgId)
	if boolean == false {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "该仓库库存不为0，不支持该操作")
		return
	}
	//判断该仓库是否在仓库配置表中
	boolean = service.IsInConfig(orgId, id)
	if boolean == true {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "当前仓库是自动出入库仓库，请先取消自动出入库之后才能进行此操作")
		return
	}
	err = service.DeleteStorehouse(id)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": "删除成功",
	})
	return
}

//仓库名称是否重复
func (this *SecondaryOrderApiController) IsStorehouseName() {
	orgId := this.GetAdminUserInfo().CurrentOrgId
	storehouse_name := this.GetString("storehouse_name")
	check := map[string][]string{
		"storehouse_name": {"must", "string", "storehouse_name"},
	}
	_, err := checkParams(this, &check)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	var bo bool
	bo, err = service.IsStorehouseName(orgId, storehouse_name)
	if bo == true {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "该仓库已存在，请重新输入")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": "ok",
	})
	return

}

//仓库地址是否重复
func (this *SecondaryOrderApiController) IsStorehouseAddress() {
	orgId := this.GetAdminUserInfo().CurrentOrgId
	storehouse_address := this.GetString("storehouse_address")
	check := map[string][]string{
		"storehouse_address": {"must", "string", "storehouse_address"},
	}
	_, err := checkParams(this, &check)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	var bo bool
	bo, err = service.IsStorehouseAddress(orgId, storehouse_address)
	if bo == true {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "该地址已存在，请重新输入")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": "ok",
	})
	return

}

//分页
func (this *SecondaryOrderApiController) StorehouseList() {
	adminUserInfo := this.GetAdminUserInfo()
	page, _ := this.GetInt64("page")   //页码
	limit, _ := this.GetInt64("limit") //每一页查出来的条数
	check := map[string][]string{
		"page":  {"must", "string", "page"},
		"limit": {"must", "string", "limit"},
	}
	_, err := checkParams(this, &check)
	keyword := this.GetString("keyword")
	orgId := this.GetAdminUserInfo().CurrentOrgId
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
	}
	namemap := make(map[int64]string)
	//根据管理员id获取管理员
	viewModels, _, _ := service.GetAdminUsersAndLoginInfo(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, 1, 100)
	for _, v := range viewModels {
		namemap[int64(v.AdminUserId)] = v.UserName
	}
	slicekey := make([]int64, 0)
	if len(keyword) > 0 {
		for k, v := range namemap {
			res := strings.Contains(v, keyword)
			if res == true {
				slicekey = append(slicekey, k)
			}
		}
	}
	//获取分页的数据
	list, total, err := service.StorehouseList(page, limit, orgId, keyword, slicekey)

	//分页
	type Storehouselist struct {
		ID                  int64
		StorehouseCode      string //仓库编号
		StorehouseName      string //仓库名称
		StorehouseAddress   string //仓库地址
		StorehouseStatus    int64  //仓库状态
		Status              int64  //数据状态
		StorehouseAdminId   int64  //仓库管理员id
		StorehouseAdminName string //仓库管理员名字
		UserOrgId           int64
	}
	//初始化该结构体
	tmplist := []*Storehouselist{}
	for i := 0; i < len(list); i++ {
		tlist := &Storehouselist{
			list[i].ID,
			list[i].StorehouseCode,
			list[i].StorehouseName,
			list[i].StorehouseAddress,
			list[i].StorehouseStatus,
			list[i].Status,
			list[i].StorehouseAdminId,
			"",
			list[i].UserOrgId,
		}
		tmplist = append(tmplist, tlist)
	}
	for _, v := range tmplist {
		if k, ok := namemap[v.StorehouseAdminId]; ok {
			v.StorehouseAdminName = k
		} else {
			v.StorehouseAdminName = "超级管理员"
		}
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list":  tmplist,
		"total": total,
	})
}

//新增仓库
func (this *SecondaryOrderApiController) AddStorehouse() {
	orgId := this.GetAdminUserInfo().CurrentOrgId
	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	defer func() {
		if err != nil{
			service.SaveErrs(this.GetAdminUserInfo().CurrentOrgId,this.Ctx.Input,err)
		}
	}()
	var storehouse_status, admin_id int64
	tmpstatus := dataBody["storehouse_status"]
	tmpid := dataBody["storehouse_admin_id"] //管理员id
	if tmpstatus == nil {
		storehouse_status = 1
	} else {
		storehouse_status = int64(dataBody["storehouse_status"].(float64)) //状态
	}
	if tmpid == nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "管理员id不能为空")
		return
	} else {
		admin_id = int64(dataBody["storehouse_admin_id"].(float64)) //管理员id
	}
	switch {
	case dataBody["storehouse_code"] == nil:
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "仓库编号不能为空")
		return
	case dataBody["storehouse_name"] == nil:
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "仓库名称不能为空")
		return
	case dataBody["storehouse_address"] == nil:
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "仓库地址不能为空")
		return
	}
	code := dataBody["storehouse_code"].(string)       //仓库编号
	name := dataBody["storehouse_name"].(string)       //仓库名称
	address := dataBody["storehouse_address"].(string) //地址
	switch {
	case name == "":
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "仓库名称不能为空")
		return
	case address == "":
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "仓库地址不能为空")
		return
	}

	//判断仓库名称是否重复
	var bo bool
	bo, err = service.IsStorehouseName(orgId, name)
	if bo == true {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "该仓库已存在，请重新输入")
		return
	}
	//判断仓库地址是否重复
	bo, err = service.IsStorehouseAddress(orgId, address)
	if bo == true {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "该地址已存在，请重新输入")
		return
	}

	storehouse := models.Storehouse{
		StorehouseCode:    code,
		StorehouseName:    name,
		StorehouseAddress: address,
		StorehouseStatus:  storehouse_status,
		UserOrgId:         orgId,
		Status:            1,
		StorehouseAdminId: admin_id,
		Ctime:             time.Now().Unix(),
	}
	var shiwu string
	shiwu, err = service.AddStroehouse(storehouse)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "保存失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list":  "保存成功",
		"shiwu": shiwu,
	})

	return

}

//修改仓库
func (this *SecondaryOrderApiController) UpdateStorehouse() {
	orgId := this.GetAdminUserInfo().CurrentOrgId
	dataBody := make(map[string]interface{}, 0)
	//orgId := this.GetAdminUserInfo().CurrentOrgId
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	var storehouse_status, admin_id int64
	tmpstatus := dataBody["storehouse_status"]
	tmpid := dataBody["storehouse_admin_id"]
	if tmpstatus == nil {
		storehouse_status = 1
	} else {
		storehouse_status = int64(dataBody["storehouse_status"].(float64)) //状态
	}
	if tmpid == nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "管理员id不能为空")
		return
	} else {
		admin_id = int64(dataBody["storehouse_admin_id"].(float64)) //管理员id
	}

	switch {
	case dataBody["id"] == nil:
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "仓库id不能为空")
		return
	case dataBody["storehouse_name"] == nil:
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "仓库名称不能为空")
		return
	case dataBody["storehouse_address"] == nil:
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "仓库地址不能为空")
		return
	}
	id := int64(dataBody["id"].(float64))
	name := dataBody["storehouse_name"].(string)       //仓库名称
	address := dataBody["storehouse_address"].(string) //地址
	//查询当前仓库状态，根据当前状态判断是否需要更改
	list, errs := service.GetOneStorehouse(id, orgId)
	if errs != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	if storehouse_status != list.StorehouseStatus && storehouse_status == 0 {
		//判断该仓库的库存是否为零
		boolean := service.IsStorehouseNil(id, orgId)
		if boolean == false {
			this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "该仓库库存不为0，不支持该操作")
			return
		}
		//判断该仓库是否在仓库配置表中
		boolean = service.IsInConfig(orgId, id)
		if boolean == true {
			this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "当前仓库是自动出入库仓库，请先取消自动出入库之后才能进行此操作")
			return
		}
	}
	//判断仓库名称是否重复
	var bo bool
	bo, err = service.IsStorehouseNameUp(orgId, id, name)
	if bo == true {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "该仓库已存在，请重新输入")
		return
	}
	//判断仓库地址是否重复
	bo, err = service.IsStorehouseAddressUp(orgId, id, address)
	if bo == true {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "该地址已存在，请重新输入")
		return
	}
	storehouse := models.Storehouse{
		ID:                id,
		StorehouseName:    name,
		StorehouseAddress: address,
		StorehouseStatus:  storehouse_status,
		StorehouseAdminId: admin_id,
		Mtime:             time.Now().Unix(),
	}
	err = service.UpdateStroehouse(storehouse)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "保存失败")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": "保存成功",
	})
	return

}

func (this *SecondaryOrderApiController) GetSencondeGoodList() {

	orgId := this.GetAdminUserInfo().CurrentOrgId

	houseList, _ := service.GetAllStoreHouseListThree(orgId)

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

func (this *SecondaryOrderApiController) SaveSencondOrder() {

	start_date := this.GetString("record_date")
	storehouse_in_id, _ := this.GetInt64("storehouse_in_id")
	storehouse_out_id, _ := this.GetInt64("storehouse_out_id")
	fmt.Println(storehouse_in_id, storehouse_out_id)
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	var startDate int64
	if len(start_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_date+" 00:00:00", loc)
		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startDate = theTime.Unix()
	}
	//生成购货订单
	timeStr := time.Now().Format("2006-01-02")
	timeArr := strings.Split(timeStr, "-")
	orgId := this.GetAdminUserInfo().CurrentOrgId

	warehousing_order := "DB1010" + timeArr[0] + timeArr[1] + timeArr[2] + fmt.Sprintf("%04v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(10000))
	recordDateStr := time.Now().Format("2006-01-02")
	recordDate, _ := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
	record_date := recordDate.Unix()
	creater := this.GetAdminUserInfo().AdminUser.Id
	warehouse := models.XtSecondWarehouse{
		SecondOrderNumber: warehousing_order,
		Creater:           creater,
		RecordDate:        startDate,
		Checker:           0,
		IsCheck:           2,
		UserOrgId:         orgId,
		Status:            1,
		Ctime:             time.Now().Unix(),
		StorehouseInId:    storehouse_in_id,
		StorehouseOutId:   storehouse_out_id,
	}

	//查询改订单号是否存在
	_, errcode := service.GetSecondWarehouseByNumber(orgId, warehousing_order)
	if errcode == gorm.ErrRecordNotFound {
		service.CreateSecondeWarehouse(warehouse)
	} else if errcode == nil {
		order := "DB1010" + timeArr[0] + timeArr[1] + timeArr[2] + fmt.Sprintf("%04v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(10000))
		warehouse.SecondOrderNumber = order
		service.CreateSecondeWarehouse(warehouse)
	}

	secondWarehouse, _ := service.GetLastSecondWarehouse(orgId)
	var warehousingInfo []*models.XtSecondWarehouseInfo
	dataBody := make(map[string]interface{}, 0)

	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	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["project_id"] == nil || reflect.TypeOf(items["project_id"]).String() != "float64" {
					utils.ErrorLog("project_id")
					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}

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

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

				project_name := items["name"].(string)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

				min_price := items["min_price"].(float64)

				info := &models.XtSecondWarehouseInfo{
					ProjectName:             project_name,
					SecondSpecificationName: second_specification_name,
					ProjectType:             project_type,
					SencondUnit:             sencond_unit,
					Count:                   count,
					SecondTotal:             second_total,
					SecondOrderNumber:       secondWarehouse.SecondOrderNumber,
					RecordDate:              record_date,
					StorehouseInId:          storehouse_in_id,
					StorehouseOutId:         storehouse_out_id,
					Creater:                 creater,
					ProjectId:               project_id,
					Remake:                  remake,
					UserOrgId:               orgId,
					Status:                  1,
					Ctime:                   time.Now().Unix(),
					Mtime:                   0,
					MinPrice:                min_price,
					IsSource:                is_source,
					WarehouseId:             secondWarehouse.ID,
				}

				warehousingInfo = append(warehousingInfo, info)
			}
		}
	}

	for _, item := range warehousingInfo {
		service.CreateSencondWarehousingInfo(item)
	}

	//获取最后一条入库单
	lastSecondWarehouse, _ := service.GetLastSecondWarehouse(orgId)

	this.ServeSuccessJSON(map[string]interface{}{
		"warehousingInfo": warehousingInfo,
		"id":              lastSecondWarehouse.ID,
	})
	return
}

func (this *SecondaryOrderApiController) GetAllSecondeOrderList() {

	check_id, _ := this.GetInt64("check_id")
	start_time := this.GetString("start_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 {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	end_time := this.GetString("end_time")
	var endTime int64
	if len(end_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 00:00:00", loc)
		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}
	keyword := this.GetString("keyword")
	page, _ := this.GetInt64("page")
	limit, _ := this.GetInt64("limit")
	orgId := this.GetAdminUserInfo().CurrentOrgId
	list, total, _ := service.GetAllSecondeOrderList(check_id, startTime, endTime, keyword, page, limit, orgId)
	houseList, _ := service.GetAllStoreHouseList(orgId)
	appId := this.GetAdminUserInfo().CurrentAppId
	doctor, _ := service.GetAllDoctorListSix(orgId, appId)
	this.ServeSuccessJSON(map[string]interface{}{
		"list":       list,
		"total":      total,
		"houseList":  houseList,
		"doctorList": doctor,
	})
	return
}

func (this *SecondaryOrderApiController) GetSencondOrderDetail() {

	id, _ := this.GetInt64("id")
	orgId := this.GetAdminUserInfo().CurrentOrgId
	warehouse, _ := service.GetSecondWarehouseOrderById(id)

	//获取药品库数据
	baseList, _ := service.GetSupplyDrugListOne(orgId, warehouse.StorehouseOutId)

	goodList, _ := service.GetSupplyGoodListOne(orgId, warehouse.StorehouseOutId)

	goodTypeList, _ := service.GetAllGoodType(orgId)

	configlist, _ := service.GetAllStoreHouseConfig(orgId)
	var drugType = "药品类型"
	drugTypeParent, _ := service.GetDrugDataConfig(0, drugType)
	drugTypeList, _ := service.GetParentDataConfig(drugTypeParent.ID, orgId)

	list, _ := service.GetSencondOrderDetail(id, orgId)

	manufacturerList, _ := service.GetAllManufacturerList(orgId)
	this.ServeSuccessJSON(map[string]interface{}{
		"list":             list,
		"warehouse":        warehouse,
		"drugList":         baseList,
		"goodList":         goodList,
		"goodTypeList":     goodTypeList,
		"drugTypeList":     drugTypeList,
		"configlist":       configlist,
		"manufacturerList": manufacturerList,
	})
	return
}

func (this *SecondaryOrderApiController) UpdateSencondOrder() {

	warehouse_id, _ := this.GetInt64("id")
	start_date := this.GetString("record_date")
	storehouse_in_id, _ := this.GetInt64("storehouse_in_id")
	storehouse_out_id, _ := this.GetInt64("storehouse_out_id")
	fmt.Println(storehouse_in_id, storehouse_out_id)
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	var startDate int64
	if len(start_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_date+" 00:00:00", loc)
		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startDate = theTime.Unix()
	}

	recordDateStr := time.Now().Format("2006-01-02")
	recordDate, _ := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
	record_date := recordDate.Unix()
	orgId := this.GetAdminUserInfo().CurrentOrgId
	creater := this.GetAdminUserInfo().AdminUser.Id
	warehouse := models.XtSecondWarehouse{
		StorehouseInId:  storehouse_in_id,
		StorehouseOutId: storehouse_out_id,
		RecordDate:      startDate,
	}

	service.UpdateModifySecondWarehouse(warehouse_id, warehouse)

	warehouseInfo, _ := service.GetSecondWarehouseOrderById(warehouse_id)
	var warehousingInfo []*models.XtSecondWarehouseInfo

	var updateWarehousingInfo []*models.XtSecondWarehouseInfo
	dataBody := make(map[string]interface{}, 0)

	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	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["id"] == nil || reflect.TypeOf(items["id"]).String() != "float64" {
					utils.ErrorLog("id")
					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}

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

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

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

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

				project_name := items["name"].(string)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

				min_price := items["min_price"].(float64)

				if id == 0 {
					info := &models.XtSecondWarehouseInfo{
						ProjectName:             project_name,
						SecondSpecificationName: second_specification_name,
						ProjectType:             project_type,
						SencondUnit:             sencond_unit,
						Count:                   count,
						SecondTotal:             second_total,
						RecordDate:              record_date,
						StorehouseInId:          storehouse_in_id,
						StorehouseOutId:         storehouse_out_id,
						Creater:                 creater,
						ProjectId:               project_id,
						Remake:                  remake,
						UserOrgId:               orgId,
						Status:                  1,
						Ctime:                   time.Now().Unix(),
						Mtime:                   0,
						MinPrice:                min_price,
						IsSource:                is_source,
						WarehouseId:             warehouse_id,
						SecondOrderNumber:       warehouseInfo.SecondOrderNumber,
					}
					warehousingInfo = append(warehousingInfo, info)
				}

				if id > 0 {
					updateInfo := &models.XtSecondWarehouseInfo{
						ID:                      id,
						ProjectName:             project_name,
						SecondSpecificationName: second_specification_name,
						ProjectType:             project_type,
						SencondUnit:             sencond_unit,
						Count:                   count,
						SecondTotal:             second_total,
						SecondOrderNumber:       warehouse.SecondOrderNumber,
						RecordDate:              record_date,
						StorehouseInId:          storehouse_in_id,
						StorehouseOutId:         storehouse_out_id,
						Creater:                 creater,
						ProjectId:               project_id,
						Remake:                  remake,
						UserOrgId:               orgId,
						MinPrice:                min_price,
						IsSource:                is_source,
					}
					updateWarehousingInfo = append(updateWarehousingInfo, updateInfo)
				}

			}
		}
	}

	for _, item := range warehousingInfo {
		service.CreateSencondWarehousingInfo(item)
	}

	for _, item := range updateWarehousingInfo {
		service.UpdateStoreWarehousing(item)
	}

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

func (this *SecondaryOrderApiController) GetSecondOrderById() {

	id, _ := this.GetInt64("id")
	orgId := this.GetAdminUserInfo().CurrentOrgId
	warehouse, _ := service.GetSecondWarehouseOrderById(id)
	list, _ := service.GetSencondOrderDetail(id, orgId)
	appId := this.GetAdminUserInfo().CurrentAppId
	doctor, _ := service.GetAllDoctorSix(orgId, appId)
	houseList, _ := service.GetAllStoreHouseList(orgId)
	this.ServeSuccessJSON(map[string]interface{}{
		"warehouse":  warehouse,
		"list":       list,
		"doctorList": doctor,
		"houseList":  houseList,
	})
	return
}

func (this *SecondaryOrderApiController) CheckSecondOrer() {

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

	idArray := strings.Split(ids, ",")
	orgId := this.GetAdminUserInfo().CurrentOrgId
	creater := this.GetAdminUserInfo().AdminUser.Id

	//根据订单id获取商品详情
	list, _ := service.GetSecondOrderList(idArray, orgId)
	for _, item := range list {
		if item.IsSource == 1 {

			medical, _ := service.GetBaseDrugMedical(item.ProjectId)
			//查询该仓库的药品库存是否满足调出数量
			drugInfoList, _ := service.GetDrugWarehouseInfoByStoreHouseId(item.ProjectId, item.StorehouseOutId, item.UserOrgId)
			var total int64
			var total_count int64
			for _, it := range drugInfoList {
				if medical.MaxUnit == it.MaxUnit && medical.MaxUnit != medical.MinUnit {
					it.StockMaxNumber = it.StockMaxNumber * medical.MinNumber
				}
			}
			for _, it := range drugInfoList {
				total += it.StockMaxNumber + it.StockMinNumber
			}
			if item.SencondUnit == medical.MaxUnit && medical.MaxUnit != medical.MinUnit {
				total_count = item.Count * medical.MinNumber
			}
			if item.SencondUnit == medical.MinUnit {
				total_count = item.Count
			}

			if total_count > total {
				goodObj, _ := service.GetDrugByGoodId(item.ProjectId)
				storehouse, _ := service.FindStoreHouseByStorehouseId(item.StorehouseOutId, item.UserOrgId)
				this.ServeSuccessJSON(map[string]interface{}{
					"msg":            "3",
					"drug_name":      goodObj.DrugName,
					"dose":           goodObj.Dose,
					"dose_unit":      goodObj.DoseUnit,
					"min_number":     goodObj.MinNumber,
					"min_unit":       goodObj.MinUnit,
					"max_unit":       goodObj.MaxUnit,
					"storehose_name": storehouse.StorehouseName,
				})
				return
			}
		}

		if item.IsSource == 2 {
			//查询该仓库的耗材库存是否满足调出数量
			var total int64
			infoList, _ := service.GetWarehouseInfoByStoreHouseId(item.ProjectId, item.StorehouseOutId, item.UserOrgId)
			for _, it := range infoList {
				total += it.StockCount
			}
			if item.Count > total {
				storehouse, _ := service.FindStoreHouseByStorehouseId(item.StorehouseOutId, item.UserOrgId)
				goodObj, _ := service.GetGoodInformationByGoodId(item.ProjectId)
				this.ServeSuccessJSON(map[string]interface{}{
					"msg":                "2",
					"good_name":          goodObj.GoodName,
					"specification_name": goodObj.SpecificationName,
					"storehose_name":     storehouse.StorehouseName,
				})
				return
			}
		}
	}
	err := service.UpdateStoreOrderByArray(idArray, orgId, creater)
	//如果审核成功
	if err == nil {
		//调用出库接口
		timeStr := time.Now().Format("2006-01-02")
		timeArr := strings.Split(timeStr, "-")
		total, _ := service.FindAllWarehouseOut(orgId)

		total = total + 1
		warehousing_out_order := strconv.FormatInt(orgId, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
		number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
		number = number + total
		warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
		operation_time := time.Now().Unix()
		creater := this.GetAdminUserInfo().AdminUser.Id
		recordDateStr := time.Now().Format("2006-01-02")
		recordDate, _ := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
		record_date := recordDate.Unix()

		totals, _ := service.FindAllWarehouseTotal(orgId)
		totals = totals + 1
		warehousing_order := "RKD" + strconv.FormatInt(orgId, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000" + strconv.FormatInt(totals, 10)

		for _, item := range list {
			//药品
			if item.IsSource == 1 {
				medical, _ := service.GetBaseDrugMedical(item.ProjectId)
				//查询该仓库的药品库存是否满足调出数量
				drugInfoList, _ := service.GetDrugWarehouseInfoByStoreHouseId(item.ProjectId, item.StorehouseOutId, item.UserOrgId)
				var total int64
				var total_count int64
				for _, it := range drugInfoList {
					if medical.MaxUnit == it.MaxUnit && medical.MaxUnit != medical.MinUnit {
						it.StockMaxNumber = it.StockMaxNumber * medical.MinNumber
					}
				}
				for _, it := range drugInfoList {
					total += it.StockMaxNumber + it.StockMinNumber
				}
				if item.SencondUnit == medical.MaxUnit && medical.MaxUnit != medical.MinUnit {
					total_count = item.Count * medical.MinNumber
				}
				if item.SencondUnit == medical.MinUnit {
					total_count = item.Count
				}

				if total_count <= total {

					drug_total, _ := service.FindAllDrugWarehouseOut(orgId)

					drug_total = drug_total + 1
					drug_warehousing_out_order := strconv.FormatInt(orgId, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
					number, _ := strconv.ParseInt(drug_warehousing_out_order, 10, 64)
					number = number + drug_total
					drug_warehousing_out_order = "YPCKD" + strconv.FormatInt(number, 10)
					operation_time := time.Now().Unix()

					drugWarehouseOut := models.DrugWarehouseOut{
						WarehouseOutOrderNumber: drug_warehousing_out_order,
						OperationTime:           operation_time,
						OrgId:                   orgId,
						Creater:                 creater,
						Ctime:                   time.Now().Unix(),
						Status:                  1,
						WarehouseOutTime:        record_date,
						Type:                    2,
						StorehouseId:            item.StorehouseOutId,
						SecondWarehouseId:       item.WarehouseId,
						IsSys:                   12,
						IsCheck:                 1,
					}
					_, drugerrcodes := service.GetDrugWarehouseBySyS(orgId, 12, item.WarehouseId, record_date)

					if drugerrcodes == gorm.ErrRecordNotFound {
						service.AddSigleDrugWarehouseOut(&drugWarehouseOut)
					}

					drugOut, _ := service.GetLastDrugWarehouseOutById(12, item.WarehouseId, orgId, record_date)

					warehouseOutInfo := &models.DrugWarehouseOutInfo{
						WarehouseOutOrderNumber: drugOut.WarehouseOutOrderNumber,
						WarehouseOutId:          drugOut.ID,
						DrugId:                  item.ProjectId,
						Count:                   item.Count,
						Price:                   medical.RetailPrice,
						TotalPrice:              0,
						Status:                  1,
						Ctime:                   time.Now().Unix(),
						Remark:                  item.Remake,
						OrgId:                   orgId,
						Type:                    2,
						Manufacturer:            0,
						Dealer:                  0,
						RetailPrice:             item.MinPrice,
						RetailTotalPrice:        0,
						CountUnit:               item.SencondUnit,
						ExpiryDate:              0,
						ProductDate:             0,
						Number:                  "",
						BatchNumber:             "",
						IsSys:                   0,
						WarehouseInfoId:         0,
						StorehouseId:            item.StorehouseOutId,
						SecondWarehouseInfoId:   item.ID,
						IsCheck:                 1,
					}
					drup, _ := service.FindBaseDrugLibRecord(orgId, item.ProjectId)

					drug_in_total, _ := service.FindAllWarehouseTotalOne(orgId)
					drug_in_total = drug_in_total + 1

					warehousing_order := "YPRKD" + strconv.FormatInt(orgId, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000" + strconv.FormatInt(drug_in_total, 10)

					drug_warehousing := models.DrugWarehouse{
						WarehousingOrder:  warehousing_order,
						OperationTime:     operation_time,
						OrgId:             orgId,
						Creater:           creater,
						Ctime:             time.Now().Unix(),
						Status:            1,
						WarehousingTime:   record_date,
						Type:              1,
						StorehouseId:      item.StorehouseInId,
						IsSys:             13,
						SecondWarehouseId: item.WarehouseId,
						IsCheck:           1,
					}

					//查询该调拨单是否有生成入库单
					_, drugerrcodess := service.GetDrugWarehouseingBySys(13, item.WarehouseId, orgId, record_date)
					if drugerrcodess == gorm.ErrRecordNotFound {
						service.CreateDrugWaresing(drug_warehousing)
					}

					drugInfoObj, _ := service.GetLastDrugWarehouseBySys(13, item.WarehouseId, orgId, record_date)

					drugwarehouseInfo := &models.DrugWarehouseInfo{
						WarehousingOrder:      drugInfoObj.WarehousingOrder,
						WarehousingId:         drugInfoObj.ID,
						DrugId:                item.ProjectId,
						Number:                "",
						ProductDate:           0,
						ExpiryDate:            0,
						WarehousingCount:      0,
						Price:                 0,
						TotalPrice:            0,
						Status:                1,
						Ctime:                 time.Now().Unix(),
						Remark:                "",
						OrgId:                 orgId,
						Type:                  2,
						Manufacturer:          0,
						Dealer:                0,
						StockMaxNumber:        0,
						RetailTotalPrice:      0,
						BatchNumber:           "",
						MaxUnit:               "",
						MinUnit:               "",
						RetailPrice:           0,
						StorehouseId:          item.StorehouseInId,
						SecondWarehouseInfoId: item.ID,
						IsCheck:               1,
					}
					service.AutoDrugDeliverInfoTwelve(orgId, item.Count, &drugWarehouseOut, &drup, warehouseOutInfo, drugwarehouseInfo)

					//查询默认仓库
					storeHouseConfig, _ := service.GetAllStoreHouseConfig(orgId)
					//更新字典里面的库存
					stockInfo, _ := service.GetDrugAllStockInfo(storeHouseConfig.DrugStorehouseOut, item.UserOrgId, item.ProjectId)
					var sum_count int64
					for _, its := range stockInfo {
						sum_count += its.StockMaxNumber*medical.MinNumber + its.StockMinNumber
					}
					service.UpdateBaseDrugSumTwo(item.ProjectId, sum_count, item.UserOrgId)
				}
			}

			//耗材
			if item.IsSource == 2 {

				//查询该仓库的耗材库存是否满足调出数量
				var total int64
				infoList, _ := service.GetWarehouseInfoByStoreHouseId(item.ProjectId, item.StorehouseOutId, item.UserOrgId)
				for _, it := range infoList {
					total += it.StockCount
				}
				//满足调拨
				if item.Count <= total {
					goodObj, _ := service.GetGoodInformationByGoodId(item.ProjectId)
					warehouseOut := models.WarehouseOut{
						WarehouseOutOrderNumber: warehousing_out_order,
						OperationTime:           operation_time,
						OrgId:                   orgId,
						Creater:                 creater,
						Ctime:                   time.Now().Unix(),
						Status:                  1,
						WarehouseOutTime:        record_date,
						Type:                    1,
						StorehouseId:            item.StorehouseOutId,
						IsSys:                   12,
						SecondWarehouseId:       item.WarehouseId,
						IsCheck:                 1,
					}

					//查询今日是否存在调拨出库
					_, errcodes := service.FindStockOutByIsSysSix(orgId, 12, record_date, item.WarehouseId)
					if errcodes == gorm.ErrRecordNotFound {
						service.AddSigleWarehouseOut(&warehouseOut)
					}

					out, _ := service.GetLastWarehouseOutBySys(12, orgId, record_date, item.WarehouseId)
					warehouseOutInfo := &models.WarehouseOutInfo{
						WarehouseOutOrderNumber: out.WarehouseOutOrderNumber,
						WarehouseOutId:          out.ID,
						GoodId:                  item.ProjectId,
						GoodTypeId:              goodObj.GoodTypeId,
						Count:                   item.Count,
						Price:                   item.MinPrice,
						TotalPrice:              0,
						Status:                  1,
						Ctime:                   time.Now().Unix(),
						Remark:                  item.Remake,
						OrgId:                   orgId,
						Type:                    1,
						Manufacturer:            0,
						Number:                  "",
						ExpiryDate:              0,
						ProductDate:             0,
						Dealer:                  0,
						LicenseNumber:           "",
						WarehouseInfotId:        0,
						StorehouseId:            item.StorehouseOutId,
						SecondWarehouseInfoId:   item.ID,
						IsCheck:                 1,
					}

					//入库操作
					warehousing := models.Warehousing{
						WarehousingOrder:  warehousing_order,
						OperationTime:     operation_time,
						OrgId:             orgId,
						Creater:           creater,
						Ctime:             time.Now().Unix(),
						Status:            1,
						WarehousingTime:   record_date,
						Type:              1,
						StorehouseId:      item.StorehouseInId,
						IsSys:             12,
						SecondWarehouseId: item.WarehouseId,
						IsCheck:           1,
					}
					//查询该调拨单是否有生成入库单
					_, errcodess := service.GetWarehouseBySecondWarehouseId(12, item.WarehouseId, orgId, record_date)
					if errcodess == gorm.ErrRecordNotFound {
						service.AddSigleWarehouse(&warehousing)
					}
					infoObj, _ := service.GetLastWarehouseById(12, item.WarehouseId, orgId, record_date)

					warehouseInfo := &models.WarehousingInfo{
						WarehousingOrder:      infoObj.WarehousingOrder,
						WarehousingId:         infoObj.ID,
						GoodId:                item.ProjectId,
						Number:                "",
						GoodTypeId:            goodObj.GoodTypeId,
						ProductDate:           0,
						ExpiryDate:            0,
						WarehousingCount:      item.Count,
						Price:                 goodObj.BuyPrice,
						TotalPrice:            0,
						Status:                1,
						Ctime:                 time.Now().Unix(),
						Remark:                item.Remake,
						OrgId:                 orgId,
						Type:                  1,
						Manufacturer:          0,
						StockCount:            item.Count,
						Dealer:                0,
						LicenseNumber:         "",
						PackingPrice:          item.MinPrice,
						StorehouseId:          item.StorehouseInId,
						SecondWarehouseInfoId: item.ID,
						IsCheck:               1,
					}

					//出库逻辑
					parseDateErr := service.ConsumablesDeliveryTwelve(orgId, record_date, warehouseOutInfo, &warehouseOut, item.Count, creater, warehouseInfo)
					fmt.Println(parseDateErr)

				}

				//查询默认仓库
				storeHouseConfig, _ := service.GetAllStoreHouseConfig(orgId)
				stockList, _ := service.GetStockCountByGoodId(item.ProjectId, storeHouseConfig.StorehouseOutInfo, orgId)
				var total_count int64
				for _, it := range stockList {
					total_count += it.StockCount
				}
				//基础库插入数据
				service.UpdateGoodInfoSumCount(item.ProjectId, total_count, orgId)
			}
		}
	}

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

func (this *SecondaryOrderApiController) DeleteStorehouseList() {

	id, _ := this.GetInt64("id")
	err := service.DeleteStorehouseList(id)
	if err == nil {
		returnData := make(map[string]interface{}, 0)
		returnData["msg"] = "ok"
		this.ServeSuccessJSON(returnData)
		return
	} else {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}

func (this *SecondaryOrderApiController) ReturnCheckSecondOrder() {

	ids := this.GetString("ids")

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

	idArray := strings.Split(ids, ",")
	orgId := this.GetAdminUserInfo().CurrentOrgId

	//根据订单id获取商品详情
	list, _ := service.GetSecondOrderList(idArray, orgId)
	//药品
	for _, item := range list {
		//药品
		if item.IsSource == 1 {
			medical, _ := service.GetBaseDrugMedical(item.ProjectId)
			//查询该仓库的药品库存是否满足调出数量
			drugInfoList, _ := service.GetDrugWarehouseInfoByStoreHouseIdOne(item.ProjectId, item.StorehouseInId, item.UserOrgId, item.ID)
			var total int64
			var total_count int64
			for _, it := range drugInfoList {
				if medical.MaxUnit == it.MaxUnit && medical.MaxUnit != medical.MinUnit {
					it.StockMaxNumber = it.StockMaxNumber * medical.MinNumber
				}
			}
			for _, it := range drugInfoList {
				total += it.StockMaxNumber + it.StockMinNumber
			}
			if item.SencondUnit == medical.MaxUnit && medical.MaxUnit != medical.MinUnit {
				total_count = item.Count * medical.MinNumber
			}
			if item.SencondUnit == medical.MinUnit {
				total_count = item.Count
			}

			if total_count > total {
				goodObj, _ := service.GetDrugByGoodId(item.ProjectId)
				storehouse, _ := service.FindStoreHouseByStorehouseId(item.StorehouseInId, item.UserOrgId)
				this.ServeSuccessJSON(map[string]interface{}{
					"msg":            "3",
					"drug_name":      goodObj.DrugName,
					"dose":           goodObj.Dose,
					"dose_unit":      goodObj.DoseUnit,
					"min_number":     goodObj.MinNumber,
					"min_unit":       goodObj.MinUnit,
					"max_unit":       goodObj.MaxUnit,
					"storehose_name": storehouse.StorehouseName,
				})
				return
			}
		}

		//耗材
		if item.IsSource == 2 {
			//查询该仓库的耗材库存是否满足调出数量
			var total int64
			infoList, _ := service.GetWarehouseInfoByStoreHouseIdOne(item.ProjectId, item.StorehouseInId, item.UserOrgId, item.ID)
			for _, it := range infoList {
				total += it.StockCount
			}
			if item.Count > total {
				storehouse, _ := service.FindStoreHouseByStorehouseId(item.StorehouseInId, item.UserOrgId)
				goodObj, _ := service.GetGoodInformationByGoodId(item.ProjectId)
				this.ServeSuccessJSON(map[string]interface{}{
					"msg":                "2",
					"good_name":          goodObj.GoodName,
					"specification_name": goodObj.SpecificationName,
					"storehose_name":     storehouse.StorehouseName,
				})
				return
			}
		}
	}
	//反审核操作
	err := service.ModifyStoreHouseById(idArray, orgId)
	if err != nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"msg": "0",
		})
		return
	}

	for _, item := range list {

		//药品
		if item.IsSource == 1 {

			medical, _ := service.GetBaseDrugMedical(item.ProjectId)
			//查询该仓库的药品库存是否满足调出数量
			drugInfoList, _ := service.GetDrugWarehouseInfoByStoreHouseIdOne(item.ProjectId, item.StorehouseInId, item.UserOrgId, item.ID)
			var total int64
			var total_count int64
			for _, it := range drugInfoList {
				if medical.MaxUnit == it.MaxUnit && medical.MaxUnit != medical.MinUnit {
					it.StockMaxNumber = it.StockMaxNumber * medical.MinNumber
				}
			}
			for _, it := range drugInfoList {
				total += it.StockMaxNumber + it.StockMinNumber
			}
			if item.SencondUnit == medical.MaxUnit && medical.MaxUnit != medical.MinUnit {
				total_count = item.Count * medical.MinNumber
			}
			if item.SencondUnit == medical.MinUnit {
				total_count = item.Count
			}

			if total_count <= total {

				//回退库存,查询该订单出库记录
				drugOutList, _ := service.GetStoreDrugWarehouseOutList(item.ProjectId, item.ID, item.UserOrgId)
				for _, it := range drugOutList {

					if medical.MaxUnit == it.CountUnit && medical.MaxUnit != medical.MinUnit {
						//回退库存
						service.ModifyDrugStoreWarehouseInfo(it.WarehouseInfoId, it.Count)
					}

					if medical.MaxUnit == it.CountUnit && medical.MaxUnit == medical.MinUnit {
						//回退库存
						service.ModifyDrugStoreWarehouseInfo(it.WarehouseInfoId, it.Count)
					}

					if medical.MinUnit == it.CountUnit && medical.MaxUnit != medical.MinUnit {

						service.ModifyDrugStoreWarehouseInfoOne(it.WarehouseInfoId, it.Count)
					}

					//查询入库单
					storeWareing, _ := service.GetStoreDrugWarehouseById(item.WarehouseId, it.OrgId)
					//删除入库单
					service.DeleteStoreWarehousingId(storeWareing.ID, storeWareing.OrgId, item.ProjectId)

					//查询出单
					storeWarehouseOut, _ := service.GetStoreDrugWarehouseOutById(it.WarehouseOutId, it.OrgId)

					//删除出库单
					service.DeleteStoreWarehouseOut(storeWarehouseOut.ID, storeWarehouseOut.OrgId, item.ProjectId)
				}

			}

			storeHouseConfig, _ := service.GetAllStoreHouseConfig(orgId)
			var sum_count int64
			stockInfo, _ := service.GetDrugAllStockInfo(storeHouseConfig.DrugStorehouseOut, item.UserOrgId, item.ProjectId)
			for _, its := range stockInfo {
				sum_count += its.StockMaxNumber*medical.MinNumber + its.StockMinNumber
			}
			service.UpdateBaseDrugSumTwo(item.ProjectId, sum_count, item.UserOrgId)
		}

		//耗材
		if item.IsSource == 2 {
			//查询该仓库的耗材库存是否满足调出数量
			var total int64
			infoList, _ := service.GetWarehouseInfoByStoreHouseIdOne(item.ProjectId, item.StorehouseInId, item.UserOrgId, item.ID)
			for _, it := range infoList {
				total += it.StockCount
			}
			//满足调拨
			if item.Count <= total {

				//回退库存,查询该订单出库记录
				outList, _ := service.GetStoreWarehouseOutList(item.ProjectId, item.ID, item.UserOrgId)
				for _, it := range outList {
					//回退库存
					service.ModifyStoreWarehouseById(it.WarehouseInfotId, it.Count)

					//获取入库单
					storeWareing, _ := service.GetStoreWarehouseById(item.WarehouseId, it.OrgId)
					//删除入库单 入库流水
					service.ModifyStoreWarehouse(storeWareing.ID, storeWareing.OrgId, item.ProjectId)
					//获取出库单
					storeWarehouseOut, _ := service.GetStoreWarehouseOutById(it.WarehouseOutId, it.OrgId)
					//删除出库单
					service.ModifyWarehouseOut(storeWarehouseOut.ID, storeWarehouseOut.OrgId, item.ProjectId)
				}
			}

			//查询默认仓库
			storeHouseConfig, _ := service.GetAllStoreHouseConfig(orgId)
			stockList, _ := service.GetStockCountByGoodId(item.ProjectId, storeHouseConfig.StorehouseOutInfo, orgId)
			var total_count int64
			for _, it := range stockList {
				total_count += it.StockCount
			}
			//基础库插入数据
			service.UpdateGoodInfoSumCount(item.ProjectId, total_count, orgId)

		}
	}

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

func (this *SecondaryOrderApiController) GetStoreHouseGoodList() {

	storehouse_out_id, _ := this.GetInt64("storehouse_out_id")
	orgId := this.GetAdminUserInfo().CurrentOrgId
	//获取药品库数据
	baseList, _ := service.GetSupplyDrugListOne(orgId, storehouse_out_id)

	goodList, _ := service.GetSupplyGoodListOne(orgId, storehouse_out_id)

	goodTypeList, _ := service.GetAllGoodType(orgId)

	configlist, _ := service.GetAllStoreHouseConfig(orgId)

	manufacturerList, _ := service.GetAllManufacturerList(orgId)
	var drugType = "药品类型"
	drugTypeParent, _ := service.GetDrugDataConfig(0, drugType)
	drugTypeList, _ := service.GetParentDataConfig(drugTypeParent.ID, orgId)
	this.ServeSuccessJSON(map[string]interface{}{
		"drugList":         baseList,
		"goodList":         goodList,
		"goodTypeList":     goodTypeList,
		"drugTypeList":     drugTypeList,
		"configlist":       configlist,
		"manufacturerList": manufacturerList,
	})
	return
}

func (this *SecondaryOrderApiController) GetSumSecondCount() {

	project_id, _ := this.GetInt64("project_id")
	sencond_unit := this.GetString("sencond_unit")

	is_source, _ := this.GetInt64("is_source")
	count, _ := this.GetInt64("count")
	storehouse_out_id, _ := this.GetInt64("storehouse_out_id")
	orgId := this.GetAdminUserInfo().CurrentOrgId
	var sum_in_count int64
	var sum_count int64
	//药品
	if is_source == 1 {

		medical, _ := service.GetBaseDrugMedical(project_id)
		fmt.Println("senconde_unit233223", sencond_unit)
		if sencond_unit == medical.MaxUnit {
			sum_in_count = count * medical.MinNumber
		}
		if sencond_unit == medical.MinUnit && medical.MaxUnit != medical.MinUnit {
			sum_in_count = count
		}
		//查询该药品剩余的库存
		secondCountList, _ := service.GetDrugSumSecondCount(project_id, storehouse_out_id, orgId)

		for _, it := range secondCountList {
			if it.MaxUnit == medical.MaxUnit {
				sum_count += (it.StockMaxNumber * medical.MinNumber) + it.StockMinNumber
			}
			if it.MaxUnit == medical.MinUnit && medical.MaxUnit != medical.MinUnit {
				sum_count += (it.StockMaxNumber + it.StockMinNumber)
			}
		}
		fmt.Println("sum_iin_coutn23232323", sum_in_count)
		fmt.Println("sum_count", sum_count)
		if sum_in_count > sum_count {
			this.ServeSuccessJSON(map[string]interface{}{
				"msg": "2",
			})
			return
		} else {
			this.ServeSuccessJSON(map[string]interface{}{
				"msg": "1",
			})
			return
		}
	}

	//耗材
	if is_source == 2 {
		var sum_good_count int64
		secondCountGoodList, _ := service.GetGoodSumSecondCount(project_id, storehouse_out_id, orgId)
		for _, it := range secondCountGoodList {
			sum_good_count += it.StockCount
		}
		if count > sum_good_count {
			this.ServeSuccessJSON(map[string]interface{}{
				"msg": "2",
			})
			return
		} else {
			this.ServeSuccessJSON(map[string]interface{}{
				"msg": "1",
			})
			return
		}
	}
}

func (this *SecondaryOrderApiController) DeleteSecondOrderInfo() {

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

	err := service.DeleteSecondOrderInfo(id)
	if err == nil {
		returnData := make(map[string]interface{}, 0)
		returnData["msg"] = "ok"
		this.ServeSuccessJSON(returnData)
		return
	} else {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	}
}

//查询一条仓库信息
func (this *SecondaryOrderApiController) GetOneStorehouse() {
	orgId := this.GetAdminUserInfo().CurrentOrgId
	check := map[string][]string{
		"id": {"must", "int", "id"},
	}
	_, err := checkParams(this, &check)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	id, _ := this.GetInt64("id")
	var list models.Storehouse
	list, err = service.GetOneStorehouse(id, orgId)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": list,
	})
	return
}

//获取当前机构所有可用仓库的名字
func (this *SecondaryOrderApiController) GetAllStorehouseName() {
	orgId := this.GetAdminUserInfo().CurrentOrgId
	list, err := service.GetAllStorehouseName(orgId)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": list,
	})

}

//根据机构id查询仓库配置
func (this *SecondaryOrderApiController) FindStorehouseConfig() {
	orgId := this.GetAdminUserInfo().CurrentOrgId
	storehouse, err := service.FindStorehouseConfig(orgId)
	//如果没有仓库配置信息就新建一个
	if err == gorm.ErrRecordNotFound {
		err := service.GetDefaultStorehouse(orgId)
		if err != nil {
			this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
			return
		}
		storehouse, err = service.FindStorehouseConfig(orgId)
		if err != nil {
			this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
			return
		}
	}
	if err != nil && err.Error() != "record not found" {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	var storehouse_info, storehouse_out_info, drug_storehouse_info, drug_storehouse_out models.Storehouse
	storehouse_info, err = service.FindStorehouseName(storehouse.StorehouseInfo)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	storehouse_out_info, err = service.FindStorehouseName(storehouse.StorehouseOutInfo)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	drug_storehouse_info, err = service.FindStorehouseName(storehouse.DrugStorehouseInfo)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	drug_storehouse_out, err = service.FindStorehouseName(storehouse.DrugStorehouseOut)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"storehouse_info":      storehouse_info.StorehouseName,
		"storehouse_out_info":  storehouse_out_info.StorehouseName,
		"drug_storehouse_info": drug_storehouse_info.StorehouseName,
		"drug_storehouse_out":  drug_storehouse_out.StorehouseName,
	})
	return
}

//更改耗材自动入库仓库
func (this *SecondaryOrderApiController) UpdateInfo() {
	orgId := this.GetAdminUserInfo().CurrentOrgId
	check := map[string][]string{
		"id": {"must", "int", "id"},
	}
	_, err := checkParams(this, &check)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	id, _ := this.GetInt64("id")
	err = service.UpdateInfo(orgId, id)

	//查询默认仓库
	houseConfig, _ := service.GetAllStoreHouseConfig(orgId)

	list, _ := service.GetAllGoodList(orgId)
	for _, item := range list {
		var sum_count int64
		var sum_in_count int64
		goodList, _ := service.GetGoodSumCountByStoreId(houseConfig.StorehouseOutInfo, item.ID, orgId)
		for _, it := range goodList {
			sum_count += it.StockCount
			sum_in_count += it.WarehousingCount
		}
		service.UpdateGoodByGoodId(item.ID, sum_count, sum_in_count, orgId)
	}

	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": "修改成功",
	})
	return

}

//更改耗材自动出库仓库
func (this *SecondaryOrderApiController) UpdateOutInfo() {
	orgId := this.GetAdminUserInfo().CurrentOrgId
	check := map[string][]string{
		"id": {"must", "int", "id"},
	}
	_, err := checkParams(this, &check)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	id, _ := this.GetInt64("id")
	err = service.UpdateOutInfo(orgId, id)

	//查询默认仓库
	houseConfig, _ := service.GetAllStoreHouseConfig(orgId)

	list, _ := service.GetAllGoodList(orgId)
	for _, item := range list {
		var sum_count int64
		var sum_in_count int64
		goodList, _ := service.GetGoodSumCountByStoreId(houseConfig.StorehouseOutInfo, item.ID, orgId)
		for _, it := range goodList {
			sum_count += it.StockCount
			sum_in_count += it.WarehousingCount
		}
		service.UpdateGoodByGoodId(item.ID, sum_count, sum_in_count, orgId)
	}

	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": "修改成功",
	})
	return

}

//更改药品自动入库仓库
func (this *SecondaryOrderApiController) UpdateDrugInfo() {
	orgId := this.GetAdminUserInfo().CurrentOrgId
	check := map[string][]string{
		"id": {"must", "int", "id"},
	}
	_, err := checkParams(this, &check)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	id, _ := this.GetInt64("id")

	err = service.UpdateDrugInfo2(orgId, id)

	//查询默认仓库
	houseConfig, _ := service.GetAllStoreHouseConfig(orgId)
	baseDrug, _ := service.GetAllBaseDrugList(orgId)

	for _, item := range baseDrug {
		var sum_drug_count int64
		var sum_drug_in_count int64

		//查询默认仓库剩余多少库存
		list, _ := service.GetDrugSumCountByStorehouseId(houseConfig.DrugStorehouseOut, orgId, item.ID)
		for _, it := range list {
			if it.MaxUnit == item.MaxUnit {
				it.StockMaxNumber = it.StockMaxNumber * item.MinNumber
				it.WarehousingCount = it.WarehousingCount * item.MinNumber
			}
			sum_drug_count += it.StockMaxNumber + it.StockMinNumber
			sum_drug_in_count += it.WarehousingCount
		}
		service.UpdateMedicalSumCount(item.ID, sum_drug_count, sum_drug_in_count, orgId)
	}

	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": "修改成功",
	})
	return

}

//更改药品自动出库仓库
func (this *SecondaryOrderApiController) UpdateDrugOut() {
	orgId := this.GetAdminUserInfo().CurrentOrgId
	check := map[string][]string{
		"id": {"must", "int", "id"},
	}
	_, err := checkParams(this, &check)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	id, _ := this.GetInt64("id")
	err = service.UpdateDrugOut(orgId, id)

	//查询默认仓库
	houseConfig, _ := service.GetAllStoreHouseConfig(orgId)
	baseDrug, _ := service.GetAllBaseDrugList(orgId)

	for _, item := range baseDrug {
		var sum_drug_count int64
		var sum_drug_in_count int64

		//查询默认仓库剩余多少库存
		list, _ := service.GetDrugSumCountByStorehouseId(houseConfig.DrugStorehouseOut, orgId, item.ID)
		for _, it := range list {
			if it.MaxUnit == item.MaxUnit {
				it.StockMaxNumber = it.StockMaxNumber * item.MinNumber
				it.WarehousingCount = it.WarehousingCount * item.MinNumber
			}
			sum_drug_count += it.StockMaxNumber + it.StockMinNumber
			sum_drug_in_count += it.WarehousingCount
		}
		service.UpdateMedicalSumCount(item.ID, sum_drug_count, sum_drug_in_count, orgId)
	}

	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": "修改成功",
	})
	return

}

//判断前端参数是否为空
func checkParams(this *SecondaryOrderApiController, m *map[string][]string) (map[string]string, error) {
	tmp := make(map[string]string)
	for k, v := range *m {
		t := this.GetString(k)
		if v[0] == "must" && t == "" {
			return nil, fmt.Errorf(v[2] + "不能为空")
		}
		tmp[k] = t
	}
	return tmp, nil
}

//兼容旧数据
func (this *SecondaryOrderApiController) Byliinit() {
	err := service.Byliinit()
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": "初始化成功",
	})
	return
}

//查询机构所属管理员
func (this *SecondaryOrderApiController) GetuserName() {
	adminUserInfo := this.GetAdminUserInfo()
	viewModels, _, _ := service.GetAdminUsersAndLoginInfo(adminUserInfo.CurrentOrgId, adminUserInfo.CurrentAppId, 1, 100)
	//viewModels, _, _ := service.GetAdminUsersAndLoginInfo(10164, 12123, 1, 100)
	c, _ := service.Getcreateid(adminUserInfo.CurrentOrgId)
	//c, _ := service.Getcreateid(10164)
	admin := []*service.AdminUserManageViewModel{} //记录当前管理员的信息
	//去除禁用的角色
	tmp := []*service.AdminUserManageViewModel{}
	for i := 0; i < len(viewModels); i++ {
		if viewModels[i].Status == 1 {
			tmp = append(tmp, viewModels[i])
		}
		if int64(viewModels[i].AdminUserId) == c.Creator {
			admin = append(admin, viewModels[i])
		}
	}
	roles := service.FindRoles(adminUserInfo.CurrentOrgId)
	//roles := service.FindRoles(10164)
	//去除没有权限的角色
	tmplist := []*service.AdminUserManageViewModel{}
	if roles == nil || len(roles) == 0 {
		this.ServeSuccessJSON(map[string]interface{}{
			"list": admin,
		})
		return
	}
	for i := 0; i < len(tmp); i++ {
		boolean := false
		//获取并解析当前用户的角色
		tmproles := strings.Split(tmp[i].RoleIds, ",")
		for j := 0; j < len(tmproles); j++ {
			//判断这些角色是否有权限
			if _, ok := roles[tmproles[j]]; ok {
				boolean = true
			}
		}
		if boolean {
			tmplist = append(tmplist, tmp[i])
		}
	}
	isappend := true //判断结果中是否添加机构创建者，true添加，false不添加
	if len(tmplist) > 0 {
		for i := 0; i < len(tmplist); i++ {
			if int64(tmplist[i].AdminUserId) == c.Creator {
				isappend = false
			}
		}
	}
	if isappend {
		tmplist = append(tmplist, admin...)
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": tmplist,
	})
	return
}

func (this *SecondaryOrderApiController) GetCreaterId() {
	creater := this.GetAdminUserInfo().AdminUser.Id
	this.ServeSuccessJSON(map[string]interface{}{
		"list": creater,
	})
}
