package service

import (
	"XT_New/models"
	"fmt"
	"github.com/jinzhu/gorm"
	"strings"
	"time"
)

//根据供应商编号获取首要联系人
func FindName(code string, orgid int64) (fistname models.SpSupplierContacts, err error) {
	err = XTReadDB().Model(&models.SpSupplierContacts{}).Where("supplier_code = ? and status = 1 and is_first = 1 and user_org_id = ?", code, orgid).First(&fistname).Error
	return fistname, err
}

//供应商分页
func GetSupplyList(ctype int64, page int64, limit int64, keyword string, orgid int64) (supplylist []*models.SpSupplierName, total int64, err error) {
	db := XTReadDB().Model(&supplylist).Where("xt_supplier_name.status = 1 and xt_supplier_name.user_org_id = ?", orgid)
	offset := (page - 1) * limit
	if len(keyword) > 0 {
		keyword = "%" + keyword + "%" //联系人
		db = db.Joins("left join xt_supplier_contacts on xt_supplier_contacts.supplier_code = xt_supplier_name.supplier_code")
		db = db.Where("xt_supplier_contacts.status = 1 and xt_supplier_contacts.user_org_id = ? and xt_supplier_contacts.name like ? or xt_supplier_name.supplier_code like ? or xt_supplier_name.supplier_name like ? ", orgid, keyword, keyword, keyword).Group("xt_supplier_name.id")
	}
	if ctype > 0 {
		db = db.Where("xt_supplier_name.supplier_type = ?", ctype)
	}
	err = db.Count(&total).Offset(offset).Order("xt_supplier_name.id desc").Limit(limit).Find(&supplylist).Error
	return supplylist, total, err
}

//修改供应商和联系人
func UpdateSupplyAndContact(thisStockIn []interface{}, suid, orgId, supplierType, tcreater int64, supplierCode, supplierName, number, bank, bankAccount string, vatRate float64) error {
	tx := XTWriteDB().Begin()
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	for _, item := range thisStockIn {
		items := item.(map[string]interface{})
		//判断联系人是否为新加的
		if items["id"] == "" || items["id"] == 0 {
			var tmp float64 = 0
			items["id"] = tmp
		}
		id := int64(items["id"].(float64))
		name := items["name"].(string)
		phone := items["phone"].(string)
		address := items["address"].(string)
		var tmpfirst int64
		switch items["is_first"].(type) {
		case int:
			var aint int = items["is_first"].(int)
			tmpfirst = int64(aint)
		case float64:
			tmpfirst = int64(items["is_first"].(float64))
		}
		isfirst := tmpfirst

		updatecontacts := models.SpSupplierContacts{
			ID:           id,
			Name:         name,
			Phone:        phone,
			Address:      address,
			IsFirst:      isfirst,
			SupplierCode: supplierCode,
			UserOrgId:    orgId,
			Status:       1,
			Ctime:        0,
			Mtime:        time.Now().Unix(),
		}
		if id == 0 { //表示这是新加的
			spcontacts := models.SpSupplierContacts{
				Name:         name,
				Phone:        phone,
				Address:      address,
				IsFirst:      isfirst,
				SupplierCode: supplierCode,
				UserOrgId:    orgId,
				Status:       1,
				Ctime:        time.Now().Unix(),
				Mtime:        0,
			} //保存一条联系人的数据
			err = SaveContacts(spcontacts, tx)
			if err != nil {
				return err
			}
		} else {
			err = UpdateContact(updatecontacts, tx)
		}
		var tmpid int64
		if isfirst == 1 {
			if id == 0 { //新加的首要联系人
				var spconid []*models.SpSupplierContacts
				spconid, err = SaveContactsId(tx, orgId)
				if err != nil {
					return err
				}
				tmpid = spconid[0].ID
			} else {
				tmpid = id
			}
			//更新供应商
			upsupply := models.SpSupplierName{
				ID:           suid,
				SupplierCode: supplierCode,
				SupplierName: supplierName,
				SupplierType: supplierType,
				VatRate:      vatRate,
				Number:       number,
				Bank:         bank,
				BankAccount:  bankAccount,
				UserOrgId:    orgId,
				Status:       1,
				ContactsId:   tmpid,
				Mtime:        time.Now().Unix(),
				Modify:       tcreater,
			}
			err = UpdateSupplyNameTX(upsupply, tx)
			if err != nil {
				return err
			}
		}

	}
	return err
}

//更新一条供应商的信息,添加了事务的
func UpdateSupplyNameTX(upsupply models.SpSupplierName, tx *gorm.DB) error {
	err := tx.Model(&models.SpSupplierName{}).Where("id = ? and status = 1", upsupply.ID).Updates(map[string]interface{}{"supplier_code": upsupply.SupplierCode, "supplier_name": upsupply.SupplierName, "supplier_type": upsupply.SupplierType, "vat_rate": upsupply.VatRate, "number": upsupply.Number, "bank": upsupply.Bank, "bank_account": upsupply.BankAccount, "user_org_id": upsupply.UserOrgId, "status": upsupply.Status, "contacts_id": upsupply.ContactsId, "mtime": upsupply.Mtime, "modify": upsupply.Modify}).Error
	return err
}

//更新一条供应商的信息,没有添加事务
func UpdateSupplyName(upsupply models.SpSupplierName) error {
	err := XTWriteDB().Model(&models.SpSupplierName{}).Where("id = ? and status = 1", upsupply.ID).Updates(map[string]interface{}{"supplier_code": upsupply.SupplierCode, "supplier_name": upsupply.SupplierName, "supplier_type": upsupply.SupplierType, "vat_rate": upsupply.VatRate, "number": upsupply.Number, "bank": upsupply.Bank, "bank_account": upsupply.BankAccount, "user_org_id": upsupply.UserOrgId, "status": upsupply.Status, "contacts_id": upsupply.ContactsId, "mtime": upsupply.Mtime, "modify": upsupply.Modify}).Error
	return err
}

//更新一条联系人的信息
func UpdateContact(updatecontacts models.SpSupplierContacts, tx *gorm.DB) error {
	err := tx.Model(&models.SpSupplierContacts{}).Where("id = ? and status = 1", updatecontacts.ID).Updates(map[string]interface{}{"name": updatecontacts.Name, "phone": updatecontacts.Phone, "address": updatecontacts.Address, "is_first": updatecontacts.IsFirst, "supplier_code": updatecontacts.SupplierCode, "user_org_id": updatecontacts.UserOrgId, "status": updatecontacts.Status, "mtime": updatecontacts.Mtime}).Error
	return err
}

