package enterprise

import (
	"git.rosy.net.cn/baseapi/platformapi/enterprise_wechat"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/business/model/legacymodel"
	"git.rosy.net.cn/jx-callback/globals"
	"strconv"
)

var EnterpriseSuite = new(enterprise_wechat.SuiteTicketInfo)

// 初始化加载全局变量
func Init() {
	var config []*legacymodel.Config
	sql := `SELECT * FROM config WHERE thirdparty = ? `
	if err := dao.GetRows(dao.GetDB(), &config, sql, []interface{}{"enterprise"}...); err != nil {
		globals.SugarLogger.Debug("enterprice init config err = ", err)
	}
	if len(config) >= model.YES {
		EnterpriseSuite.SuiteId = config[0].RefreshToken
		EnterpriseSuite.SuiteTicket = config[0].Token
		EnterpriseSuite.InfoType = ""
		time, _ := strconv.ParseInt(config[0].Date, 10, 64)
		EnterpriseSuite.TimeStamp = time
	}
}

func UpdateEnterpriseSuite(data *enterprise_wechat.SuiteTicketInfo) error {
	if data.SuiteTicket != "" && data.TimeStamp > 0 {
		EnterpriseSuite = data
	}
	// 修改数据库
	db := dao.GetDB()
	config := &legacymodel.Config{
		Thirdparty:   "enterprise",
		Token:        data.SuiteTicket,
		Date:         string(data.TimeStamp),
		LastOperator: model.AdminName,
		RefreshToken: data.SuiteId,
	}
	return dao.CreateOrUpdate(db, config)
}
