package excel

import (
	"eta/eta_mobile/utils"
	"github.com/beego/beego/v2/client/orm"
	"time"
)

type ExcelWorker struct {
	ExcelWorkerId   int       `orm:"column(excel_worker_id);pk"`
	ExcelInfoId     int       `description:"表格id"`
	SysUserId       int       `description:"创建人"`
	SysUserRealName string    `description:"创建人姓名"`
	ModifyTime      time.Time `description:"修改时间"`
	CreateTime      time.Time `description:"创建时间"`
}

func (e *ExcelWorker) TableName() string {
	return "excel_worker"
}

// 新增 协作人
func (e *ExcelWorker) AddWorker(excelInfoId int, addWorkers []*ExcelWorker, notDeleteWorkers []string) (err error) {
	o, err := orm.NewOrmUsingDB("data").Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = o.Rollback()
		} else {
			_ = o.Commit()
		}
	}()
	if len(notDeleteWorkers) > 0 {
		sql := `delete from excel_worker where excel_info_id = ? and sys_user_id not in (` + utils.GetOrmInReplace(len(notDeleteWorkers)) + `)`
		_, err = o.Raw(sql, excelInfoId, notDeleteWorkers).Exec()
		if err != nil {
			return
		}
	} else if len(notDeleteWorkers) == 0 { // 清空协作人
		sql := `delete from excel_worker where excel_info_id = ? `
		_, err = o.Raw(sql, excelInfoId).Exec()
		if err != nil {
			return
		}
	}
	if len(addWorkers) > 0 {
		_, err = o.InsertMulti(len(addWorkers), addWorkers)
	}
	return
}

// 修改
func (e *ExcelWorker) Update(cols []string) (err error) {
	o := orm.NewOrmUsingDB("data")
	_, err = o.Update(e, cols...)
	return
}

// 删除
func (e *ExcelWorker) Delete() (err error) {
	o := orm.NewOrmUsingDB("data")
	_, err = o.Delete(e)
	return
}

// 查询
func (e *ExcelWorker) GetByExcelInfoId(excelInfoId int) (items []*ExcelWorker, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `select * from excel_worker where excel_info_id = ? `
	_, err = o.Raw(sql, excelInfoId).QueryRows(&items)
	return
}

// 查询
func (e *ExcelWorker) GetBySysUserId(sysUserId int) (items []*ExcelWorker, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `select * from excel_worker where sys_user_id = ? `
	_, err = o.Raw(sql, sysUserId).QueryRows(&items)
	return
}
