package service

import (
	"XT_New/models"
	"XT_New/utils"
	"fmt"
	"github.com/jinzhu/gorm"
	"math/rand"
	"strconv"
	"time"
)

//生成编号，规则为:"SH-"+4位随机数
func CreateCode() string {
	s := fmt.Sprintf("%04v", rand.New(rand.NewSource(time.Now().UnixNano())).Int63n(10000))
	code := "SH-" + s
	return code
}

//查询仓库名称是否重复(用于修改)
func IsStorehouseNameUp(orgid, id int64, storehouse_name string) (bool, error) {
	var total int
	var tmp bool
	err := XTReadDB().Model(&models.Storehouse{}).Where("storehouse_name = ? and user_org_id = ? and status = 1 and id != ?", storehouse_name, orgid, id).Count(&total).Error
	if total > 0 {
		tmp = true //有重复的
	} else {
		tmp = false
	}
	return tmp, err
}

//查询仓库地址是否重复（用于修改）
func IsStorehouseAddressUp(orgid, id int64, storehouse_address string) (bool, error) {
	var total int
	var tmp bool
	err := XTReadDB().Model(&models.Storehouse{}).Where("storehouse_address = ? and user_org_id = ? and status = 1 and id != ?", storehouse_address, orgid, id).Count(&total).Error
	if total > 0 {
		tmp = true //有重复的
	} else {
		tmp = false
	}
	return tmp, err
}

//查询编号是否重复
func FindStorehouseCode(orgid int64, code string) bool {
	var total int
	XTReadDB().Model(&models.Storehouse{}).Where(" storehouse_code = ? and user_org_id = ? and status = 1", code, orgid).Count(&total)
	if total > 0 {
		return true
	} else {
		return false
	}
}

//判断仓库的库存是否为零 true为零，false不为零
func IsStorehouseNil(id, orgid int64) bool { //根据 id gro_id 查为零的库存
	var h, y int
	//判断耗材是否为零
	XTReadDB().Model(&models.WarehousingInfo{}).Where("stock_count > 0 and status = 1 and org_id = ? and storehouse_id = ?", orgid, id).Count(&h)
	if h > 0 {
		return false
	}
	//判断药品是否为零
	XTReadDB().Model(&models.XtDrugWarehouseInfo{}).Where("stock_max_number > 0 or stock_min_number > 0 ").Where(" org_id = ? and storehouse_id = ?", orgid, id).Count(&y)
	if y > 0 {
		return false
	}
	return true
}

//修改仓库状态
func UpdateStorehouseStatus(id int64) error {
	err := XTWriteDB().Exec("UPDATE xt_storehouse,(SELECT CASE storehouse_status WHEN 1 THEN 0 WHEN 0 THEN 1 END AS tt FROM xt_storehouse WHERE id=?)tmp SET storehouse_status = tmp.tt where id=?", id, id).Error
	return err
}

//删除仓库
func DeleteStorehouse(id int64) error {
	err := XTWriteDB().Model(&models.Storehouse{}).Where("id = ?", id).Update("status", 0).Error
	return err
}

//查询仓库名称是否重复
func IsStorehouseName(orgid int64, storehouse_name string) (bool, error) {
	var total int
	var tmp bool
	err := XTReadDB().Model(&models.Storehouse{}).Where("storehouse_name = ? and user_org_id = ? and status = 1", storehouse_name, orgid).Count(&total).Error
	if total > 0 {
		tmp = true //有重复的
	} else {
		tmp = false
	}
	return tmp, err
}

//查询仓库地址是否重复
func IsStorehouseAddress(orgid int64, storehouse_address string) (bool, error) {
	var total int
	var tmp bool
	err := XTReadDB().Model(&models.Storehouse{}).Where("storehouse_address = ? and user_org_id = ? and status = 1", storehouse_address, orgid).Count(&total).Error
	if total > 0 {
		tmp = true //有重复的
	} else {
		tmp = false
	}
	return tmp, err
}

//新增仓库
func AddStroehouse(storehouse models.Storehouse) (shiwu string, err error) {
	tx := XTWriteDB().Begin()
	defer func() {
		if err != nil {
			utils.ErrorLog("事务失败，原因为: %v", err)
			shiwu = "失败"
			tx.Rollback()
		} else {
			shiwu = "成功"
			tx.Commit()
		}
	}()
	//创建仓库
	err = tx.Create(&storehouse).Error
	if err != nil {
		return shiwu, err
	}
	utils.ErrorLog("创建仓库成功")
	var id models.Storehouse
	//获取创建仓库的id
	err = tx.Model(&models.Storehouse{}).Select("id").Where("status = 1 and user_org_id = ?", storehouse.UserOrgId).Order("id desc").First(&id).Error
	if err != nil {
		return shiwu, err
	}

	//判断是否存在仓库配置
	boolean := IsStorehouseconfigXT(storehouse.UserOrgId, tx)
	if boolean == false {
		//创建仓库配置
		err = CreateStorehouseConfigXT(storehouse.UserOrgId, id.ID, tx)
		if err != nil {
			utils.ErrorLog("仓库配置失败")
			return shiwu, err
		}
	} else {
		utils.ErrorLog("仓库配置已存在")
	}
	utils.ErrorLog("结束")
	return shiwu, err
}

//修改仓库
func UpdateStroehouse(storehouse models.Storehouse) error {
	err := XTWriteDB().Model(&models.Storehouse{}).Where("id = ? and status = 1", storehouse.ID).Updates(
		map[string]interface{}{
			"storehouse_name":     storehouse.StorehouseName,
			"storehouse_address":  storehouse.StorehouseAddress,
			"storehouse_status":   storehouse.StorehouseStatus,
			"storehouse_admin_id": storehouse.StorehouseAdminId,
			"mtime":               storehouse.Mtime,
		}).Error
	return err
}

