package entity

import (
	"database/sql"
	"errors"
	"fmt"

	. "app.yhyue.com/moapp/jybase/common"
	. "app.yhyue.com/moapp/jybase/date"
	. "bp.jydev.jianyu360.cn/BaseService/resourceCenter/public/db"
)

var Base_ent_wait_empower = base_ent_wait_empower{}

//企业授权表
type base_ent_wait_empower struct {
	Id                  int64
	Appid               string
	Goods_spec_power_id int64  //商品规格权益id
	Function_code       string //功能代码
	Ent_id              int64  //企业id
	Start_time          string //开始时间
	End_time            string //结束时间
	Empower_count       int64  //授权数量
	Limit_strategy      string //限制频率；1d：1天 1m：1个月
}

//根据商品规格获取待授权记录
func (b *base_ent_wait_empower) WaitEmpowersBySpecId(appid string, spec_id, ent_id int64) *[]*base_ent_wait_empower {
	list := Mysql_BaseService.SelectBySql(`SELECT c.* FROM base_goods_spec a
	INNER JOIN base_goods_spec_power b ON (a.id=? AND a.appid=? AND a.id=b.spec_id)
	INNER JOIN base_ent_wait_empower c ON (c.ent_id=? AND c.end_time>? AND b.id=c.goods_spec_power_id)`, spec_id, appid, ent_id, NowFormat(Date_Full_Layout))
	return JsonUnmarshal(list, &[]*base_ent_wait_empower{}).(*[]*base_ent_wait_empower)
}

//根据功能代码获取待授权记录
func (b *base_ent_wait_empower) WaitEmpowers(appid, function_code string, ent_id int64) *[]*base_ent_wait_empower {
	list := Mysql_BaseService.SelectBySql(`select * from base_ent_wait_empower where appid=? and function_code=? and ent_id=? and end_time>?`, appid, function_code, ent_id, NowFormat(Date_Full_Layout))
	return JsonUnmarshal(list, &[]*base_ent_wait_empower{}).(*[]*base_ent_wait_empower)
}

//所有待授权记录
func (b *base_ent_wait_empower) AllWaitEmpowers(tx *sql.Tx, appid string, ent_id int64) *[]*base_ent_wait_empower {
	list := Mysql_BaseService.SelectBySqlByTx(tx, `select * from base_ent_wait_empower where appid=? and ent_id=? and end_time>?`, appid, ent_id, NowFormat(Date_Full_Layout))
	return JsonUnmarshal(list, &[]*base_ent_wait_empower{}).(*[]*base_ent_wait_empower)
}

//校验功能代码
func (b *base_ent_wait_empower) CheckFunctionCode(appid string, function_code []string, ent_id int64) (int64, error) {
	m := map[string]bool{}
	for _, v := range *b.AllWaitEmpowers(nil, appid, ent_id) {
		m[v.Function_code] = true
	}
	for _, v := range function_code {
		if !m[v] {
			return -1, errors.New(fmt.Sprintf("企业%d没有该待授权%s功能代码", ent_id, v))
		}
	}
	return 1, nil
}

//是否全部授权
func (b *base_ent_wait_empower) IsAllEmpower(appid, function_code string, ent_id int64) bool {
	return Mysql_BaseService.CountBySql(`select count(1) as count from base_ent_wait_empower where appid=? and function_code=? and ent_id=? and end_time>? and empower_count<0`, appid, function_code, ent_id, NowFormat(Date_Full_Layout)) > 0
}
