package models

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

type EnCompanyPermission struct {
	EnCompanyPermissionId int       `orm:"column(en_company_permission_id);pk" description:"英文品种权限ID"`
	EnCompanyId           int       `description:"英文客户ID"`
	EnPermissionId        int       `description:"英文品种ID"`
	CreateTime            time.Time `description:"创建时间"`
}

var EnCompanyPermissionColumns = struct {
	EnCompanyPermissionId string
	EnCompanyId           string
	EnPermissionId        string
	CreateTime            string
}{
	EnCompanyPermissionId: "en_company_permission_id",
	EnCompanyId:           "en_company_id",
	EnPermissionId:        "en_permission_id",
	CreateTime:            "create_time",
}

func (m *EnCompanyPermission) TableName() string {
	return "en_company_permission"
}

func (m *EnCompanyPermission) Create() (err error) {
	o := orm.NewOrmUsingDB("rddp")
	id, err := o.Insert(m)
	if err != nil {
		return
	}
	m.EnCompanyPermissionId = int(id)
	return
}

func (m *EnCompanyPermission) Update(cols []string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	_, err = o.Update(m, cols...)
	return
}

func (m *EnCompanyPermission) Del() (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := fmt.Sprintf(`DELETE FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), EnCompanyPermissionColumns.EnCompanyPermissionId)
	_, err = o.Raw(sql, m.EnCompanyPermissionId).Exec()
	return
}

func (m *EnCompanyPermission) GetItemById(id int) (item *EnCompanyPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE %s = ? LIMIT 1`, m.TableName(), EnCompanyPermissionColumns.EnCompanyPermissionId)
	err = o.Raw(sql, id).QueryRow(&item)
	return
}

func (m *EnCompanyPermission) GetItemByCondition(condition string, pars []interface{}) (item *EnCompanyPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := fmt.Sprintf(`SELECT * FROM %s WHERE 1=1 `, m.TableName())
	sql += condition
	sql += ` LIMIT 1`
	err = o.Raw(sql, pars).QueryRow(&item)
	return
}

func (m *EnCompanyPermission) GetCountByCondition(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	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 *EnCompanyPermission) GetItemsByCondition(condition string, pars []interface{}, fieldArr []string, orderRule string) (items []*EnCompanyPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	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 *EnCompanyPermission) GetPageItemsByCondition(startSize, pageSize int, condition string, pars []interface{}, fieldArr []string, orderRule string) (total int, items []*EnCompanyPermission, err error) {
	o := orm.NewOrmUsingDB("rddp")
	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
}

func ClearAndCreateEnCompanyPermissions(companyId int, permissions []*EnCompanyPermission) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `DELETE FROM en_company_permission WHERE en_company_id = ?`
	if _, e := o.Raw(sql, companyId).Exec(); e != nil {
		err = fmt.Errorf("delete err: %s", e.Error())
		return
	}
	if len(permissions) > 0 {
		if _, e := o.InsertMulti(len(permissions), permissions); e != nil {
			err = fmt.Errorf("insert multi err: %s", e.Error())
			return
		}
	}
	return
}

// GetEnglishCompanyIdsByEnPermissionIds 根据权限IDs获取报告IDs
func GetEnglishCompanyIdsByEnPermissionIds(permissionIds []int) (companyIds []int, err error) {
	if len(permissionIds) == 0 {
		return
	}
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT DISTINCT a.en_company_id FROM en_company_permission AS a
			JOIN english_company AS b ON a.en_company_id = b.company_id
			WHERE
				a.en_permission_id IN (` + utils.GetOrmInReplace(len(permissionIds)) + `) AND b.status <> 3 AND b.enabled = 1 AND b.is_deleted = 0`
	_, err = o.Raw(sql, permissionIds).QueryRows(&companyIds)
	return
}
