package db

import (
	"context"
	"github.com/sirupsen/logrus"
	"youngee_b_api/model/gorm_model"
)

// CreateSupplierInvoice 创建服务商发票
func CreateSupplierInvoice(ctx context.Context, req *gorm_model.YounggeeSupplierInvoice) error {
	db := GetWriteDB(ctx)
	err := db.Create(&req).Error
	if err != nil {
		return err
	}
	return nil
}

// UpdateSupplierInvoice 更新服务商发票
func UpdateSupplierInvoice(ctx context.Context, req *gorm_model.YounggeeSupplierInvoice) error {
	db := GetWriteDB(ctx)
	whereCondition := gorm_model.YounggeeSupplierInvoice{InvoiceId: req.InvoiceId}
	err := db.Model(&gorm_model.YounggeeSupplierInvoice{}).Where(whereCondition).Updates(req).Error
	if err != nil {
		return err
	}
	return nil
}

// GetIncomeIdsByInvoiceId 根据invoice_id取得income_ids
func GetIncomeIdsByInvoiceId(ctx context.Context, invoiceId int) (string, error) {
	db := GetWriteDB(ctx)
	var invoiceInfo *gorm_model.YounggeeSupplierInvoice
	err := db.Model(gorm_model.YounggeeSupplierInvoice{}).Where("invoice_id = ?", invoiceId).Find(&invoiceInfo).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetSProjectDetail] error query mysql, err:%+v", err)
		return "", err
	}
	return invoiceInfo.IncomeIds, nil
}

// GetInvoiceListBySupplierId 根据invoice_status和supplier_id获取发票信息列表
func GetInvoiceListBySupplierId(ctx context.Context, supplierId int, invoiceStatus int, withdrawStatus int, pageSize int32, pageNum int32) ([]*gorm_model.YounggeeSupplierInvoice, int64, error) {
	db := GetWriteDB(ctx)
	// 1. 根据服务商id过滤
	db = db.Debug().Model(gorm_model.YounggeeSupplierInvoice{}).Where("supplier_id = ? and invoice_status = ? and withdraw_status = ?", supplierId, invoiceStatus, withdrawStatus)

	// 2. 确定查询总数和返回当前页数据
	var total int64
	var invoiceList []*gorm_model.YounggeeSupplierInvoice
	if err := db.Count(&total).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetFullProjectList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	limit := pageSize
	offset := pageSize * pageNum // assert pageNum start with 0
	err := db.Order("invoice_id desc").Limit(int(limit)).Offset(int(offset)).Find(&invoiceList).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetFullProjectList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	return invoiceList, total, nil
}