//查询供应商单条记录
func GetSupplyOne(id int64) (supply models.SpSupplierName, err error) {
	err = XTReadDB().Model(&models.SpSupplierName{}).Where("id = ? and status = 1", id).First(&supply).Error
	return supply, err
}

//删除单条联系人记录
func DelContactOne(id int64) error {
	err := XTWriteDB().Model(&models.SpSupplierContacts{}).Where("id = ?", id).Update("status", 0).Error
	return err
}

//获取单条供应商和涉及到的联系人记录
func GetSupplyAndContactOne(id, orgId int64) (supply models.SpSupplierName, contact []*models.SpSupplierContacts, err error) {
	err = XTReadDB().Model(&models.SpSupplierName{}).Where("id = ? and status = 1 and user_org_id = ?", id, orgId).First(&supply).Error
	code := supply.SupplierCode
	err = XTReadDB().Model(&models.SpSupplierContacts{}).Where("supplier_code = ? and status = 1 and user_org_id = ?", code, orgId).Find(&contact).Error
	return supply, contact, err
}

//删除供应商及联系人
func DelSupply(supply models.SpSupplierName, orgId int64) (shiwu string, err error) {
	tx := XTWriteDB().Begin()
	defer func() {
		if err != nil {
			shiwu = "失败"
			tx.Rollback()
		} else {
			shiwu = "成功"
			tx.Commit()
		}
	}()
	//删除供应商
	err = tx.Model(&supply).Update("status", 0).Error
	if err != nil {
		return shiwu, err
	}
	var spcode models.SpSupplierName
	//获取供应商编号
	err = tx.Model(&models.SpSupplierName{}).Select("supplier_code").Where("user_org_id = ? and id = ?", orgId, supply.ID).First(&spcode).Error
	if err != nil {
		return shiwu, err
	}
	//删除联系人
	err = tx.Model(&models.SpSupplierContacts{}).Where("supplier_code = ? and user_org_id = ?", spcode.SupplierCode, orgId).Update("status", 0).Error

	return shiwu, err
}

//保存供应商和联系人
func SaveSupplyAndContact(thisStockIn []interface{}, orgId, supplierType, tcreater int64, supplierCode, supplierName, number, bank, bankAccount string, vatRate float64) error {
	tx := XTWriteDB().Begin()
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	for _, item := range thisStockIn {
		items := item.(map[string]interface{})
		name := items["name"].(string)
		phone := items["phone"].(string)
		address := items["address"].(string)
		//isfirst := int64(items["is_first"].(float64))
		var tmpfirst int64
		//tmptype :=  reflect.TypeOf(items["is_first"])
		switch items["is_first"].(type) {
		case int:
			var aint int = items["is_first"].(int)
			tmpfirst = int64(aint)
		case float64:
			tmpfirst = int64(items["is_first"].(float64))
		}
		isfirst := tmpfirst

		spcontacts := models.SpSupplierContacts{
			Name:         name,
			Phone:        phone,
			Address:      address,
			IsFirst:      isfirst,
			SupplierCode: supplierCode,
			UserOrgId:    orgId,
			Status:       1,
			Ctime:        time.Now().Unix(),
			Mtime:        0,
		}
		err = SaveContacts(spcontacts, tx)
		if isfirst == 1 {
			var spconid []*models.SpSupplierContacts
			spconid, err = SaveContactsId(tx, orgId)
			if err != nil {
				return err
			}
			tmpid := spconid[0].ID
			//保存供应商
			supply := models.SpSupplierName{
				SupplierCode: supplierCode,
				SupplierName: supplierName,
				SupplierType: supplierType,
				VatRate:      vatRate,
				Number:       number,
				Bank:         bank,
				BankAccount:  bankAccount,
				UserOrgId:    orgId,
				Status:       1,
				ContactsId:   tmpid,
				Ctime:        time.Now().Unix(),
				Mtime:        0,
				Creater:      tcreater,
				Modify:       tcreater,
			}
			err = SaveSupplyTx(supply, tx)
			if err != nil {
				return err
			}
		}
		if err != nil {
			return err
		}
	}
	return err
}

//获取供应商编码
func GetSuppliyCode(orgId int64) (spcode []*models.SpSupplierName, err error) {
	err = XTReadDB().Model(&models.SpSupplierName{}).Select("supplier_code").Where("supplier_code like 'gys%' and status = 1 and user_org_id = ? ", orgId).Order("supplier_code desc").First(&spcode).Error
	return spcode, err
}

//查询供应商的名字是否有重复
func FindSupplierName(supplierName string, orgId int64) (sbool bool, err error) {
	var total int
	err = XTReadDB().Model(&models.SpSupplierName{}).Where("supplier_name = ? and user_org_id = ? and status = 1", supplierName, orgId).Count(&total).Error
	if total != 0 {
		sbool = true
	} else {
		sbool = false
	}
	return sbool, err
}

//查询供应商的编号是否有重复(用于修改)
func FindSupplierCode(supplierCode string, supplierid, orgid int64) (codebool bool, err error) {
	var total int
	err = XTReadDB().Model(&models.SpSupplierName{}).Where("supplier_code = ? and id != ? and user_org_id = ? and status = 1", supplierCode, supplierid, orgid).Count(&total).Error
	if total > 0 {
		codebool = true
	} else {
		codebool = false
	}
	return codebool, err
}

//查询供应商的编号是否有重复（用于新增）
func FindSupplierCodes(supplierCode string, orgid int64) (codebool bool, err error) {
	var total int
	err = XTReadDB().Model(&models.SpSupplierName{}).Where("supplier_code = ? and status = 1 and user_org_id = ?", supplierCode, orgid).Count(&total).Error
	if total > 0 {
		codebool = true
	} else {
		codebool = false
	}
	return codebool, err
}

//保存一条供应商数据加事务的
func SaveSupplyTx(supply models.SpSupplierName, tx *gorm.DB) error {
	err := tx.Create(&supply).Error
	return err
}

