package db

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

// GetSupplierIncomeList 查询服务商收入列表
func GetSupplierIncomeList(ctx context.Context, reqData *http_model.FullSProjectIncomeListRequest) ([]*gorm_model.YounggeeSupplierIncome, int64, error) {
	db := GetReadDB(ctx)

	// 1. 根据基本信息过滤
	db = db.Debug().Model(gorm_model.YounggeeSupplierIncome{}).Where("supplier_id = ? and income_status = ?", reqData.SupplierId, reqData.IncomeStatus)

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

// UpdateSupplierIncomeStatus 修改服务商收入状态
func UpdateSupplierIncomeStatus(ctx context.Context, incomeIds []int, incomeStatus int) error {
	// 1. 建立数据库连接并修改
	db := GetReadDB(ctx)
	if err := db.Debug().Model(&gorm_model.YounggeeSupplierIncome{}).Where("income_id IN ?", incomeIds).
		Updates(gorm_model.YounggeeSupplierIncome{IncomeStatus: incomeStatus}).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[ChangeTaskStatus]2 error query mysql total, err:%+v", err)
		return err
	}
	return nil
}

// GetIncomeInfoByIncomeId 根据income_id查询收入信息
func GetIncomeInfoByIncomeId(ctx context.Context, incomeId int) (*gorm_model.YounggeeSupplierIncome, error) {
	db := GetReadDB(ctx)
	var incomeInfo *gorm_model.YounggeeSupplierIncome
	err := db.Model(&gorm_model.YounggeeSupplierIncome{}).Where("income_id = ?", incomeId).Find(&incomeInfo).Error
	if err != nil {
		return nil, err
	}
	return incomeInfo, nil
}
