package shanghu

import (
	orm "duoduo/database"
	"time"
)

type MerchantCardProject struct {
	ID               int64     `gorm:"column:id;type:bigint(20);primary_key;AUTO_INCREMENT" json:"id"`
	MerchantOpenID   string    `gorm:"column:merchant_open_id;type:varchar(255);NOT NULL" json:"merchant_open_id"` // open_id
	ProjectUnitPrice string    `gorm:"column:project_unit_price;type:decimal(10,2)" json:"project_unit_price"`     // 单价
	ProjectUnit      string    `gorm:"column:project_unit;type:varchar(255)" json:"project_unit"`                  // 产品单位
	ProjectUrl       string    `gorm:"column:project_url;type:varchar(255)" json:"project_url"`                    // 图片
	ProjectName      string    `gorm:"column:project_name;type:varchar(100)" json:"project_name"`                  // 产品名
	CreateBy         int64     `gorm:"column:create_by;type:bigint(20)" json:"create_by"`                          // 创建者
	UpdateBy         int64     `gorm:"column:update_by;type:bigint(20)" json:"update_by"`                          // 更新者
	CreatedAt        time.Time `gorm:"column:created_at;type:datetime(3)" json:"created_at"`                       // 创建时间
	UpdatedAt        time.Time `gorm:"column:updated_at;type:datetime(3)" json:"updated_at"`                       // 最后更新时间
	DeletedAt        time.Time `gorm:"column:deleted_at;type:datetime(3);default:null" json:"deleted_at"`          // 删除时间
}

func (m *MerchantCardProject) TableName() string {
	return "merchant_card_project"
}

func (u *MerchantCardProject) Create() (MerchantCardProject, error) {
	var doc MerchantCardProject
	var err error

	doc = *u
	err = orm.ShMysql.Table(u.TableName()).Create(&doc).Error
	if err != nil {
		return doc, err
	}

	return doc, nil
}

func (m *MerchantCardProject) GetMerchantCardProject() (MerchantCardProject, error) {
	var doc MerchantCardProject

	table := orm.ShMysql.Table(m.TableName())
	table = table.Where("id = ?  ", m.ID)

	if err := table.Select("*").First(&doc).Error; err != nil {
		return doc, err
	}

	return doc, nil
}

// list 接口使用
func (m *MerchantCardProject) GetOpenIdList(pageSize int, pageIndex int) ([]MerchantCardProject, int, error) {
	var doc []MerchantCardProject

	table := orm.ShMysql.Table(m.TableName())

	table = table.Where("merchant_open_id = ?  ", m.MerchantOpenID)
	var count int
	if err := table.Select("*").Order("id desc").Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
		return nil, 0, err
	}
	table.Count(&count)
	return doc, count, nil
}

func (m *MerchantCardProject) UpdateMerchantCardProject() error {

	if err := orm.ShMysql.Table(m.TableName()).Model(&m).Where("id = ? ", m.ID).Updates(
		map[string]interface{}{
			"project_name":       m.ProjectName,
			"project_url":        m.ProjectUrl,
			"project_unit":       m.ProjectUnit,
			"project_unit_price": m.ProjectUnitPrice,
			"update_time":        time.Now()}).Error; err != nil {
		return err
	}

	return nil
}