package semantic_analysis

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

type SaCompareLabel struct {
	SaCompareLabelId int       `orm:"column(sa_compare_label_id);pk" description:"段落标签ID"`
	CompareId        int       `description:"比对ID"`
	DocId            int       `description:"文档ID"`
	SectionId        int       `description:"段落ID"`
	LabelId          int       `description:"标签ID"`
	LabelName        string    `description:"标签名称"`
	IsPart           int       `description:"是否为片段: 0-整段; 1-片段"`
	StartIndex       int       `description:"片段开始下标"`
	EndIndex         int       `description:"片段结束下标"`
	Content          string    `description:"内容"`
	SysAdminId       int       `description:"创建人ID"`
	SysAdminName     string    `description:"创建人姓名"`
	CreateTime       time.Time `description:"创建时间"`
}

var SaCompareLabelColumns = struct {
	SaCompareLabelId string
	CompareId        string
	DocId            string
	SectionId        string
	LabelId          string
	LabelName        string
	IsPart           string
	StartIndex       string
	EndIndex         string
	Content          string
	SysAdminId       string
	SysAdminName     string
	CreateTime       string
}{
	SaCompareLabelId: "sa_compare_label_id",
	CompareId:        "compare_id",
	DocId:            "doc_id",
	SectionId:        "section_id",
	LabelId:          "label_id",
	LabelName:        "label_name",
	IsPart:           "is_part",
	StartIndex:       "start_index",
	EndIndex:         "end_index",
	SysAdminId:       "sys_admin_id",
	SysAdminName:     "sys_admin_name",
	CreateTime:       "create_time",
}

func (m *SaCompareLabel) TableName() string {
	return "sa_compare_label"
}

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

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

func (m *SaCompareLabel) Del() (err error) {
	o := orm.NewOrm()
	sql := `DELETE FROM sa_compare_label WHERE sa_compare_label_id = ? LIMIT 1`
	_, err = o.Raw(sql, m.SaCompareLabelId).Exec()
	return
}

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

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

func (m *SaCompareLabel) 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
}

type SaCompareLabelGroupCount struct {
	DocId     int `description:"文档ID"`
	SectionId int `description:"段落ID"`
	LabelId   int `description:"标签ID"`
	UseNum    int `description:"引用数"`
}

func (m *SaCompareLabel) GetGroupCountByCondition(condition string, pars []interface{}, groupRule string) (items []*SaCompareLabelGroupCount, err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf(`SELECT COUNT(1) AS use_num, %s FROM %s WHERE 1=1 %s GROUP BY %s`, groupRule, m.TableName(), condition, groupRule)
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}

func (m *SaCompareLabel) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*SaCompareLabel, 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 *SaCompareLabel) GetPageItemsByCondition(startSize, pageSize int, condition string, pars []interface{}, fieldArr []string, orderRule string) (total int, items []*SaCompareLabel, 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
}

// UpdateSaCompareLabelByLabelId 更新比对标签信息
func UpdateSaCompareLabelByLabelId(labelId int, labelName string) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE sa_compare_label SET label_name = ? WHERE label_id = ?`
	_, err = o.Raw(sql, labelName, labelId).Exec()
	return
}

// SaCompareLabelItem 比对标签
type SaCompareLabelItem struct {
	SaCompareLabelId int    `description:"比对标签ID"`
	LabelId          int    `description:"标签ID"`
	LabelName        string `description:"标签名称"`
	CompareId        int    `description:"比对ID"`
	CompareContent   string `description:"比对内容(片段)"`
	DocId            int    `description:"文档ID"`
	Title            string `description:"文档标题"`
	SectionId        int    `description:"段落ID"`
	SectionContent   string `description:"段落内容"`
	Sort             int    `description:"段落排序"`
}

// GetSaCompareLabelByCond 获取比对标签
func GetSaCompareLabelByCond(condition string, pars []interface{}) (items []*SaCompareLabelItem, err error) {
	o := orm.NewOrm()
	sql := `SELECT
				a.sa_compare_label_id,
				a.label_id,
				a.label_name,
				a.compare_id,
				a.doc_id,
				a.content AS compare_content,
				b.title,
				c.sa_doc_section_id AS section_id,
				c.content AS section_content,
				c.sort
			FROM
				sa_compare_label AS a
			JOIN sa_doc AS b ON a.doc_id = b.sa_doc_id
			JOIN sa_doc_section AS c ON a.section_id = c.sa_doc_section_id
			WHERE
				1 = 1 %s
			ORDER BY
				a.doc_id,
				c.sort ASC`
	sql = fmt.Sprintf(sql, condition)
	_, err = o.Raw(sql, pars).QueryRows(&items)
	return
}