//保存一条供应商数据没有事务的
func SaveSupply(supply models.SpSupplierName) error {
	err := XTWriteDB().Create(&supply).Error
	return err
}

//获取联系人的id
func SaveContactsId(tx *gorm.DB, orgid int64) (spconid []*models.SpSupplierContacts, err error) {
	err = tx.Model(&models.SpSupplierContacts{}).Select("id").Where("status = 1 and user_org_id = ?", orgid).Order("id desc").First(&spconid).Error
	return
}

//保存一条联系人数据
func SaveContacts(spcontacts models.SpSupplierContacts, tx *gorm.DB) error {
	err := tx.Create(&spcontacts).Error
	return err
}

func GetSupplyDrugList(orgid 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)", orgid).Find(&drug).Error
	return drug, err
}

func GetSupplyGoodList(orgid 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 = ?", orgid).Find(&good).Error
	return good, err
}

func GetSupplierList(orgid int64) (suppler []*models.SpSupplierName, err error) {

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

func FindAllSupplyOrder(orgid int64) (total int64, err error) {

	err = XTReadDB().Model(&models.SupplierWarehouseInfo{}).Where("user_org_id = ?", orgid).Count(&total).Error
	return total, err
}

func CreateSupplyWarehouse(info models.SupplierWarehouseInfo) error {

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

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

func CreateSupplyWarehousingOrder(order *models.SupplierWarehousingInfoOrder) error {

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

func GetAllPurchaseOrderList(check_id int64, startime int64, endtime int64, keyword string, page int64, limit int64, orgid int64) (info []*models.VmSupplierWarehouseInfo, total int64, err error) {

	db := XTReadDB().Model(&info).Where("sgj_xt.xt_supplier_warehouse_info.status = 1")
	likeKey := "%" + keyword + "%"
	offset := (page - 1) * limit
	if check_id > 0 {
		db = db.Where("sgj_xt.xt_supplier_warehouse_info.is_check = ?", check_id)
	}
	if startime > 0 {
		db = db.Where("sgj_xt.xt_supplier_warehouse_info.record_date >= ?", startime)
	}
	if endtime > 0 {
		db = db.Where("sgj_xt.xt_supplier_warehouse_info.record_date<=?", endtime)
	}

	if len(keyword) > 0 {
		db = db.Joins("join sgj_xt.xt_supplier_name on sgj_xt.xt_supplier_name.id = sgj_xt.xt_supplier_warehouse_info.supplier_id")
		db = db.Where("sgj_xt.xt_supplier_warehouse_info.number like ? or sgj_xt.xt_supplier_name.supplier_name like ? ", likeKey, likeKey).Group("sgj_xt.xt_supplier_warehouse_info.id")
	}
	if orgid > 0 {
		db = db.Where("sgj_xt.xt_supplier_warehouse_info.user_org_id = ?", orgid)
	}
	err = db.Count(&total).Offset(offset).Limit(limit).Preload("SupplierWarehousingInfoOrder", "status= 1 and user_org_id = ?", orgid).Preload("SpSupplierWarehouseOut", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = 1").Preload("SpSupplierWarehousingOutOrder", "status= 1 and user_org_id = ?", orgid)
	}).Order("ctime desc").Find(&info).Error
	return info, total, err
}

func GetSupplyWarehousingOrderInfo(id int64) (order []*models.SupplierWarehousingInfoOrder, err error) {

	err = XTReadDB().Where("warehousing_id = ? and status = 1", id).Find(&order).Error
	return order, err
}

func GetSupplyWarehousingOrderInfoTwo(id int64, ids []string) (order []*models.SupplierWarehousingInfoOrder, err error) {

	err = XTReadDB().Where("warehousing_id = ? and status = 1 and project_id in(?)", id, ids).Find(&order).Error
	return order, err
}

func ModefySupplyWarehouseInfo(id int64, info models.SupplierWarehouseInfo) error {

	err := XTWriteDB().Model(&models.SupplierWarehouseInfo{}).Where("id = ? and status = 1", id).Updates(map[string]interface{}{"rate_of_concession": info.RateOfConcession, "discount_amount": info.DiscountAmount, "document_date": info.DocumentDate, "delivery_date": info.DeliveryDate, "supplier_id": info.SupplierId, "return_remake": info.ReturnRemake}).Error
	return err
}

func ModifySupplyWarehouseOrder(order *models.SupplierWarehousingInfoOrder) error {

	err := XTWriteDB().Model(&models.SupplierWarehousingInfoOrder{}).Where("id = ? and status = 1", order.ID).Updates(map[string]interface{}{}).Updates(map[string]interface{}{"is_source": order.IsSource, "count": order.Count, "price": order.Price, "amount": order.Amount, "remark": order.Remark, "project_id": order.ProjectId, "supply_license_number": order.SupplyLicenseNumber, "supply_type": order.SupplyType, "supply_specification_name": order.SupplySpecificationName, "supply_total": order.SupplyTotal, "supply_manufacturer": order.SupplyManufacturer, "name": order.Name, "supply_unit": order.SupplyUnit, "manufacturer_id": order.ManufacturerId}).Error
	return err
}

func UpdateSupplyWaresing(id int64, info models.SupplierWarehouseInfo) error {

	err := XTWriteDB().Model(&models.SupplierWarehouseInfo{}).Where("id = ? and status = 1", id).Updates(map[string]interface{}{"is_check": info.IsCheck, "checker": info.Checker, "check_time": info.CheckTime, "mtime": time.Now().Unix()}).Error
	return err
}

func GetPurchaseOrderDetail(id int64) (models.SupplierWarehouseInfo, error) {

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

func FindAllSupplyWarehouseOutOrder(orgid int64) (total int64, err error) {
	err = XTReadDB().Model(&models.SpSupplierWarehouseOut{}).Where("user_org_id = ?", orgid).Count(&total).Error
	return total, err
}

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

func CreateSupplyWarehouseOut(out models.SpSupplierWarehouseOut) error {

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

func CreateSupplyWarehousOutOrder(order *models.SpSupplierWarehousingOutOrder) error {

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

func GetSupplyWarehouseOutById(id int64, user_org_id int64) (order []*models.SpSupplierWarehousingOutOrder, err error) {

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

func GetSupplyWarehouseOutByIdOne(id int64, user_org_id int64, ids []string) (order []*models.SpSupplierWarehousingOutOrder, err error) {

	err = XTReadDB().Where("warehouse_out_id = ? and status = 1 and user_org_id = ? and project_id in(?)", id, user_org_id, ids).Find(&order).Error
	return order, err
}

func GetAllGoodOderList(check_id int64, keyword string, page int64, limit int64, startime int64, endtime int64, orgid int64) (out []*models.VmSupplierWarehouseOut, total int64, err error) {
	db := XTReadDB().Model(&out).Where("sgj_xt.xt_supplier_warehouse_out.status = 1")
	likeKey := "%" + keyword + "%"
	offset := (page - 1) * limit
	if check_id > 0 {
		db = db.Where("sgj_xt.xt_supplier_warehouse_out.is_check = ?", check_id)
	}
	if startime > 0 {
		db = db.Where("sgj_xt.xt_supplier_warehouse_out.record_date >= ?", startime)
	}
	if endtime > 0 {
		db = db.Where("sgj_xt.xt_supplier_warehouse_out.record_date<=?", endtime)
	}

	if len(keyword) > 0 {
		db = db.Joins("join sgj_xt.xt_supplier_name on sgj_xt.xt_supplier_name.id = sgj_xt.xt_supplier_warehouse_out.supplier_id")
		db = db.Where("sgj_xt.xt_supplier_warehouse_out.good_number like ? or sgj_xt.xt_supplier_name.supplier_name  like ? ", likeKey, likeKey).Group("xt_supplier_warehouse_out.id")
	}
	if orgid > 0 {
		db = db.Where("sgj_xt.xt_supplier_warehouse_out.user_org_id = ?", orgid)
	}
	err = db.Count(&total).Offset(offset).Limit(limit).Preload("SpSupplierWarehousingOutOrder", "status= 1 and user_org_id = ?", orgid).Preload("SpSupplierWarehousingCancelOrder", "status= 1 and user_org_id = ?", orgid).Order("ctime desc").Find(&out).Error
	return out, total, err
}

func GetGoodOrderDetail(id int64, orgid int64) (models.SpSupplierWarehouseOut, error) {
	out := models.SpSupplierWarehouseOut{}
	err := XTReadDB().Where("id = ? and user_org_id = ? and status = 1", id, orgid).Find(&out).Error
	return out, err
}

func UpdateGoodWarehouseOut(id int64, out models.SpSupplierWarehouseOut) error {

	err := XTWriteDB().Model(&out).Where("id=? and status = 1", id).Updates(map[string]interface{}{"arrearage": out.Arrearage, "payment": out.Payment, "rate_of_concession": out.RateOfConcession, "discount_amount": out.DiscountAmount, "document_date": out.DocumentDate, "return_remake": out.ReturnRemake, "supplier_id": out.SupplierId}).Error
	return err
}

func UpdateGoodWarehouseOutOrder(order *models.SpSupplierWarehousingOutOrder) error {

	err := XTWriteDB().Model(&order).Where("id = ? and status = 1", order.ID).Updates(map[string]interface{}{"project_id": order.ProjectId, "is_source": order.IsSource, "count": order.Count, "price": order.Price, "remark": order.Remark, "supply_batch_number": order.SupplyBatchNumber, "supply_product_date": order.SupplyProductDate, "supply_expiry_date": order.SupplyExpiryDate, "supply_type": order.SupplyType, "supply_specification_name": order.SupplySpecificationName, "supply_total": order.SupplyTotal, "supply_manufacturer": order.SupplyManufacturer, "name": order.Name, "supply_unit": order.SupplyUnit, "manufacturer_id": order.ManufacturerId, "supply_license_number": order.SupplyLicenseNumber, "warehousing_id": order.WarehousingId, "warehouse_info_id": order.WarehouseInfoId, "min_price": order.MinPrice}).Error
	return err
}

func DeletePurchOrder(id int64, orgid int64) error {

	err := XTWriteDB().Model(&models.SupplierWarehouseInfo{}).Where("id = ? and status =1", id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	err = XTWriteDB().Model(&models.SupplierWarehousingInfoOrder{}).Where("warehousing_id =? and user_org_id = ? and status = 1", id, orgid).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	return err
}

func GetAllPurcaseOrderById(id int64, orgid int64) (order []*models.VSupplierWarehousingInfoOrder, err error) {

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

func GetAllGoodOrderById(id int64, orgid int64) (order []*models.VSpSupplierWarehousingOutOrder, err error) {
	db := XTReadDB().Table("xt_supplier_warehousing_out_order as o").Where("o.status = 1")
	if id > 0 {
		db = db.Where("o.warehouse_out_id = ?", id)
	}
	if orgid > 0 {
		db = db.Where("o.user_org_id =? and o.is_warehouse= 1", orgid)
	}
	err = db.Select("o.id,o.order_number,o.project_id,o.count as count,o.supply_unit,o.is_source,o.warehousing_id,o.warehouse_out_id").Find(&order).Error
	return order, err
}

func GetAllGoodOrderByIdSix(id int64, orgid int64) (order []*models.VSpSupplierWarehousingOutOrder, err error) {
	db := XTReadDB().Table("xt_supplier_warehousing_out_order as o").Where("o.status = 1")
	if id > 0 {
		db = db.Where("o.warehousing_id = ?", id)
	}
	if orgid > 0 {
		db = db.Where("o.user_org_id =? and o.is_warehouse= 1", orgid)
	}
	err = db.Select("o.id,o.order_number,o.project_id,o.count as count,o.supply_unit,o.is_source").Find(&order).Error
	return order, err
}

func GetAllGoodOrderByIdTwo(id int64, orgid int64) (order []*models.SpSupplierWarehousingOutOrder, err error) {

	err = XTReadDB().Where("warehouse_out_id = ? and user_org_id = ? and status = 1 and is_warehouse = 2", id, orgid).Find(&order).Error
	return order, err
}

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

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

func GetReturnOrder(id int64, orgid int64) error {

	err := XTWriteDB().Model(&models.SupplierWarehouseInfo{}).Where("id = ? and status = 1 and user_org_id = ?", id, orgid).Updates(map[string]interface{}{"is_check": 2, "mtime": time.Now().Unix(), "check_time": 0, "checker": 0}).Error
	return err
}

func CheckGoodOrder(id int64, orgid int64, out models.SpSupplierWarehouseOut) error {

	err := XTWriteDB().Model(&models.SpSupplierWarehouseOut{}).Where("id = ? and user_org_id =? and status = 1", id, orgid).Updates(map[string]interface{}{"is_check": out.IsCheck, "checker": out.Checker, "check_time": out.CheckTime, "mtime": time.Now().Unix()}).Error
	return err
}

func ModefySupplyWarehousing(is_warehose int64, warehousing_id int64, orgid int64) error {

	err := XTWriteDB().Model(&models.SupplierWarehouseInfo{}).Where("id = ? and status = 1 and user_org_id =?", warehousing_id, orgid).Updates(map[string]interface{}{"is_warehouse": is_warehose, "mtime": time.Now().Unix()}).Error
	return err
}

func GetAllDoctorSix(orgid int64, appid int64) (appRole []*models.App_Role, err error) {

	err = UserReadDB().Where("org_id = ? AND app_id = ? AND status = 1", orgid, appid).Find(&appRole).Error
	return appRole, err
}

func GetSingleDrugWarehouseOrder(record_date int64, orgid int64) (*models.DrugWarehouse, error) {
	warehouse := models.DrugWarehouse{}
	var err error
	err = XTReadDB().Model(&warehouse).Where("warehousing_time = ? and org_id = ? and status = 1", record_date, orgid).Find(&warehouse).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &warehouse, nil
}

func GetSindleWarehouse(record_date int64, orgid int64) (*models.Warehousing, error) {
	warehousing := models.Warehousing{}
	var err error
	err = XTReadDB().Model(&warehousing).Where("warehousing_time = ? and org_id = ? and status = 1", record_date, orgid).Find(&warehousing).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &warehousing, nil
}

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

func GetSupplyCancelOrder(orgid int64) (total int64, err error) {
	err = XTReadDB().Model(&models.SpSupplierWarehouseCancel{}).Where("user_org_id = ?", orgid).Count(&total).Error
	return total, err
}

func CreateReturnCacelOrder(cancel models.SpSupplierWarehouseCancel) error {

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

func GetLastReturnCancelOrder(orgid int64) (models.SpSupplierWarehouseCancel, error) {

	cancel := models.SpSupplierWarehouseCancel{}
	err := XTReadDB().Where("user_org_id =? and status = 1", orgid).Find(&cancel).Error
	return cancel, err
}

func CreateCancelReturnOrder(order *models.SpSupplierWarehousingCancelOrder) error {

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

func GetReturnCancelOrder(id int64, orgid int64) (models.SpSupplierWarehouseCancel, error) {

	cancel := models.SpSupplierWarehouseCancel{}
	err := XTReadDB().Where("id = ? and status= 1 and user_org_id =?", id, orgid).Find(&cancel).Error
	return cancel, err
}

func GetReturnCancelOrderList(id int64, orgid int64) (order []*models.SpSupplierWarehousingCancelOrder, err error) {

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

func GetAllGoodReturnOrderList(checkid int64, keyword string, page int64, limit int64, startime int64, endtime int64, orgid int64) (order []*models.VmSpSupplierWarehouseCancel, total int64, err error) {

	db := XTReadDB().Table("sgj_xt.xt_supplier_warehouse_cancel").Where("sgj_xt.xt_supplier_warehouse_cancel.status = 1")
	likeKey := "%" + keyword + "%"
	offset := (page - 1) * limit
	if checkid > 0 {
		db = db.Where("sgj_xt.xt_supplier_warehouse_cancel.is_check = ?", checkid)
	}
	if len(keyword) > 0 {
		db = db.Joins("join sgj_xt.xt_supplier_name on sgj_xt.xt_supplier_name.id = sgj_xt.xt_supplier_warehouse_cancel.supplier_id")
		db = db.Where("sgj_xt.xt_supplier_warehouse_cancel.number like ? or sgj_xt.xt_supplier_name.supplier_name  like ? ", likeKey, likeKey).Group("xt_supplier_warehouse_cancel.id")
	}
	if startime > 0 {
		db = db.Where("sgj_xt.xt_supplier_warehouse_cancel.record_date >= ?", startime)
	}

	if endtime > 0 {
		db = db.Where("sgj_xt.xt_supplier_warehouse_cancel.record_date <= ?", endtime)
	}
	if orgid > 0 {
		db = db.Where("sgj_xt.xt_supplier_warehouse_cancel.user_org_id = ?", orgid)
	}
	err = db.Count(&total).Offset(offset).Limit(limit).Preload("SpSupplierWarehousingCancelOrder", "status= 1 and user_org_id = ?", orgid).Order("ctime desc").Find(&order).Error
	return order, total, err
}

func GetGoodReturnDetail(id int64, orgid int64) (models.VmSpSupplierWarehouseCancel, error) {
	cancel := models.VmSpSupplierWarehouseCancel{}
	db := XTReadDB().Model(&cancel).Where("status = 1")
	if id > 0 {
		db = db.Where("id = ?", id)
	}
	if orgid > 0 {
		db = db.Where("user_org_id = ?", orgid)
	}
	err := db.Find(&cancel).Error
	return cancel, err
}

func GetGoodReturnOrderDetail(id int64, orgid int64) (order []*models.SpSupplierWarehousingCancelOrder, err error) {

	db := XTReadDB().Model(&order).Where("status =1")
	if id > 0 {
		db = db.Where("warehouse_cancel_id = ?", id)
	}
	if orgid > 0 {
		db = db.Where("user_org_id = ?", orgid)
	}
	err = db.Find(&order).Error
	return order, err
}

func UpdateWarehouseCancelOrder(order *models.SpSupplierWarehousingCancelOrder) error {

	err = XTWriteDB().Model(&order).Where("id = ? and status = 1", order.ID).Updates(map[string]interface{}{"manufacturer_id": order.ManufacturerId, "order_number": order.OrderNumber, "project_id": order.ProjectId, "is_source": order.IsSource, "count": order.Count, "price": order.Price, "remark": order.Remark, "rate_of_concession": order.RateOfConcession, "discount_amount": order.DiscountAmount, "supply_specification_name": order.SupplySpecificationName, "supply_type": order.SupplyType, "supply_total": order.SupplyTotal, "supply_manufacturer": order.SupplyManufacturer, "name": order.Name, "supply_unit": order.SupplyUnit, "supply_license_number": order.SupplyLicenseNumber, "supply_count": order.SupplyCount, "deposit_rate": order.DepositRate}).Error
	return err
}

func UpdateWarehouseCancel(id int64, cancel models.SpSupplierWarehouseCancel) error {

	err := XTWriteDB().Model(&cancel).Where("id = ? and status = 1", id).Updates(map[string]interface{}{"rate_of_concession": cancel.RateOfConcession, "discount_amount": cancel.DiscountAmount, "document_date": cancel.DocumentDate, "supplier_id": cancel.SupplierId, "arrearage": cancel.Arrearage, "payment": cancel.Payment, "return_remark": cancel.ReturnRemark}).Error
	return err
}

func GetSupplyCancelOrderById(warehouse_out_id int64, orgid int64) (*models.SpSupplierWarehouseCancel, error) {
	cancel := models.SpSupplierWarehouseCancel{}
	var err error
	err = XTReadDB().Where("warehouse_out_id = ? and user_org_id = ? and status = 1", warehouse_out_id, orgid).Find(&cancel).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &cancel, nil
}

func UpdateSupplyGoodOrder(id int64, out models.SpSupplierWarehouseOut) error {

	err := XTWriteDB().Model(&models.SpSupplierWarehouseOut{}).Where("id = ? and status = 1", id).Updates(map[string]interface{}{"is_check": out.IsCheck, "checker": out.Checker, "check_time": out.CheckTime}).Error
	return err
}

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

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

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

func GetDrugSupplyWarehouseId(id int64, orgid int64) (models.DrugWarehouseInfo, error) {
	info := models.DrugWarehouseInfo{}
	err := XTReadDB().Where("supply_warehouse_id = ? and org_id = ? and status = 1", id, orgid).Find(&info).Error
	return info, err
}

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

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

func UpdateDrugSupplyWarehousingInfo(id int64, orgid int64) error {

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

func UpdateDrugSupplyFlow(id int64, orgid int64) error {

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

func UpdateGoodSupplyWarehousingInfo(id int64, orgid int64) error {

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

func UpdateGoodSupplyFlow(id int64, orgid int64) error {

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

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

	err = XTReadDB().Where("supply_warehouse_id <> ? and org_id = ? and status = 1", id, orgid).Find(&info).Error
	return info, err
}

func UpdateSupplyWarehousing(id int64, orgid int64) error {

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

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

	err = XTReadDB().Where("supply_warehouse_id <> ? and org_id = ? and status = 1", id, orgid).Find(&info).Error
	return info, err
}

func UpdateGoodWarehousing(id int64, orgid int64) error {
	err := XTWriteDB().Model(&models.Warehousing{}).Where("supply_warehouse_id = ? and org_id = ? and status = 1", id, orgid).Updates(map[string]interface{}{"status": 0}).Error
	return err
}

func UpdateSupplyWarehousingById(id int64, orgid int64) error {

	err := XTWriteDB().Model(&models.SupplierWarehouseInfo{}).Where("id = ? and user_org_id =? and status = 1", id, orgid).Updates(map[string]interface{}{"is_warehouse": 1}).Error
	return err
}

func DeleteGoodOrder(id int64, orgid int64) error {

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

	err = XTWriteDB().Model(&models.SpSupplierWarehousingOutOrder{}).Where("warehouse_out_id = ? and user_org_id = ? and status = 1", id, orgid).Updates(map[string]interface{}{"status": 0}).Error
	return err
}
func GetSupplyCancelWarehouse(id int64, orgid int64) (cancel []*models.SpSupplierWarehouseCancel, err error) {

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

func GetGoodOrderListById(id int64, orgid int64) (out []*models.VmSpSupplierWarehousingOutOrder, err error) {

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

func GetGoodCanceListById(id int64, orgid int64) (cancel []*models.VmSpSupplierWarehousingCancelOrder, err error) {

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

func CreateDrugFlowSix(drugflow []*models.DrugFlow) (err error) {
	if len(drugflow) > 0 {
		utx := writeDb.Begin()
		if len(drugflow) > 0 {
			thisSQL := "INSERT INTO xt_drug_flow (warehousing_id, drug_id, number,batch_number,count,user_org_id,patient_id,system_time,consumable_type,is_sys,warehousing_order,warehouse_out_id,warehouse_out_order_number,is_edit,cancel_stock_id,cancel_order_number,manufacturer,dealer,creator,update_creator,status,ctime,mtime,price,warehousing_detail_id,warehouse_out_detail_id,cancel_out_detail_id,expire_date,product_date,max_unit,min_unit,supply_warehouse_id,supply_warehouse_detail_info,storehouse_id) VALUES "
			insertParams := make([]string, 0)
			insertData := make([]interface{}, 0)
			for _, info := range drugflow {

				insertParams = append(insertParams, "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
				insertData = append(insertData, info.WarehousingId)
				insertData = append(insertData, info.DrugId)
				insertData = append(insertData, info.Number)
				insertData = append(insertData, info.BatchNumber)
				insertData = append(insertData, info.Count)
				insertData = append(insertData, info.UserOrgId)
				insertData = append(insertData, info.PatientId)
				insertData = append(insertData, info.SystemTime)
				insertData = append(insertData, info.ConsumableType)
				insertData = append(insertData, info.IsSys)
				insertData = append(insertData, info.WarehousingOrder)
				insertData = append(insertData, info.WarehouseOutId)
				insertData = append(insertData, info.WarehouseOutOrderNumber)

				insertData = append(insertData, info.IsEdit)
				insertData = append(insertData, info.CancelStockId)
				insertData = append(insertData, info.CancelOrderNumber)
				insertData = append(insertData, info.Manufacturer)
				insertData = append(insertData, info.Dealer)
				insertData = append(insertData, info.Creator)
				insertData = append(insertData, info.UpdateCreator)
				insertData = append(insertData, info.Status)
				insertData = append(insertData, info.Ctime)
				insertData = append(insertData, info.Mtime)
				insertData = append(insertData, info.Price)
				insertData = append(insertData, info.WarehousingDetailId)
				insertData = append(insertData, info.WarehouseOutDetailId)
				insertData = append(insertData, info.CancelOutDetailId)
				insertData = append(insertData, info.ExpireDate)
				insertData = append(insertData, info.ProductDate)
				insertData = append(insertData, info.MaxUnit)
				insertData = append(insertData, info.MinUnit)
				insertData = append(insertData, info.SupplyWarehouseId)
				insertData = append(insertData, info.SupplyWarehouseDetailInfo)
				insertData = append(insertData, info.StorehouseId)
			}
			thisSQL += strings.Join(insertParams, ", ")
			err = utx.Exec(thisSQL, insertData...).Error
			if err != nil {
				utx.Rollback()
				return
			}
		}
		utx.Commit()
	}
	return
}

func CheckReturnOrder(id int64, orgid int64, cancel models.SpSupplierWarehouseCancel) error {

	err := XTWriteDB().Model(&cancel).Where("id = ? and user_org_id = ? and status = 1", id, orgid).Updates(map[string]interface{}{"is_check": cancel.IsCheck, "checker": cancel.Checker, "check_time": cancel.CheckTime}).Error
	return err
}

func GetSupplyCancelOrderDetail(id int64, orgid int64) (cancel []*models.SpSupplierWarehousingCancelOrder, err error) {

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

func DeletePurchaseOrder(id int64) error {

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

func DeleteGoodOrderById(id int64) error {

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

func GetlastWarehouseOutById(user_org_id int64, record_date int64) (models.WarehouseOut, error) {

	out := models.WarehouseOut{}
	err := XTReadDB().Where("org_id = ? and warehouse_out_time = ? and is_sys = 0 and status = 1", user_org_id, record_date).Find(&out).Error
	return out, err
}

func GetDrugWarehouseOutById(orgid int64, record_date int64) (*models.DrugWarehouseOut, error) {

	out := models.DrugWarehouseOut{}
	var err error
	err = XTReadDB().Where("org_id = ? and warehouse_out_time = ? and status =1 and is_sys = 0", orgid, record_date).Find(&out).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &out, nil
}

func GetLastDrugWarehouseById(orgid int64, record_date int64) (models.DrugWarehouseOut, error) {

	out := models.DrugWarehouseOut{}
	err := XTReadDB().Where("org_id = ? and warehouse_out_time =? and status = 1 and is_sys =0 ", orgid, record_date).Last(&out).Error
	return out, err
}

func UpdateSupplyCancelById(id int64, order models.SpSupplierWarehousingCancelOrder) error {

	err := XTReadDB().Model(&order).Where("id = ? and status = 1", id).Updates(map[string]interface{}{"source_count": order.SourceCount}).Error
	return err
}

func DeleteReturnOrder(id int64) error {

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

func DeleteReturnOrderById(id int64) error {
	err = XTWriteDB().Model(&models.SpSupplierWarehousingCancelOrder{}).Where("id = ? and status = 1", id).Updates(map[string]interface{}{"status": 0}).Error
	return err
}

func ModefyReturnOrder(id int64) error {

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

func UpdateWarehousingInfoById(goodid int64, supply_warehouse_id int64, info models.WarehousingInfo) error {

	err := XTWriteDB().Model(&info).Where("good_id = ? and supply_warehouse_detail_info = ? and status = 1", goodid, supply_warehouse_id).UpdateColumn("stock_count", gorm.Expr("stock_count + ?", info.StockCount)).Error
	return err
}

func DeleteGoodWarehouseOut(goodid int64, supply_warehouse_id int64, orgid int64) error {

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

	err = XTWriteDB().Model(&models.VmStockFlow{}).Where("good_id = ? and supply_cancel_out_id = ? and status = 1 and user_org_id =?", goodid, supply_warehouse_id, orgid).Updates(map[string]interface{}{"status": 0}).Error

	return err
}
func UpdateDrugWasehousring(goodid int64, supply_warehouse_id int64, info models.DrugWarehouseInfo) error {

	err := XTWriteDB().Model(&info).Where("drug_id = ? and supply_warehouse_detail_info = ? and status = 1", goodid, supply_warehouse_id).UpdateColumn("stock_max_number", gorm.Expr("stock_max_number + ?", info.StockMaxNumber)).Error
	return err
}

func UpdateDrugWasehousringOne(goodid int64, supply_warehouse_id int64, info models.DrugWarehouseInfo) error {

	err := XTWriteDB().Model(&info).Where("drug_id = ? and supply_warehouse_detail_info = ? and status = 1", goodid, supply_warehouse_id).UpdateColumn("stock_min_number", gorm.Expr("stock_min_number + ?", info.StockMinNumber)).Error
	return err
}

func DeleteDrugWarehouseOutNight(goodid int64, supply_warehouse_id int64) error {

	err := XTWriteDB().Model(&models.DrugWarehouseOutInfo{}).Where("drug_id = ? and supply_cancel_out_id = ? and status = 1", goodid, supply_warehouse_id).Updates(map[string]interface{}{"status": 0}).Error

	err = XTWriteDB().Model(&models.DrugFlow{}).Where("drug_id = ? and supply_cancel_out_id = ? and status = 1", goodid, supply_warehouse_id).Updates(map[string]interface{}{"status": 0}).Error

	return err
}

func GetGoodIsSource(warehousing_id int64, project_id int64, orgid int64) (*models.SupplierWarehousingInfoOrder, error) {
	info := models.SupplierWarehousingInfoOrder{}
	var err error
	err = XTReadDB().Model(&info).Where("warehousing_id = ? and project_id = ? and user_org_id = ? and status = 1", warehousing_id, project_id, orgid).Find(&info).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &info, nil
}

func ModfySupplyWarehouseOut(warehousing_id int64, orgid int64) error {

	out := models.SpSupplierWarehouseOut{}
	err := XTWriteDB().Model(&out).Where("warehousing_id = ? and user_org_id =? and status = 1", warehousing_id, orgid).Updates(map[string]interface{}{"warehousing_id": 0, "number": ""}).Error
	return err
}

func FindWarehousingInfoTwenTy(goodId int64, supply_warehouse_detail_info int64, source int64, storehouse_id int64) (models.WarehousingInfo, error) {

	info := models.WarehousingInfo{}
	var err error
	if source == 1 {
		err = XTReadDB().Select(" good_id,sum(stock_count) as stock_count").Where("good_id = ? and status = 1 and supply_warehouse_detail_info =? and storehouse_id = ?", goodId, supply_warehouse_detail_info, storehouse_id).Find(&info).Error

	}
	if source == 2 {
		err = XTReadDB().Select(" good_id,sum(stock_count) as stock_count").Where("good_id = ? and status = 1 and storehouse_id = ?", goodId, storehouse_id).Find(&info).Error

	}
	return info, err
}

func GetDrugTotalCountTwenTy(drugid int64, supply_warehouse_detail_info int64, source int64, storehouse_id int64) (list []*models.VmDrugWarehouseInfo, err error) {

	if source == 1 {
		db := XTReadDB().Table("xt_drug_warehouse_info as x").Where("x.status = 1")
		table := XTReadDB().Table("xt_base_drug as d").Where("d.status = 1")
		fmt.Println(table)
		if drugid > 0 {
			db = db.Where("x.drug_id = ?", drugid)
		}
		if supply_warehouse_detail_info > 0 {
			db = db.Where("x.supply_warehouse_detail_info = ?", supply_warehouse_detail_info)
		}
		if storehouse_id > 0 {
			db = db.Where("x.storehouse_id= ?", storehouse_id)
		}
		err = db.Select("x.drug_id,x.stock_max_number,x.stock_min_number,d.min_number,d.max_unit,d.min_unit,x.max_unit as count_unit,x.supply_warehouse_detail_info").Joins("left join xt_base_drug as d on d.id = x.drug_id").Scan(&list).Error
	}

	if source == 2 {
		db := XTReadDB().Table("xt_drug_warehouse_info as x").Where("x.status = 1")
		table := XTReadDB().Table("xt_base_drug as d").Where("d.status = 1")
		fmt.Println(table)
		if drugid > 0 {
			db = db.Where("x.drug_id = ?", drugid)
		}
		err = db.Select("x.drug_id,x.stock_max_number,x.stock_min_number,d.min_number,d.max_unit,d.min_unit,x.max_unit as count_unit,x.supply_warehouse_detail_info").Joins("left join xt_base_drug as d on d.id = x.drug_id").Scan(&list).Error

	}
	return list, err
}

func GetSupplyWarehouseOutIsExsit(warehouse_out_id int64, project_id int64, orgid int64) (*models.SpSupplierWarehousingOutOrder, error) {

	out := models.SpSupplierWarehousingOutOrder{}
	var err error
	err = XTReadDB().Where("warehouse_out_id = ? and project_id = ? and user_org_id = ? and status = 1", warehouse_out_id, project_id, orgid).Find(&out).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &out, nil
}

func ModfySupplyCancel(id int64, orgid int64, project_id int64) error {

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

	err = XTWriteDB().Model(models.SpSupplierWarehousingCancelOrder{}).Where("warehouse_cancel_id = ? and user_org_id = ? and status = 1 and project_id = ?", id, orgid, project_id).Updates(map[string]interface{}{"warehouse_info_id": 0, "warehouse_out_id": 0, "warehousing_id": 0, "good_number": "", "order_number": ""}).Error
	return err
}

func UpdateSupplyWarehouseInfo(id int64) error {

	err = XTWriteDB().Model(&models.SupplierWarehouseInfo{}).Where("id = ? and status= 1").Updates(map[string]interface{}{"is_warehouse": 2}).Error
	return err
}

func GetDrugWarehosueInfoByWarehousingId(drug_id int64, supply_warehouse_id int64, orgid int64) (models.DrugWarehouseOutInfo, error) {

	info := models.DrugWarehouseOutInfo{}
	err := XTReadDB().Where("drug_id = ? and supply_warehouse_id = ? and org_id = ? and status = 1", drug_id, supply_warehouse_id, orgid).Last(&info).Error
	return info, err
}

func GetGoodWarehouseInfoByWarehousingId(good_id int64, supply_warehouse_id int64, orgid int64) (models.WarehouseOutInfo, error) {

	info := models.WarehouseOutInfo{}
	err := XTReadDB().Where("good_id = ? and supply_warehouse_id = ? and org_id = ? and status = 1", good_id, supply_warehouse_id, orgid).Last(&info).Error
	return info, err
}

func GetAllDrugWaresingList(drug_id int64, org_id int64) (info []*models.SpDrugWarehouseInfo, err error) {

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

func GetAllGoodWaresingList(good_id int64, org_id int64) (info []*models.SpWarehouseInfo, err error) {

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

func GetReturnOrderById(id int64) (models.SpSupplierWarehouseCancel, error) {

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

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

func GetWarehouseOutById(id int64, orgid int64) (out []*models.WarehouseOutInfo, err error) {

	err = XTReadDB().Where("warehouse_out_id = ? and status= 1 and org_id = ?", id, orgid).Find(&out).Error
	return out, err
}

func DeleteWarehouseOutById(id int64) error {

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

func GetDrugWarehouseByDate(operation_time int64, orgid int64) (models.DrugWarehouseOut, error) {

	out := models.DrugWarehouseOut{}
	err := XTReadDB().Where("warehouse_out_time = ? and org_id = ? and status =1 and is_sys =0 ", operation_time, orgid).Find(&out).Error
	return out, err
}

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

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

func UpdateDrugWarehouseById(id int64) error {

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

func UpdateWarehouseingById(id int64) error {

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

func UpdateSupplyOrderListById(id int64) error {

	err := XTWriteDB().Model(models.SpSupplierWarehousingOutOrder{}).Where("id = ? and status = 1", id).Updates(map[string]interface{}{"is_warehouse": 2}).Error
	return err
}

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

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

func GetAllGoodWarehouseInfo(orgid int64) (info []*models.WarehousingInfo, err error) {
	err = XTReadDB().Where("org_id = ? and status = 1 and supply_warehouse_id>0", orgid).Find(&info).Error
	return info, err
}

func GetLastDrugWarehosueInfoByWarehouseOutId(orgid int64, warehouse_out_id int64) (models.XtDrugWarehouseInfo, error) {
	info := models.XtDrugWarehouseInfo{}
	err := XTReadDB().Model(&info).Where("user_org_id = ? and status = 1 and supply_warehouse_id = ?", orgid, warehouse_out_id).Find(&info).Error
	return info, err
}
