package dao

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

type SupplierDao struct{}

func (d SupplierDao) GetSupplierInfoById(supplierId int64) (*entity.Supplier, error) {
	var supplier entity.Supplier
	err := Db.Debug().Model(&entity.Supplier{}).Where("supplier_id = ?", supplierId).First(&supplier).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return &supplier, nil
}

// 根据服务商名称/认证名搜索
func (d SupplierDao) GetSuppliersByMsg(fieldName string) ([]*entity.Supplier, error) {
	var suppliers []*entity.Supplier
	supplierId, err := strconv.ParseInt(fieldName, 10, 64)
	if err == nil {
		err1 := Db.Debug().Model(&entity.Supplier{}).Where("supplier_id = ? AND supplier_type != 0", supplierId).First(&suppliers).Error
		if err1 != nil && err1 != gorm.ErrRecordNotFound {
			return nil, err1
		}
	} else {
		err1 := Db.Debug().Model(&entity.Supplier{}).Where("supplier_name = ? OR company_name = ? OR name = ? AND supplier_type != 0", fieldName, fieldName, fieldName).Find(&suppliers).Error
		if err1 != nil {
			return nil, err
		}
	}

	return suppliers, nil
}

func (d SupplierDao) GetSupplierPhone(supplierId int64) (string, error) {
	var phone string
	err := Db.Debug().Model(&entity.Supplier{}).Where("supplier_id = ?", supplierId).Select("phone_number").First(&phone).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return "", err
	}
	return phone, nil
}
