package dao

import (
	"gorm.io/gorm"
	"youngee_b_api/app/entity"
)

type EnterpriseSupplierCooperateDao struct{}

// 检查给定的服务商是否在该商家库中
func (d EnterpriseSupplierCooperateDao) EnterpriseDatabaseCheck(enterpriseId string, supplierId int64) (bool, error) {
	var count int64
	err := Db.Debug().Model(&entity.EnterpriseSupplierCooperate{}).Where("enterprise_id = ? AND supplier_id = ? AND cooperate_status != 2", enterpriseId, supplierId).Count(&count).Error
	if err != nil {
		return false, err
	}
	return count > 0, nil
}

// 批量插入数据
func (d EnterpriseSupplierCooperateDao) InsertBatch(records []*entity.EnterpriseSupplierCooperate) error {
	result := Db.Debug().Model(&entity.EnterpriseSupplierCooperate{}).Omit("agree_time", "reject_time").Create(&records)
	return result.Error
}

// 获取指定商家的服务商库
func (d EnterpriseSupplierCooperateDao) GetSupplierByEnterprise(enterpriseId string, page int, pageSize int) ([]*entity.EnterpriseSupplierCooperate, int64, error) {
	var enterpriseSupplierCooperates []*entity.EnterpriseSupplierCooperate
	var total int64
	offset := (page - 1) * pageSize
	query := Db.Model(&entity.EnterpriseSupplierCooperate{}).Where("enterprise_id = ? AND cooperate_status = 2", enterpriseId)
	query.Count(&total)
	query = query.Select("supplier_id, cooperate_num, upload_talent_num, cooperate_talent_num, b_operator, b_operator_type, agree_time")
	err := query.Order("agree_time desc").Offset(offset).Limit(pageSize).Find(&enterpriseSupplierCooperates).Error
	if err != nil {
		return nil, 0, err
	}

	return enterpriseSupplierCooperates, total, nil
}

// 获取指定商家的某个服务商数据
func (d EnterpriseSupplierCooperateDao) GetDataByEnterpriseAndSupplier(enterpriseId string, supplierId int64) (*entity.EnterpriseSupplierCooperate, error) {
	var enterpriseSupplierCooperate *entity.EnterpriseSupplierCooperate
	query := Db.Debug().Model(&entity.EnterpriseSupplierCooperate{}).Where("enterprise_id = ? AND supplier_id = ?", enterpriseId, supplierId)
	query = query.Select("supplier_id, cooperate_num, upload_talent_num, cooperate_talent_num, b_operator, b_operator_type")
	err := query.Find(&enterpriseSupplierCooperate).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return enterpriseSupplierCooperate, nil
}

// 获取邀请待确认的服务商
func (d EnterpriseSupplierCooperateDao) GetSupplierConfirmingList(enterpriseId string, page int, pageSize int) ([]*entity.EnterpriseSupplierCooperate, int64, error) {
	var enterpriseSupplierCooperates []*entity.EnterpriseSupplierCooperate
	var total int64
	offset := (page - 1) * pageSize
	query := Db.Model(&entity.EnterpriseSupplierCooperate{}).Where("enterprise_id = ? AND cooperate_status = 1", enterpriseId)
	query.Count(&total)
	query = query.Select("supplier_id,  b_operator, b_operator_type, cooperate_status, create_time")
	err := query.Order("create_time desc").Offset(offset).Limit(pageSize).Find(&enterpriseSupplierCooperates).Error
	if err != nil {
		return nil, 0, err
	}

	return enterpriseSupplierCooperates, total, nil
}
