package service

import (
	"Xcx_New/models"
	"github.com/jinzhu/gorm"
)

type DrugConfig struct {
	ID                    int64        `gorm:"column:id" json:"id" form:"id"`
	DrugName              string       `gorm:"column:drug_name" json:"drug_name" form:"drug_name"`
	DrugCategory          int64        `gorm:"column:drug_category" json:"drug_category" form:"drug_category"`
	DrugSpec              string       `gorm:"column:drug_spec" json:"drug_spec" form:"drug_spec"`
	DrugType              int64        `gorm:"column:drug_type" json:"drug_type" form:"drug_type"`
	DrugStatus            string       `gorm:"column:drug_status" json:"drug_status" form:"drug_status"`
	Status                int64        `gorm:"column:status" json:"status" form:"status"`
	OrgId                 int64        `gorm:"column:org_id" json:"org_id" form:"org_id"`
	Manufacturer          int64        `gorm:"column:manufacturer" json:"manufacturer" form:"manufacturer"`
	DrugSpecs             []DrugConfig `gorm:"ForeignKey:DrugName;AssociationForeignKey:DrugName" json:"drug_specs"`
	RetailPrice           float64      `gorm:"column:retail_price" json:"retail_price" form:"retail_price"`
	LastPrice             float64      `gorm:"column:last_price" json:"last_price" form:"last_price"`
	MinUnit               string       `gorm:"column:min_unit" json:"min_unit" form:"min_unit"`
	HospApprFlag          int64        `gorm:"column:hosp_appr_flag" json:"hosp_appr_flag" form:"hosp_appr_flag"`
	LmtUsedFlag           int64        `gorm:"column:lmt_used_flag" json:"lmt_used_flag" form:"lmt_used_flag"`
	Total                 float64      `gorm:"column:total" json:"total" form:"total"`
	PrescribingNumberUnit string       `gorm:"column:prescribing_number_unit" json:"prescribing_number_unit" form:"prescribing_number_unit"`
}

func (DrugConfig) TableName() string {
	return "xt_base_drug"
}

func GetDrugs(orgId int64) (drugs []*DrugConfig, err error) {
	err = readDb.Model(&DrugConfig{}).Where("org_id = ? AND  status = 1  AND find_in_set('停用',drug_status) = 0", orgId).Preload("DrugSpecs", "status = 1  AND find_in_set('停用',drug_status) = 0 AND org_id = ?", orgId).Group("drug_name").Find(&drugs).Error
	return
}

func FindAllDrugByManufactureId(manufacturer_id int64, dealer_id int64, org_id int64) (goodInfo []*DrugConfig, err error) {
	db := readDb.Model(&DrugConfig{}).Where("org_id = ? AND status = 1 AND find_in_set('停用',drug_status) = 0", org_id)
	if manufacturer_id > 0 {
		db = db.Where("manufacturer = ?", manufacturer_id)
	}
	if dealer_id > 0 {
		db = db.Where("dealer = ?", dealer_id)
	}
	err = db.Preload("DrugSpecs", "status = 1 AND org_id = ? AND find_in_set('停用',drug_status) = 0", org_id).Group("drug_name").Find(&goodInfo).Error
	return goodInfo, err
}

type MedicineInsuranceDate struct {
	RecordTime int64
}

func GetLastMedicineInsurance(orgID int64, type_id int64, module int64) (mip []*models.MedicineInsurancePercentage, err error) {
	var mip_other models.MedicineInsurancePercentage
	err = readDb.Model(&models.MedicineInsurancePercentage{}).Where("user_org_id = ? AND status=1 AND  type_id = ? AND module = ?", orgID, type_id, module).Last(&mip_other).Error
	err = readDb.Model(&models.MedicineInsurancePercentage{}).Where("user_org_id = ? AND status=1 AND record_time = ? AND type_id = ? AND module = ?", orgID, mip_other.RecordTime, type_id, module).Find(&mip).Error
	return
}

type DrugWarehouseInfo struct {
	ID     int64  `gorm:"column:id" json:"id" form:"id"`
	Number string `gorm:"column:number" json:"number" form:"number"`
	Status int64  `gorm:"column:status" json:"status" form:"status"`
	OrgId  int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
}

func (DrugWarehouseInfo) TableName() string {
	return "xt_drug_warehouse_info"
}
func FindStockInNumber(orgId int64) (stockIns []*DrugWarehouseInfo, err error) {
	err = readDb.Model(&DrugWarehouseInfo{}).Where("org_id = ? AND status = 1", orgId).Group("number").Find(&stockIns).Error
	return
}