//查询一条仓库的信息
func GetOneStorehouse(id, orgid int64) (storehouse models.Storehouse, err error) {
	err = XTReadDB().Model(&models.Storehouse{}).Where("id = ? and user_org_id = ?", id, orgid).Find(&storehouse).Error
	return
}

//分页
func StorehouseList(page, limit, orgid int64, keyword string, slicekey []int64) (storehouse []models.Storehouse, total int64, err error) {
	db := XTReadDB().Model(&storehouse).Where("status = 1 and user_org_id = ?", orgid)
	offset := (page - 1) * limit
	if len(keyword) > 0 {
		var adminid string = "storehouse_code like ? or storehouse_name like ? or storehouse_address like ? "
		if len(slicekey) > 0 {
			for i := 0; i < len(slicekey); i++ {
				adminid = adminid + " or storehouse_admin_id =" + strconv.FormatInt(slicekey[i], 10)
			}
		}
		keyword = "%" + keyword + "%"
		db = db.Where(adminid, keyword, keyword, keyword)
	}
	err = db.Count(&total).Offset(offset).Order("id").Limit(limit).Find(&storehouse).Error
	return storehouse, total, err
}

//获取当前机构所有可用的仓库名字
func GetAllStorehouseName(orgid int64) (storehouse []models.Storehouse, err error) {
	err = XTReadDB().Model(&models.Storehouse{}).Where("storehouse_status = 1 and status = 1 and user_org_id = ?", orgid).Find(&storehouse).Error
	return
}

//根据机构id,生成一个默认仓库
func GetDefaultStorehouse(orgid int64) error {
	var code string
	for a := true; a == true; {
		code = CreateCode()
		tmp := FindStorehouseCode(orgid, code)
		//如果没有重复的编码结束循环
		if tmp == false {
			a = false
		}
	}
	createid, err := Getcreateid(orgid)
	if err != nil {
		return err
	}
	storehouse := models.Storehouse{
		StorehouseCode:    code,
		StorehouseName:    "默认仓库",
		StorehouseAddress: "",
		StorehouseStatus:  1,
		UserOrgId:         orgid,
		StorehouseAdminId: createid.Creator,
		Status:            1,
		Ctime:             time.Now().Unix(),
	}
	_, err = AddStroehouse(storehouse)
	return err
}

//查找该机构id是否有仓库存在,ture存在，false不存在
func IsStorehouse(orgid int64) bool {
	var total int
	XTReadDB().Model(&models.Storehouse{}).Where("user_org_id = ?", orgid).Count(&total)
	if total > 0 {
		return true
	} else {
		return false
	}
}

//查找该机构id是否有仓库配置存在,ture存在，false不存在
func IsStorehouseconfigXT(orgid int64, tx *gorm.DB) bool {
	var total int
	tx.Model(&models.StorehouseConfig{}).Where("user_org_id = ? and status = 1", orgid).Count(&total)
	if total > 0 {
		return true
	} else {
		return false
	}
}

//  根据机构id查询仓库配置
//storehouse_info:耗材 自动入库 的仓库id
//storehouse_out_info:耗材 自动出库 的仓库id
//drug_storehouse_info:药品 自动入库 的仓库id
//drug_storehouse_out:药品 自动出库 的仓库id
func FindStorehouseConfig(orgid int64) (storehouse_config models.StorehouseConfig, err error) {
	err = XTReadDB().Model(&models.StorehouseConfig{}).Where("status = 1 and user_org_id = ?", orgid).Find(&storehouse_config).Error
	return
}

//根据机构id,仓库id新建一个仓库配置
func CreateStorehouseConfig(orgid, id int64) (err error) {
	storeconfig := models.StorehouseConfig{
		UserOrgId:          orgid,
		StorehouseInfo:     id,
		StorehouseOutInfo:  id,
		DrugStorehouseInfo: id,
		DrugStorehouseOut:  id,
		Status:             1,
		Ctime:              time.Now().Unix(),
	}
	err = XTWriteDB().Create(&storeconfig).Error
	return
}

//根据机构id,仓库id新建一个仓库配置,带事务
func CreateStorehouseConfigXT(orgid, id int64, tx *gorm.DB) (err error) {
	storeconfig := models.StorehouseConfig{
		UserOrgId:          orgid,
		StorehouseInfo:     id,
		StorehouseOutInfo:  id,
		DrugStorehouseInfo: id,
		DrugStorehouseOut:  id,
		Status:             1,
		Ctime:              time.Now().Unix(),
	}
	err = tx.Create(&storeconfig).Error
	return
}

//更改耗材自动入库仓库
func UpdateInfo(orgid, id int64) (err error) {
	mtime := time.Now().Unix()
	err = XTWriteDB().Model(&models.StorehouseConfig{}).Where("user_org_id = ? and status = 1", orgid).Updates(map[string]interface{}{"storehouse_info": id, "mtime": mtime}).Error
	return
}

//更改耗材自动出库仓库
func UpdateOutInfo(orgid, id int64) (err error) {
	mtime := time.Now().Unix()
	err = XTWriteDB().Model(&models.StorehouseConfig{}).Where("user_org_id = ? and status = 1", orgid).Updates(map[string]interface{}{"storehouse_out_info": id, "mtime": mtime}).Error
	return
}

//更改药品自动入库仓库
func UpdateDrugInfo2(orgid, id int64) (err error) {
	mtime := time.Now().Unix()
	err = XTWriteDB().Model(&models.StorehouseConfig{}).Where("user_org_id = ? and status = 1", orgid).Updates(map[string]interface{}{"drug_storehouse_info": id, "mtime": mtime}).Error
	return
}

//更改药品自动出库仓库
func UpdateDrugOut(orgid, id int64) (err error) {
	mtime := time.Now().Unix()
	err = XTWriteDB().Model(&models.StorehouseConfig{}).Where("user_org_id = ? and status = 1", orgid).Updates(map[string]interface{}{"drug_storehouse_out": id, "mtime": mtime}).Error
	return
}

