package service

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

func GetInvoiceByOrderId(orgId int64, orderID int64) (*models.ServeInvoice, error) {
	var invoice models.ServeInvoice
	orderLike := "%," + strconv.FormatInt(orderID, 10) + ",%"
	err := readUserDb.Model(&models.ServeInvoice{}).Where("org_id=? and orders LIKE ?", orgId, orderLike).First(&invoice).Error
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}

	return &invoice, nil
}

func CreateInvoice(m *models.ServeInvoice) error {
	err := writeUserDb.Create(m).Error
	return err
}
func FindUnInvoiceOrders(orgID int64) (list []*models.ServeOrder, err error) {
	// 这一段是查询出还没有开票的订单
	// SELECT so.* from sgj_users.sgj_serve_order as so WHERE NOT EXISTS
	// (select o.id
	// from sgj_users.sgj_serve_order as o
	// JOIN sgj_users.sgj_serve_invoice as i ON  FIND_IN_SET(o.id, i.orders)
	// WHERE o.org_id=13 and o.order_status=2 and o.status=1 and so.id=o.id )

	err = readUserDb.Table("sgj_serve_order as so").Where("so.org_id=? and so.order_status=2 and so.status=1", orgID).Where("NOT EXISTS (?)", readUserDb.Table("sgj_serve_order as o").Joins("JOIN sgj_serve_invoice as i ON FIND_IN_SET(o.id, i.orders)").Where("o.org_id=? and o.order_status=2 and o.status=1 and i.status=1 and so.id=o.id", orgID).Select("o.id").QueryExpr()).Find(&list).Error
	return

}

func FindInvoices(orgID int64) (list []*models.ServeInvoice, err error) {
	err = readUserDb.Model(&models.ServeInvoice{}).Where("org_id=? and status=1", orgID).Find(&list).Error
	return
}
func FindServeOrdersByIDs(orgId int64, ids []int64) (hads []*models.ServeOrder, nos []*models.ServeOrder, err error) {

	err = readUserDb.Table("sgj_serve_order as so").Where("so.id IN (?) and so.org_id=? and so.order_status=2 and so.status=1", ids, orgId).Where("EXISTS (?)", readUserDb.Table("sgj_serve_order as o").Joins("JOIN sgj_serve_invoice as i ON FIND_IN_SET(o.id, i.orders)").Where("so.id IN (?) and o.org_id=? and o.order_status=2 and o.status=1 and i.status=1 and so.id=o.id", ids, orgId).Select("o.id").QueryExpr()).Find(&hads).Error
	if err != nil {
		return
	}
	err = readUserDb.Table("sgj_serve_order as so").Where("so.id  IN (?) and so.org_id=? and so.order_status=2 and so.status=1", ids, orgId).Where("NOT EXISTS (?)", readUserDb.Table("sgj_serve_order as o").Joins("JOIN sgj_serve_invoice as i ON FIND_IN_SET(o.id, i.orders)").Where("so.id IN (?) and o.org_id=? and o.order_status=2 and o.status=1 and i.status=1 and so.id=o.id", ids, orgId).Select("o.id").QueryExpr()).Find(&nos).Error
	if err != nil {
		return
	}
	return
}
