package models

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

// MaycurPublicOfferingSale 每刻报销-公募销售表
type MaycurPublicOfferingSale struct {
	Id         int       `orm:"column(id);pk"`
	UserId     string    `description:"同步过来的销售ID"`
	Mobile     string    `description:"手机号"`
	Nickname   string    `description:"销售姓名"`
	DeptText   string    `description:"部门描述"`
	IsLeader   int       `description:"是否为负责人: 0-否; 1-是"`
	CreateTime time.Time `description:"创建时间"`
	ModifyTime time.Time `description:"更新时间"`
}

func (m *MaycurPublicOfferingSale) TableName() string {
	return "maycur_public_offering_sale"
}

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

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

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

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

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

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

func (m *MaycurPublicOfferingSale) 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 *MaycurPublicOfferingSale) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*MaycurPublicOfferingSale, 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
}