type DrugStockInfo struct {
	ID           int64   `gorm:"column:id" json:"id" form:"id"`
	DrugName     string  `gorm:"column:drug_name" json:"drug_name" form:"drug_name"`
	DrugSpec     string  `gorm:"column:drug_spec" json:"drug_spec" form:"drug_spec"`
	RetailPrice  float64 `gorm:"column:retail_price" json:"retail_price" form:"retail_price"`
	LastPrice    float64 `gorm:"column:last_price" json:"last_price" form:"last_price"`
	DrugStatus   string  `gorm:"column:drug_status" json:"drug_status" form:"drug_status"`
	Status       int64   `gorm:"column:status" json:"status" form:"status"`
	Ctime        int64   `gorm:"column:ctime" json:"ctime" form:"ctime"`
	Mtime        int64   `gorm:"column:mtime" json:"mtime" form:"mtime"`
	OrgId        int64   `gorm:"column:org_id" json:"org_id" form:"org_id"`
	DrugCode     string  `gorm:"column:drug_code" json:"drug_code" form:"drug_code"`
	HospApprFlag int64   `gorm:"column:hosp_appr_flag" json:"hosp_appr_flag" form:"hosp_appr_flag"`
	LmtUsedFlag  int64   `gorm:"column:lmt_used_flag" json:"lmt_used_flag" form:"lmt_used_flag"`

	QueryWarehousingInfo  []models.DrugWarehouseInfo    `gorm:"ForeignKey:DrugId;AssociationForeignKey:ID" json:"query_drug_warehousing_info"`
	QuerySalesReturnInfo  []models.DrugSalesReturnInfo  `gorm:"ForeignKey:DrugId;AssociationForeignKey:ID" json:"query_drug_sales_return_info"`
	QueryWarehouseOutInfo []models.DrugWarehouseOutInfo `gorm:"ForeignKey:DrugId;AssociationForeignKey:ID" json:"query_drug_warehouseout_info"`
	QueryCancelStockInfo  []models.DrugCancelStockInfo  `gorm:"ForeignKey:DrugId;AssociationForeignKey:ID" json:"query_drug_cancel_stock_info"`

	Total                 float64 `gorm:"column:total" json:"total" form:"total"`
	PrescribingNumberUnit string  `gorm:"column:prescribing_number_unit" json:"prescribing_number_unit" form:"prescribing_number_unit"`
}

func (DrugStockInfo) TableName() string {
	return "xt_base_drug"
}

func FindAllDrugStockInfo(orgId int64, page int64, limit int64, keyword string, drugCategory int64, startTime int64, endTime int64) (list []*DrugStockInfo, total int64, err error) {
	db := readDb.Model(&DrugStockInfo{})
	if drugCategory > 0 {
		db = db.Where("xt_base_drug.org_id = ? AND xt_base_drug.status = 1 AND xt_base_drug.drug_category = ?", orgId, drugCategory)
	} else {
		db = db.Where("xt_base_drug.org_id = ? AND xt_base_drug.status = 1", orgId)
	}

	if startTime > 0 {

		db = db.Preload("QueryWarehousingInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("org_id = ? AND status = 1 and ctime >=?", orgId, startTime)
		})
		db = db.Preload("QuerySalesReturnInfo", "org_id = ? AND status = 1 and ctime>=?", orgId, startTime)
		db = db.Preload("QueryWarehouseOutInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("org_id = ? AND status = 1 and sys_record_time>=?", orgId, startTime)
		})

		db = db.Preload("QueryCancelStockInfo", "org_id = ? AND status = 1 and ctime>=?", orgId, startTime)
	} else {

		db = db.Preload("QueryWarehousingInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("org_id = ? AND status = 1", orgId)
		})
		db = db.Preload("QuerySalesReturnInfo", "org_id = ? AND status = 1", orgId)
		db = db.Preload("QueryWarehouseOutInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("org_id = ? AND status = 1", orgId)
		})
		db = db.Preload("QueryCancelStockInfo", "org_id = ? AND status = 1", orgId)
	}

	if endTime > 0 {
		db = db.Preload("QueryWarehousingInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("org_id = ? AND status = 1  and ctime <=?", orgId, startTime, endTime)
		})
		db = db.Preload("QuerySalesReturnInfo", "org_id = ? AND status = 1 and ctime>=? and ctime<=?", orgId, startTime, endTime)
		db = db.Preload("QueryWarehouseOutInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("org_id = ? AND status = 1 and sys_record_time>=? and sys_record_time<=?", orgId, startTime, endTime)
		})
		db = db.Preload("QueryCancelStockInfo", "org_id = ? AND status = 1 and ctime >=? and ctime<=?", orgId, startTime, endTime)
	} else {

		db = db.Preload("QueryWarehousingInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("org_id = ? AND status = 1", orgId)
		})
		db = db.Preload("QuerySalesReturnInfo", "org_id = ? AND status = 1", orgId)
		db = db.Preload("QueryWarehouseOutInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("org_id = ? AND status = 1", orgId)
		})
		db = db.Preload("QueryCancelStockInfo", "org_id = ? AND status = 1", orgId)
	}

	if len(keyword) > 0 {
		likeKey := "%" + keyword + "%"
		db = db.Where("xt_base_drug.drug_name LIKE ? OR xt_base_drug.drug_spec LIKE ?", likeKey, likeKey)
	}
	db = db.Count(&total)
	offset := (page - 1) * limit
	err = db.Offset(offset).Limit(limit).Order("ctime desc").Find(&list).Error
	return
}