//根据id查询仓库名称
func FindStorehouseName(id int64) (storehouse models.Storehouse, err error) {
	err = XTReadDB().Model(&models.Storehouse{}).Where("id = ?", id).Find(&storehouse).Error
	return
}

//判断该仓库是否在仓库配置表中
func IsInConfig(orgid, id int64) bool {
	var total int
	XTReadDB().Model(&models.StorehouseConfig{}).Where("user_org_id = ? and status = 1", orgid).Where(
		"storehouse_info = ? or storehouse_out_info = ? or drug_storehouse_info = ? or drug_storehouse_out = ?", id, id, id, id).Count(&total)
	if total > 0 {
		return true //存在
	} else {
		return false
	}
}

//兼容旧数据
func Byliinit() (err error) {
	tx := XTWriteDB().Begin()
	defer func() {
		if err != nil && err.Error() != "record not found" {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	err = initsgj_user_admin(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = StoreReduceOrg(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = StoreReduceConfig(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_storehouse(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_stock_flow(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_drug_flow(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initdialysis_before_prepare(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_automatic_reduce_detail(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_drug_automatic_reduce_detail(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_warehouse(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_warehouse_info(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_warehouse_out(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_warehouse_out_info(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_drug_warehouse(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_drug_warehouse_info(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_drug_warehouse_out(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_drug_warehouse_out_info(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_cancel_stock(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_cancel_stock_info(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_drug_cancel_stock(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_drug_cancel_stock_info(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_supplier_warehouse_info(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_supplier_warehousing_info_order(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_supplier_warehouse_out(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_supplier_warehousing_out_order(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_supplier_warehouse_cancel(tx)
	if err != nil && err.Error() != "record not found" {
		return
	}
	err = initxt_supplier_warehousing_cancel_order(tx)

	return
}

//初始化管理员名字
func initsgj_user_admin(tx *gorm.DB) (err error) {
	err = tx.Exec("update sgj_users.sgj_user_admin set name = \"超级管理员\" where name is null or name = \"\"").Error
	return
}

//根据xt_gobal_template 获取的机构id减去仓库表存在的机构id，把结果插入到仓库表
func StoreReduceOrg(tx *gorm.DB) (err error) {
	err = tx.Exec("INSERT INTO sgj_xt.xt_storehouse(storehouse_code,storehouse_name,user_org_id,ctime)" +
		"SELECT CONCAT(\"SH-\",FLOOR(RAND()*9000+1000)),\"默认仓库\",tmp.id,UNIX_TIMESTAMP()" +
		"FROM" +
		"(select t1.org_id as id FROM sgj_xt.xt_gobal_template as t1 LEFT JOIN " +
		"(SELECT distinct user_org_id as i FROM sgj_xt.xt_storehouse) as t2 on t1.org_id = t2.i WHERE t2.i is null and t1.status = 1)tmp").Error
	//err = tx.Exec("INSERT INTO sgj_xt.xt_storehouse(storehouse_code,storehouse_name,user_org_id,ctime)" +
	//	"SELECT CONCAT(\"sh-\",FLOOR(RAND()*9000+1000)),\"默认仓库\",tmp.id,UNIX_TIMESTAMP()" +
	//	"FROM" +
	//	"(select t1.id FROM sgj_users.sgj_user_org as t1 LEFT JOIN " +
	//	"(SELECT distinct user_org_id as i FROM sgj_xt.xt_storehouse) as t2 on t1.id = t2.i WHERE t2.i is null and t1.status != 0 and t1.import = 0)tmp").Error
	return
}

//查找仓库表的orgid 减去仓库配置表的orgid，把结果插入到仓库配置表
func StoreReduceConfig(tx *gorm.DB) (err error) {
	err = tx.Exec("INSERT INTO sgj_xt.xt_storehouse_config(user_org_id,storehouse_info,storehouse_out_info,drug_storehouse_info,drug_storehouse_out,ctime)" +
		"SELECT tmp.user_org_id,tmp.id,tmp.id,tmp.id,tmp.id,UNIX_TIMESTAMP()" +
		"FROM(select t1.id,t1.user_org_id FROM sgj_xt.xt_storehouse as t1 LEFT JOIN " +
		"(SELECT user_org_id as i FROM sgj_xt.xt_storehouse_config) as t2 on t1.user_org_id = t2.i WHERE t2.i is null and t1.status = 1)tmp").Error
	return
}

//初始化 xt_storehouse 管理员的名字
func initxt_storehouse(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_storehouse as t," +
		"(SELECT o.id,o.creator from sgj_users.sgj_user_org as o," +
		"(SELECT DISTINCT org_id from sgj_xt.xt_gobal_template)as t " +
		"WHERE t.org_id = o.id )tmp " +
		"SET t.storehouse_admin_id = tmp.creator,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE t.status = 1 and t.user_org_id = tmp.id").Error
	return
}

//初始化 xt_stock_flow（完成）
func initxt_stock_flow(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_stock_flow as t," +
		"(SELECT t1.user_org_id as orgid,t1.storehouse_info as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct user_org_id as orgid FROM sgj_xt.xt_stock_flow  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.user_org_id = tmp.orgid").Error
	return
}

//初始化 xt_drug_flow（完成）
func initxt_drug_flow(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_drug_flow as t," +
		"(SELECT t1.user_org_id as orgid,t1.storehouse_info as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct user_org_id as orgid FROM sgj_xt.xt_drug_flow  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.user_org_id = tmp.orgid").Error
	return
}

//初始化 dialysis_before_prepare（完成）
func initdialysis_before_prepare(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.dialysis_before_prepare as t," +
		"(SELECT t1.user_org_id as orgid,t1.storehouse_info as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct user_org_id as orgid FROM sgj_xt.dialysis_before_prepare  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.user_org_id = tmp.orgid").Error
	return
}

//初始化 xt_automatic_reduce_detail（完成）
func initxt_automatic_reduce_detail(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_automatic_reduce_detail as t," +
		"(SELECT t1.user_org_id as orgid,t1.storehouse_out_info as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct org_id as orgid FROM sgj_xt.xt_automatic_reduce_detail  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.org_id = tmp.orgid").Error
	return
}

//初始化 xt_drug_automatic_reduce_detail（完成）
func initxt_drug_automatic_reduce_detail(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_drug_automatic_reduce_detail as t," +
		"(SELECT t1.user_org_id as orgid,t1.drug_storehouse_out as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct org_id as orgid FROM sgj_xt.xt_drug_automatic_reduce_detail  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.org_id = tmp.orgid").Error
	return
}

//初始化 xt_warehouse（完成）
func initxt_warehouse(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_warehouse as t," +
		"(SELECT t1.user_org_id as orgid,t1.storehouse_info as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct org_id as orgid FROM sgj_xt.xt_warehouse  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.org_id = tmp.orgid").Error
	return
}

//初始化 xt_warehouse_info（完成）
func initxt_warehouse_info(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_warehouse_info as t," +
		"(SELECT t1.user_org_id as orgid,t1.storehouse_info as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct org_id as orgid FROM sgj_xt.xt_warehouse_info  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.org_id = tmp.orgid").Error
	return
}

//初始化 xt_warehouse_out（完成）
func initxt_warehouse_out(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_warehouse_out as t," +
		"(SELECT t1.user_org_id as orgid,t1.storehouse_out_info as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct org_id as orgid FROM sgj_xt.xt_warehouse_out  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.org_id = tmp.orgid").Error
	return
}

//初始化 xt_warehouse_out_info（完成）
func initxt_warehouse_out_info(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_warehouse_out_info as t," +
		"(SELECT t1.user_org_id as orgid,t1.storehouse_out_info as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct org_id as orgid FROM sgj_xt.xt_warehouse_out_info  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.org_id = tmp.orgid").Error
	return
}

//初始化 xt_drug_warehouse（完成）
func initxt_drug_warehouse(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_drug_warehouse as t," +
		"(SELECT t1.user_org_id as orgid,t1.drug_storehouse_info as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct org_id as orgid FROM sgj_xt.xt_drug_warehouse  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.org_id = tmp.orgid").Error
	return
}

//初始化 xt_drug_warehouse_info（完成）
func initxt_drug_warehouse_info(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_drug_warehouse_info as t," +
		"(SELECT t1.user_org_id as orgid,t1.drug_storehouse_info as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct org_id as orgid FROM sgj_xt.xt_drug_warehouse_info  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.org_id = tmp.orgid").Error
	return
}

//初始化 xt_drug_warehouse_out（完成）
func initxt_drug_warehouse_out(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_drug_warehouse_out as t," +
		"(SELECT t1.user_org_id as orgid,t1.drug_storehouse_out as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct org_id as orgid FROM sgj_xt.xt_drug_warehouse_out  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.org_id = tmp.orgid").Error
	return
}

//初始化 xt_drug_warehouse_out_info（完成）
func initxt_drug_warehouse_out_info(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_drug_warehouse_out_info as t," +
		"(SELECT t1.user_org_id as orgid,t1.drug_storehouse_out as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct org_id as orgid FROM sgj_xt.xt_drug_warehouse_out_info  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.org_id = tmp.orgid").Error
	return
}

//初始化 xt_cancel_stock（完成）
func initxt_cancel_stock(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_cancel_stock as t," +
		"(SELECT t1.user_org_id as orgid,t1.storehouse_out_info as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct org_id as orgid FROM sgj_xt.xt_cancel_stock  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.org_id = tmp.orgid").Error
	return
}

//初始化 xt_cancel_stock_info（完成）
func initxt_cancel_stock_info(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_cancel_stock_info as t," +
		"(SELECT t1.user_org_id as orgid,t1.storehouse_out_info as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct org_id as orgid FROM sgj_xt.xt_cancel_stock_info  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.org_id = tmp.orgid").Error
	return
}

//初始化 xt_drug_cancel_stock（完成）
func initxt_drug_cancel_stock(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_drug_cancel_stock as t," +
		"(SELECT t1.user_org_id as orgid,t1.drug_storehouse_out as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct org_id as orgid FROM sgj_xt.xt_drug_cancel_stock  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.org_id = tmp.orgid").Error
	return
}

//初始化 xt_drug_cancel_stock_info（完成）
func initxt_drug_cancel_stock_info(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_drug_cancel_stock_info as t," +
		"(SELECT t1.user_org_id as orgid,t1.drug_storehouse_out as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct org_id as orgid FROM sgj_xt.xt_drug_cancel_stock_info  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.org_id = tmp.orgid").Error
	return
}

//初始化 xt_supplier_warehouse_info（完成）
func initxt_supplier_warehouse_info(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_supplier_warehouse_info as t," +
		"(SELECT t1.user_org_id as orgid,t1.storehouse_info as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct user_org_id as orgid FROM sgj_xt.xt_supplier_warehouse_info  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.user_org_id = tmp.orgid").Error
	return
}

//初始化 xt_supplier_warehousing_info_order（完成）
func initxt_supplier_warehousing_info_order(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_supplier_warehousing_info_order as t," +
		"(SELECT t1.user_org_id as orgid,t1.storehouse_info as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct user_org_id as orgid FROM sgj_xt.xt_supplier_warehousing_info_order  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.user_org_id = tmp.orgid").Error
	return
}

//初始化 xt_supplier_warehouse_out（完成）
func initxt_supplier_warehouse_out(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_supplier_warehouse_out as t," +
		"(SELECT t1.user_org_id as orgid,t1.storehouse_out_info as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct user_org_id as orgid FROM sgj_xt.xt_supplier_warehouse_out  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.user_org_id = tmp.orgid").Error
	return
}

//初始化 xt_supplier_warehousing_out_order（完成）
func initxt_supplier_warehousing_out_order(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_supplier_warehousing_out_order as t," +
		"(SELECT t1.user_org_id as orgid,t1.storehouse_info as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct user_org_id as orgid FROM sgj_xt.xt_supplier_warehousing_out_order  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.user_org_id = tmp.orgid").Error
	return
}

//初始化 xt_supplier_warehouse_cancel（完成）
func initxt_supplier_warehouse_cancel(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_supplier_warehouse_cancel as t," +
		"(SELECT t1.user_org_id as orgid,t1.storehouse_info as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct user_org_id as orgid FROM sgj_xt.xt_supplier_warehouse_cancel  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.user_org_id = tmp.orgid").Error
	return
}

//初始化 xt_supplier_warehousing_cancel_order（完成）
func initxt_supplier_warehousing_cancel_order(tx *gorm.DB) (err error) {
	err = tx.Exec("UPDATE sgj_xt.xt_supplier_warehousing_cancel_order as t," +
		"(SELECT t1.user_org_id as orgid,t1.storehouse_info as id from sgj_xt.xt_storehouse_config as t1," +
		"(SELECT distinct user_org_id as orgid FROM sgj_xt.xt_supplier_warehousing_cancel_order  WHERE storehouse_id is NULL or storehouse_id = 0 )t2 " +
		"WHERE t1.user_org_id = t2.orgid)tmp " +
		"SET t.storehouse_id = tmp.id,t.mtime = UNIX_TIMESTAMP()" +
		"WHERE (t.storehouse_id = 0 or t.storehouse_id is null) and t.user_org_id = tmp.orgid").Error
	return
}

//查询机构创建者的id
func Getcreateid(orgid int64) (createid models.UserOrg, err error) {
	err = XTReadDB().Select("id,creator").Where("id = ? and status = 1", orgid).Find(&createid).Error
	return
}

//根据机构id查询拥有仓库管理权限的角色
func FindRoles(orgid int64) map[string]int {
	role := []models.RolePurviews{}
	tmp := models.PurviewTmp{}
	roles := make(map[string]int)
	//查询sgj_user_purview表条件是urlfor="/stock/warehousequery" and name="仓库管理"
	XTReadDB().Select("id").Where("urlfor=\"/stock/warehousequery\" and name=\"仓库管理\"").Find(&tmp)
	tmpstring := "%" + fmt.Sprint(tmp.Id) + "%"
	XTReadDB().Select("role_id").Where("purview_ids like ? and org_id = ? and status = 1", tmpstring, orgid).Find(&role)
	for i := 0; i < len(role); i++ {
		roles[strconv.FormatInt(role[i].RoleId, 10)] = i
	}
	return roles
}

//判断两个切片中的元素是否有重复的，true有重复的元素，false无相同元素
func IsIdentical(str1 []string, str2 []string) (t bool) {
	t = false
	if len(str1) == 0 || len(str2) == 0 {
		return
	}
	map1, map2 := make(map[string]int), make(map[string]int)
	for i := 0; i < len(str1); i++ {
		map1[str1[i]] = i
	}
	for i := 0; i < len(str2); i++ {
		map2[str2[i]] = i
	}
	for k, _ := range map1 {
		if _, ok := map2[k]; ok {
			t = true
		}
	}
	return
}

//
func GetAllStoreHouseList(orgid int64) (house []*models.XtStorehouse, err error) {

	err = XTReadDB().Where("user_org_id = ? and status = 1", orgid).Find(&house).Error
	return house, err
}

func GetAllStoreHouseListThree(orgid int64) (house []*models.XtStorehouse, err error) {

	err = XTReadDB().Where("user_org_id = ? and status = 1 and storehouse_status = 1", orgid).Find(&house).Error
	return house, err
}

func GetAllStoreHouseListOne(orgid int64) (list []*models.VmStorehouseName, err error) {

	db := XTReadDB().Table("xt_drug_warehouse_info as x").Where("x.status = 1 and x.storehouse_id > 0")

	table := XTReadDB().Table("xt_storehouse as s").Where("s.status= 1")
	fmt.Println(table)
	if orgid > 0 {
		db = db.Where("(x.stock_max_number >0 or x.stock_min_number >0 ) and x.org_id = ?", orgid)
	}
	err = db.Select("x.storehouse_id,s.storehouse_name,s.id").Joins("left join xt_storehouse as s on s.id =x.storehouse_id").Group("x.storehouse_id").Find(&list).Error
	return list, err
}

func GetAllStoreHouseListTwo(orgid int64) (list []*models.VmStorehouseNameOne, err error) {

	db := XTReadDB().Table("xt_warehouse_info as x").Where("x.status = 1")

	table := XTReadDB().Table("xt_storehouse as s").Where("s.status= 1")
	fmt.Println(table)
	if orgid > 0 {
		db = db.Where("stock_count >0  and x.org_id = ?", orgid)
	}
	err = db.Select("x.storehouse_id,s.storehouse_name,s.id").Joins("left join xt_storehouse as s on s.id =x.storehouse_id").Group("x.storehouse_id").Find(&list).Error
	return list, err
}

func GetAllStoreHouseConfig(orgid int64) (models.XtStorehouseConfig, error) {

	config := models.XtStorehouseConfig{}
	err = XTReadDB().Where("user_org_id = ? and status = 1", orgid).First(&config).Error
	return config, err
}

func FindStoreHouseByStorehouseId(id int64, user_org_id int64) (models.XtStorehouse, error) {
	storehouse := models.XtStorehouse{}
	err := XTReadDB().Where("id = ? and user_org_id = ? and status = 1", id, user_org_id).Find(&storehouse).Error
	return storehouse, err
}

func GetSecondWarehouseByNumber(user_org_id int64, warehousing_order string) (*models.XtSecondWarehouse, error) {

	warehouse := models.XtSecondWarehouse{}
	var err error
	err = XTReadDB().Where("user_org_id = ? and second_order_number = ?  and status =1", user_org_id, warehousing_order).Find(&warehouse).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &warehouse, nil
}

func CreateSecondeWarehouse(warehouse models.XtSecondWarehouse) error {

	err := XTWriteDB().Create(&warehouse).Error
	return err
}

func CreateSencondWarehousingInfo(info *models.XtSecondWarehouseInfo) error {

	err := XTWriteDB().Create(&info).Error
	return err
}

func GetAllSecondeOrderList(is_check int64, startime int64, endtime int64, keyword string, page int64, limit int64, orgid int64) (list []*models.VmSecondWarehouse, total int64, err error) {

	db := XTReadDB().Table("sgj_xt.xt_second_warehouse").Where("sgj_xt.xt_second_warehouse.status = 1")
	likeKey := "%" + keyword + "%"
	offset := (page - 1) * limit
	if is_check > 0 {
		db = db.Where("sgj_xt.xt_second_warehouse.is_check = ?", is_check)
	}
	if len(keyword) > 0 {
		db = db.Joins("join sgj_xt.xt_storehouse on sgj_xt.xt_storehouse.id = sgj_xt.xt_second_warehouse.storehouse_in_id or sgj_xt.xt_storehouse.id = sgj_xt.xt_second_warehouse.storehouse_out_id").Group("sgj_xt.xt_second_warehouse.id")
		db = db.Where("sgj_xt.xt_second_warehouse.second_order_number like ? or sgj_xt.xt_storehouse.storehouse_name  like ? ", likeKey, likeKey)
	}

	if startime > 0 {
		db = db.Where("sgj_xt.xt_second_warehouse.record_date >= ?", startime)
	}

	if endtime > 0 {
		db = db.Where("sgj_xt.xt_second_warehouse.record_date <= ?", endtime)
	}
	if orgid > 0 {
		db = db.Where("sgj_xt.xt_second_warehouse.user_org_id = ?", orgid)
	}
	err = db.Count(&total).Offset(offset).Limit(limit).Order("ctime desc").Find(&list).Error
	return list, total, err
}

func GetSecondWarehouseOrderById(id int64) (models.XtSecondWarehouse, error) {
	warehouse := models.XtSecondWarehouse{}
	err := XTReadDB().Where("id = ? and status = 1", id).Find(&warehouse).Error
	return warehouse, err
}

func GetLastSecondWarehouse(orgid int64) (models.XtSecondWarehouse, error) {
	warehouse := models.XtSecondWarehouse{}
	err := XTReadDB().Where("user_org_id = ? and status = 1", orgid).Last(&warehouse).Error
	return warehouse, err
}

func GetSencondOrderDetail(id int64, orgid int64) (info []*models.XtSecondWarehouseInfo, err error) {

	err = XTReadDB().Where("warehouse_id = ? and user_org_id = ? and status = 1", id, orgid).Find(&info).Error
	return info, err
}

func UpdateModifySecondWarehouse(id int64, warehouse models.XtSecondWarehouse) error {

	err := XTWriteDB().Model(&warehouse).Where("id=? and status = 1", id).Update(map[string]interface{}{"storehouse_in_id": warehouse.StorehouseInId, "storehouse_out_id": warehouse.StorehouseOutId, "record_date": warehouse.RecordDate}).Error
	return err
}

func UpdateStoreWarehousing(info *models.XtSecondWarehouseInfo) error {

	err := XTWriteDB().Model(&info).Where("id = ? and status = 1", info.ID).Update(map[string]interface{}{"project_name": info.ProjectName, "second_specification_name": info.SecondSpecificationName, "project_type": info.ProjectType, "sencond_unit": info.SencondUnit, "count": info.Count, "second_total": info.SecondTotal, "storehouse_in_id": info.StorehouseInId, "storehouse_out_id": info.StorehouseOutId, "project_id": info.ProjectId, "remake": info.Remake, "min_price": info.MinPrice, "is_source": info.IsSource}).Error
	return err
}

func GetSecondOrderList(ids []string, orgid int64) (warehouse []*models.XtSecondWarehouseInfo, err error) {

	err = XTReadDB().Where("warehouse_id in(?) and user_org_id = ? and status = 1", ids, orgid).Find(&warehouse).Error
	return warehouse, err
}

func UpdateStoreOrderByArray(ids []string, orgid int64, checker int64) error {

	err := XTWriteDB().Model(&models.XtSecondWarehouse{}).Where("id in(?) and user_org_id = ? and status = 1", ids, orgid).Update(map[string]interface{}{"is_check": 1, "checker": checker, "check_time": time.Now().Unix()}).Error
	return err
}

func GetWarehouseInfoByStoreHouseId(good_id int64, storehouse_id int64, orgid int64) (info []*models.WarehousingInfo, err error) {

	err = XTReadDB().Where("good_id = ? and storehouse_id = ? and org_id = ? and status = 1", good_id, storehouse_id, orgid).Find(&info).Error
	return info, err
}

func GetWarehouseInfoByStoreHouseIdOne(good_id int64, storehouse_id int64, orgid int64, second_warehouse_info_id int64) (info []*models.WarehousingInfo, err error) {

	err = XTReadDB().Where("good_id = ? and storehouse_id = ? and org_id = ? and status = 1 and second_warehouse_info_id = ?", good_id, storehouse_id, orgid, second_warehouse_info_id).Find(&info).Error
	return info, err
}

func GetLastWarehouseOutBySys(is_sys int64, orgid int64, warehouse_out_time int64, second_warehouse_id int64) (models.WarehouseOut, error) {
	out := models.WarehouseOut{}
	err := XTReadDB().Where("is_sys = ? and org_id = ? and status = 1 and warehouse_out_time = ? and second_warehouse_id = ?", is_sys, orgid, warehouse_out_time, second_warehouse_id).Last(&out).Error
	return out, err
}

func GetDrugWarehouseInfoByStoreHouseId(drug_id int64, storehouse_id int64, orgid int64) (info []*models.DrugWarehouseInfo, err error) {

	err = XTReadDB().Where("drug_id = ? and storehouse_id = ? and org_id = ? and status = 1", drug_id, storehouse_id, orgid).Find(&info).Error
	return info, err
}

func GetDrugWarehouseInfoByStoreHouseIdOne(drug_id int64, storehouse_id int64, orgid int64, second_warehouse_info_id int64) (info []*models.DrugWarehouseInfo, err error) {

	err = XTReadDB().Where("drug_id = ? and storehouse_id = ? and org_id = ? and status = 1 and second_warehouse_info_id = ?", drug_id, storehouse_id, orgid, second_warehouse_info_id).Find(&info).Error
	return info, err
}

func DeleteStorehouseList(id int64) error {

	err = XTWriteDB().Model(&models.XtSecondWarehouse{}).Where("id = ? and status = 1", id).Update(map[string]interface{}{"status": 0}).Error

	err = XTWriteDB().Model(&models.XtSecondWarehouseInfo{}).Where("warehouse_id in(?) and status = 1", id).Update(map[string]interface{}{"status": 0}).Error
	return err
}

func GetStoreWarehouseOutList(good_id int64, second_warehouse_info_id int64, orgid int64) (info []*models.WarehouseOutInfo, err error) {

	err = XTReadDB().Where("good_id = ? and status = 1 and second_warehouse_info_id = ? and org_id = ?", good_id, second_warehouse_info_id, orgid).Find(&info).Error
	return info, err
}

func ModifyStoreWarehouseById(id int64, stock_count int64) error {

	info := models.WarehousingInfo{}
	err = XTWriteDB().Model(&info).Where("id = ?  and status = 1", id).UpdateColumn("stock_count", gorm.Expr("stock_count + ?", stock_count)).Error
	return err
}

func GetStoreWarehouseById(storehouse_id int64, orgid int64) (models.Warehousing, error) {
	warehousing := models.Warehousing{}
	err := XTReadDB().Where("second_warehouse_id = ? and org_id = ?", storehouse_id, orgid).Find(&warehousing).Error
	return warehousing, err
}

func ModifyStoreWarehouse(id int64, orgid int64, good_id int64) error {

	err := XTWriteDB().Model(&models.Warehousing{}).Where("id = ? and status = 1", id).Update(map[string]interface{}{"status": 0}).Error

	err = XTWriteDB().Model(&models.WarehousingInfo{}).Where("warehousing_id  = ? and org_id = ? and status =1 and good_id = ?", id, orgid, good_id).Update(map[string]interface{}{"status": 0}).Error

	err = XTWriteDB().Model(&models.VmStockFlow{}).Where("warehousing_id = ? and user_org_id = ? and status = 1 and good_id = ?", id, orgid, good_id).Update(map[string]interface{}{"status": 0}).Error
	return err
}

func GetStoreWarehouseOutById(id int64, orgid int64) (models.WarehouseOut, error) {

	out := models.WarehouseOut{}
	err := XTReadDB().Where("id = ? and org_id = ?", id, orgid).Find(&out).Error
	return out, err
}

func ModifyWarehouseOut(id int64, orgid int64, good_id int64) error {
	err := XTWriteDB().Model(&models.WarehouseOut{}).Where("id = ? and status = 1", id).Update(map[string]interface{}{"status": 0}).Error

	err = XTWriteDB().Model(&models.WarehouseOutInfo{}).Where("warehouse_out_id = ? and org_id = ? and status =1 and good_id = ?", id, orgid, good_id).Update(map[string]interface{}{"status": 0}).Error

	err = XTWriteDB().Model(&models.VmStockFlow{}).Where("warehouse_out_id = ? and user_org_id = ? and status = 1 and good_id = ?", id, orgid, good_id).Update(map[string]interface{}{"status": 0}).Error
	return err
}

func GetStoreDrugWarehouseOutList(drug_id int64, second_warehouse_info_id int64, orgid int64) (drugInfo []*models.DrugWarehouseOutInfo, err error) {
	err = XTReadDB().Where("drug_id = ? and status = 1 and second_warehouse_info_id = ? and org_id = ?", drug_id, second_warehouse_info_id, orgid).Find(&drugInfo).Error
	return drugInfo, err
}

func ModifyDrugStoreWarehouseInfo(id int64, stock_max_number int64) error {

	info := models.DrugWarehouseInfo{}
	err := XTWriteDB().Model(&info).Where("id = ?  and status = 1", id).UpdateColumn("stock_max_number", gorm.Expr("stock_max_number + ?", stock_max_number)).Error
	return err
}

func ModifyDrugStoreWarehouseInfoOne(id int64, stock_min_number int64) error {
	info := models.DrugWarehouseInfo{}
	err := XTWriteDB().Model(&info).Where("id = ?  and status = 1", id).UpdateColumn("stock_min_number", gorm.Expr("stock_min_number + ?", stock_min_number)).Error
	return err
}

func GetStoreDrugWarehouseById(second_warehouse_id int64, orgid int64) (models.DrugWarehouse, error) {
	warehouse := models.DrugWarehouse{}
	err := XTReadDB().Where("second_warehouse_id = ? and org_id = ?", second_warehouse_id, orgid).Find(&warehouse).Error
	return warehouse, err
}

func DeleteStoreWarehousingId(id int64, orgid int64, drug_id int64) error {

	err := XTWriteDB().Model(&models.DrugWarehouse{}).Where("id = ? and org_id = ? and status = 1", id, orgid).Update(map[string]interface{}{"status": 0}).Error

	err = XTWriteDB().Model(&models.DrugWarehouseInfo{}).Where("warehousing_id  = ? and org_id = ? and status = 1 and drug_id = ?", id, orgid, drug_id).Update(map[string]interface{}{"status": 0}).Error

	err = XTWriteDB().Model(&models.DrugFlow{}).Where("warehousing_id = ? and user_org_id =? and status = 1 and drug_id = ?", id, orgid, drug_id).Update(map[string]interface{}{"status": 0}).Error
	return err
}

func GetStoreDrugWarehouseOutById(id int64, orgid int64) (models.DrugWarehouseOut, error) {

	warehouse := models.DrugWarehouseOut{}
	err = XTReadDB().Where("id = ? and org_id = ?", id, orgid).Find(&warehouse).Error
	return warehouse, err
}

func DeleteStoreWarehouseOut(id int64, orgid int64, drug_id int64) error {
	err := XTWriteDB().Model(&models.DrugWarehouseOut{}).Where("id = ? and org_id = ? and status = 1", id, orgid).Update(map[string]interface{}{"status": 0}).Error

	err = XTWriteDB().Model(&models.DrugWarehouseOutInfo{}).Where("warehouse_out_id = ? and org_id = ? and status = 1 and drug_id = ?", id, orgid, drug_id).Update(map[string]interface{}{"status": 0}).Error

	err = XTWriteDB().Model(&models.DrugFlow{}).Where("warehouse_out_id = ? and user_org_id =? and status = 1 and drug_id = ?", id, orgid, drug_id).Update(map[string]interface{}{"status": 0}).Error
	return err
}

func ModifyStoreHouseById(id []string, orgid int64) error {

	err := XTWriteDB().Model(&models.XtSecondWarehouse{}).Where("id in(?) and user_org_id = ? and status = 1", id, orgid).Update(map[string]interface{}{"is_check": 2, "checker": 0, "check_time": 0}).Error
	return err
}

func GetStoreWarehouseInfoById(id int64) (models.WarehousingInfo, error) {
	info := models.WarehousingInfo{}
	err := XTReadDB().Where("id = ? and status = 1", id).Find(&info).Error
	return info, err
}

func GetStoreHouseDrugWarehouseingInfo(id int64) (models.DrugWarehouseInfo, error) {

	info := models.DrugWarehouseInfo{}
	err := XTReadDB().Where("id = ? and status = 1", id).Find(&info).Error
	return info, err
}

func GetDrugSumCountByStorehouseId(storehouse_id int64, orgid int64, drug_id int64) (info []*models.DrugWarehouseInfo, err error) {

	err = XTReadDB().Where("storehouse_id = ? and org_id = ? and status = 1 and (stock_max_number >0 or stock_min_number>0) and drug_id =? and is_check = 1", storehouse_id, orgid, drug_id).Find(&info).Error
	return info, err
}

func GetDrugSumCountByStorehouseIdSix(storehouse_id int64, orgid int64) (info []*models.DrugWarehouseInfo, err error) {

	err = XTReadDB().Where("storehouse_id = ? and org_id = ? and status = 1 and (stock_max_number >0 or stock_min_number>0)", storehouse_id, orgid).Find(&info).Error
	return info, err
}

func GetGoodSumCountByStoreId(storehouse_id int64, goodid int64, orgid int64) (info []*models.WarehousingInfo, err error) {

	err = XTReadDB().Where("storehouse_id = ? and good_id = ? and org_id =? and status =1 and stock_count > 0 and is_check = 1", storehouse_id, goodid, orgid).Find(&info).Error
	return info, err
}

func GetGoodSumCountByStoreIdSix(storehouse_id int64, orgid int64) (info []*models.WarehousingInfo, err error) {

	err = XTReadDB().Where("storehouse_id = ?  and org_id =? and status =1 and stock_count > 0", storehouse_id, orgid).Find(&info).Error
	return info, err
}

func GetSupplyDrugListOne(orgid int64, storehouse_id int64) (drug []*models.SpBaseDrug, err error) {

	db := XTReadDB().Table("xt_base_drug as x").Where("x.status = 1 AND find_in_set('停用',drug_status) = 0")

	if orgid > 0 {
		db = db.Where("x.org_id = ?", orgid)
	}

	err = db.Preload("DrugWarehouseInfo", "status = 1 and org_id = ? and (stock_max_number >0 or stock_min_number>0) and storehouse_id = ?", orgid, storehouse_id).Find(&drug).Error
	return drug, err
}

func GetSupplyGoodListOne(orgid int64, storehouse_id int64) (good []*models.SpGoodInformation, err error) {

	db := XTReadDB().Table("xt_good_information as x").Where("x.status = 1 AND find_in_set('停用',good_status) = 0")

	if orgid > 0 {
		db = db.Where("x.org_id = ?", orgid)
	}

	err = db.Preload("GoodWarehouseInfo", "status = 1 and org_id = ? and storehouse_id = ?", orgid, storehouse_id).Find(&good).Error
	return good, err
}

func GetDrugSumSecondCount(drug_id int64, storehouse_id int64, orgid int64) (info []*models.XtDrugWarehouseInfo, err error) {

	err = XTReadDB().Where("drug_id = ? and storehouse_id = ? and org_id = ? and status = 1 and (stock_max_number >0 or stock_min_number>0)", drug_id, storehouse_id, orgid).Find(&info).Error
	return info, err
}

func GetGoodSumSecondCount(good_id int64, storehouse_id int64, orgid int64) (info []*models.WarehousingInfo, err error) {

	err = XTReadDB().Where("good_id = ? and storehouse_id = ? and org_id = ? and status = 1 and stock_count > 0", good_id, storehouse_id, orgid).Find(&info).Error
	return info, err
}

func DeleteSecondOrderInfo(id int64) error {

	err := XTWriteDB().Model(&models.XtSecondWarehouseInfo{}).Where("id = ? and status = 1", id).Update(map[string]interface{}{"status": 0}).Error
	return err
}
