package models

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"strings"
	"time"
)

// MaycurPublicOfferingCompany 每刻报销-公募销售表
type MaycurPublicOfferingCompany struct {
	Id         int       `orm:"column(id);pk"`
	Name       string    `description:"客户名称"`
	ShortName  string    `description:"客户简称"`
	Social     string    `description:"社会信用代码"`
	SaleNames  string    `description:"销售姓名(多个)"`
	CreateTime time.Time `description:"创建时间"`
	ModifyTime time.Time `description:"更新时间"`
}

func (m *MaycurPublicOfferingCompany) TableName() string {
	return "maycur_public_offering_company"
}

func (m *MaycurPublicOfferingCompany) Create() (err error) {
	o := orm.NewOrm()
	id, err := o.Insert(m)
	if err != nil {
		return
	}
	m.Id = int(id)
	return
}

func (m *MaycurPublicOfferingCompany) CreateMulti(items []*MaycurPublicOfferingCompany) (err error) {
	if len(items) == 0 {
		return
	}
	o := orm.NewOrm()
	_, err = o.InsertMulti(len(items), items)
	return
}

func (m *MaycurPublicOfferingCompany) Update(cols []string) (err error) {
	o := orm.NewOrm()
	_, err = o.Update(m, cols...)
	return
}

func (m *MaycurPublicOfferingCompany) Del() (err error) {
	o := orm.NewOrm()
	sql := `DELETE FROM maycur_public_offering_company WHERE id = ? LIMIT 1`
	_, err = o.Raw(sql, m.Id).Exec()
	return
}

func (m *MaycurPublicOfferingCompany) GetItemById(id int) (err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM maycur_public_offering_company WHERE id = ? LIMIT 1`
	err = o.Raw(sql, id).QueryRow(&m)
	return
}

func (m *MaycurPublicOfferingCompany) GetItemByCondition(condition string, pars []interface{}) (err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM maycur_public_offering_company WHERE 1=1 `
	sql += condition
	sql += ` LIMIT 1`
	err = o.Raw(sql, pars).QueryRow(&m)
	return
}

func (m *MaycurPublicOfferingCompany) GetCountByCondition(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf(`SELECT COUNT(1) FROM %s WHERE 1=1 %s`, m.TableName(), condition)
	err = o.Raw(sql, pars).QueryRow(&count)
	return
}

func (m *MaycurPublicOfferingCompany) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*MaycurPublicOfferingCompany, err error) {
	o := orm.NewOrm()
	fields := strings.Join(fieldArr, ",")
	if len(fieldArr) == 0 {
		fields = `*`
	}
	order := `ORDER BY create_time DESC`
	if orderRule != "" {
		order = ` ORDER BY ` + orderRule
	}
	sql := fmt.Sprintf(`SELECT %s FROM %s WHERE 1=1 %s %s`, fields, m.TableName(), condition, order)
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}