func GetCancelDrugOrderPrint(id []string, orgid int64) (info []*models.DrugCancelStock, err error) {

	db := XTReadDB().Model(&info)

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

	err = db.Preload("DrugCancelStockInfo", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = 1 AND org_id = ?", orgid).Preload("BaseDrugLib", "status = 1 AND org_id= ?", orgid)
	}).Find(&info).Error

	return info, err
}

func GetDrugCancelExportList(orderid []string, orgid int64) (info []*models.DrugCancelStockInfo, err error) {

	db := XTReadDB().Model(&info)
	if len(orderid) > 0 {
		db = db.Where("cancel_stock_id in(?)", orderid)
	}
	if orgid > 0 {
		db = db.Where("org_id = ?", orgid)
	}
	db = db.Preload("BaseDrugLib", "status = 1 and org_id = ?", orgid)
	err = db.Find(&info).Error
	return info, err
}

func GetDrugWarehouseInfoPrint(startime int64, endtime int64, orgid int64) (info []*models.XtDrugWarehouseInfo, err error) {

	db := XTReadDB().Table("xt_drug_warehouse_info").Where("status = 1")
	if startime > 0 {
		db = db.Where("ctime >=?", startime)
	}
	if endtime > 0 {
		db = db.Where("ctime<=?", endtime)
	}
	if orgid > 0 {
		db = db.Where("org_id = ?", orgid)
	}
	err = db.Preload("XtBaseDrug", "status = 1 and org_id = ?", orgid).Group("drug_id").Find(&info).Error

	//err = db.Select("x.id,x.warehousing_id,x.drug_id,x.number,x.product_date,x.expiry_date,sum(x.warehousing_count) as warehousing_count,x.price,x.total_price,x.dealer,x.manufacturer,x.remark,x.is_return,x.warehousing_order,x.type,x.retail_price,x.retail_total_price,x.warehouseing_unit,x.max_unit,x.min_unit,x.stock_max_number,x.stock_min_number,x.batch_number").Group("x.drug_id").Find(&DrugWarehouseInfo{}).Error
	return info, err
}

//func GetDrugWarehouseInfoList(startime int64,endtime int64,orgid int64)(info []*models.BloodAutomaticReduceDetail,err error)  {
//
//
//  db := XTReadDB().Table("xt_drug_warehouse_info as x").Where("x.status = 1")
//  if startime > 0 {
//    db = db.Where("x.ctime >=?", startime)
//  }
//  if endtime>0{
//    db = db.Where("x.ctime<=?", endtime)
//  }
//  if orgid > 0{
//    db = db.Where("x.org_id = ?", orgid)
//  }
//
//
//}

func GetDrugOutOrderPrint(startime int64, endtime int64, orgid int64) (info []*models.XtDrugWarehouseOutInfo, err error) {

	db := XTReadDB().Table("xt_drug_warehouse_out_info").Where("status = 1")
	if startime > 0 {
		db = db.Where("ctime >=?", startime)
	}
	if endtime > 0 {
		db = db.Where("ctime<=?", endtime)
	}
	if orgid > 0 {
		db = db.Where("org_id = ?", orgid)
	}
	err = db.Preload("XtBaseDrug", "status = 1 and org_id = ?", orgid).Group("drug_id").Find(&info).Error
	return info, err
}

func GetDrugOutOrderPrintList(startime int64, endtime int64, orgid int64) (list []*models.XtDrugAutomaticReduceDetail, err error) {

	db := XTReadDB().Table("xt_drug_automatic_reduce_detail").Where("status = 1")
	if startime > 0 {
		db = db.Where("ctime >=?", startime)
	}
	if endtime > 0 {
		db = db.Where("ctime<=?", endtime)
	}
	if orgid > 0 {
		db = db.Where("org_id = ?", orgid)
	}
	err = db.Preload("XtBaseDrug", "status = 1 and org_id = ?", orgid).Find(&list).Error
	return list, err
}
