package models

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

// MaycurCompanyProfile 每刻报销-客户档案表
type MaycurCompanyProfile struct {
	MaycurCompanyProfileId int       `orm:"column(maycur_company_profile_id);pk"`
	BizCode                string    `description:"选项编码"`
	Name                   string    `description:"公司名称"`
	NameDisplay            string    `description:"公司名称-JSON"`
	Enabled                int       `description:"状态：0-禁用; 1-启用"`
	ParentCode             string    `description:"父级选项编码"`
	Authzs                 string    `description:"客户可见性-JSON"`
	CreateTime             time.Time `description:"创建时间"`
	ModifyTime             time.Time `description:"更新时间"`
}

func (m *MaycurCompanyProfile) TableName() string {
	return "maycur_company_profile"
}

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

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

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

func (m *MaycurCompanyProfile) Del() (err error) {
	o := orm.NewOrm()
	sql := `DELETE FROM maycur_company_profile WHERE maycur_company_profile_id = ? LIMIT 1`
	_, err = o.Raw(sql, m.MaycurCompanyProfileId).Exec()
	return
}

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

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

func (m *MaycurCompanyProfile) 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 *MaycurCompanyProfile) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*MaycurCompanyProfile, 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 *MaycurCompanyProfile) Clear() (err error) {
	o := orm.NewOrm()
	sql := `TRUNCATE TABLE maycur_company_profile`
	_, err = o.Raw(sql).Exec()
	return
}

// MultiCreateAndUpdate 批量新增及更新
func (m *MaycurCompanyProfile) MultiCreateAndUpdate(newProfiles, updateProfiles []*MaycurCompanyProfile, updateCols []string) (err error) {
	o := orm.NewOrm()
	tx, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = tx.Rollback()
		} else {
			_ = tx.Commit()
		}
	}()

	if len(newProfiles) > 0 {
		_, err = tx.InsertMulti(len(newProfiles), newProfiles)
		if err != nil {
			return
		}
	}
	if len(updateProfiles) > 0 {
		for _, p := range updateProfiles {
			_, err = o.Update(p, updateCols...)
			if err != nil {
				return
			}
		}
	}
	return
}

// MaycurSyncCompanyListWithSeller 需要同步的中英文客户及销售
type MaycurSyncCompanyListWithSeller struct {
	CompanyId     int    `description:"客户ID"`
	CompanyName   string `description:"客户姓名"`
	SellerIds     string `description:"销售IDs"`
	IsShare       int    `description:"是否为共享客户"`
	ShareSellerId int    `description:"共享销售ID"`
}

// GetMaycurSyncCompanyListWithSeller 获取需要同步的中英文客户及销售
func GetMaycurSyncCompanyListWithSeller() (items []*MaycurSyncCompanyListWithSeller, err error) {
	o := orm.NewOrm()
	sql := `SELECT
				a.company_id,
				a.company_name,
				GROUP_CONCAT(DISTINCT b.seller_id) AS seller_ids
			FROM
				company AS a
			JOIN company_product AS b ON a.company_id = b.company_id
			JOIN admin AS c ON b.seller_id = c.admin_id AND c.enabled = 1
			WHERE
				b.status IN ("试用", "正式", "永续", "冻结")
			GROUP BY
				a.company_id`
	_, err = o.Raw(sql).QueryRows(&items)
	return
}
