package semantic_analysis

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

// SaCompareSearchKeyword 文档比对搜索关键词表
type SaCompareSearchKeyword struct {
	SaCompareSearchKeywordId int       `orm:"column(sa_compare_search_keyword_id);pk"`
	CompareId                int       `description:"文档比对ID"`
	Keyword                  string    `description:"关键词"`
	CreateTime               time.Time `description:"创建时间"`
}

var SaCompareSearchKeywordColumns = struct {
	SaCompareSearchKeywordId string
	CompareId                string
	Keyword                  string
	CreateTime               string
}{
	SaCompareSearchKeywordId: "sa_compare_search_keyword_id",
	CompareId:                "compare_id",
	Keyword:                  "keyword",
	CreateTime:               "create_time",
}

func (m *SaCompareSearchKeyword) TableName() string {
	return "sa_compare_search_keyword"
}

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

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

func (m *SaCompareSearchKeyword) Del() (err error) {
	o := orm.NewOrm()
	sql := `DELETE FROM sa_compare_search_keyword WHERE sa_compare_search_keyword_id = ? LIMIT 1`
	_, err = o.Raw(sql, m.SaCompareSearchKeywordId).Exec()
	return
}

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

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

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

func (m *SaCompareSearchKeyword) GetPageItemsByCondition(startSize, pageSize int, condition string, pars []interface{}, fieldArr []string, orderRule string) (total int, items []*SaCompareSearchKeyword, 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)
	totalSql := `SELECT COUNT(1) total FROM (` + sql + `) z`
	if err = o.Raw(totalSql, pars).QueryRow(&total); err != nil {
		return
	}
	sql += ` LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&items)
	return
}

type SaCompareSearchKeywordSaveReq struct {
	SaCompareId int      `description:"文档比对ID"`
	Keywords    []string `description:"关键词"`
}

func (m *SaCompareSearchKeyword) DelAndCreateSearchKeywords(compareId int, keywords []string) (err error) {
	o := orm.NewOrm()
	tx, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = tx.Rollback()
			return
		}
		_ = tx.Commit()
	}()

	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s = ?`, m.TableName(), SaCompareSearchKeywordColumns.CompareId)
	if _, e := o.Raw(sql, compareId).Exec(); e != nil {
		return e
	}
	if len(keywords) > 0 {
		items := make([]*SaCompareSearchKeyword, 0)
		for _, v := range keywords {
			items = append(items, &SaCompareSearchKeyword{
				CompareId:  compareId,
				Keyword:    v,
				CreateTime: time.Now().Local(),
			})
		}
		if _, e := o.InsertMulti(len(items), items); e != nil {
			return e
		}
	}
	return
}
