package entity

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

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

var Base_ent_empower = base_ent_empower{}

//企业授权表
type base_ent_empower struct {
	Id            int64
	Appid         string
	Ent_id        int64  //企业id
	Ent_user_id   int64  //企业员工id
	Function_code string //功能代码
}

//授权记录
func (b *base_ent_empower) List(appid, function_code string, ent_id, page_num, page_size int64) *[]*base_ent_empower {
	q := `select * from base_ent_empower where appid=? and function_code=? and ent_id=? order by id desc`
	args := []interface{}{appid, function_code, ent_id}
	if page_num > 0 {
		q += ` limit ?,?`
		args = append(args, (page_num-1)*page_size, page_size)
	}
	list := Mysql_BaseService.SelectBySql(q, args...)
	return JsonUnmarshal(list, &[]*base_ent_empower{}).(*[]*base_ent_empower)
}

//授权记录数量
func (b *base_ent_empower) Count(appid, function_code string, ent_id int64) int64 {
	return Mysql_BaseService.CountBySql(`select count(1) as count from base_ent_empower where appid=? and function_code=? and ent_id=?`, appid, function_code, ent_id)
}

//是否授权
func (b *base_ent_empower) HasEmpower(appid, function_code string, ent_id, ent_user_id int64) bool {
	if Base_ent_wait_empower.IsAllEmpower(appid, function_code, ent_id) {
		return true
	}
	empower := b.List(appid, function_code, ent_id, 0, 0)
	if empower != nil {
		if len(*empower) == 1 && (*empower)[0].Ent_user_id == 0 {
			return true
		} else {
			for _, vv := range *empower {
				if vv.Ent_id == ent_id && vv.Ent_user_id == ent_user_id {
					return true
				}
			}
		}
	}
	return false
}

//先把有权限的人清空，再把权益授权给新的人
func (b *base_ent_empower) ReEmpower(appid string, function_code []string, ent_id int64, ent_user_id []int64) bool {
	return Mysql_BaseService.ExecTx("重新授权", func(tx *sql.Tx) bool {
		args := []interface{}{appid, ent_id}
		wh := []string{}
		for _, v := range function_code {
			wh = append(wh, "?")
			args = append(args, v)
		}
		r1 := Mysql_BaseService.UpdateOrDeleteBySqlByTx(tx, `delete from base_ent_empower where appid=? and ent_id=? and function_code in (`+strings.Join(wh, ",")+`)`, args...)
		nowFormat := NowFormat(Date_Full_Layout)
		values := []interface{}{}
		for _, v := range ent_user_id {
			for _, vv := range function_code {
				values = append(values, appid, ent_id, v, vv, nowFormat)
			}
		}
		r2, r3 := int64(-1), int64(-1)
		if len(values) > 0 {
			r2, r3 = Mysql_BaseService.InsertBatchByTx(tx, "base_ent_empower", []string{"appid", "ent_id", "ent_user_id", "function_code", "create_time"}, values)
		}
		return r1 >= 0 && r2 == int64(len(function_code)*len(ent_user_id)) && r3 > 0
	})
}

//授权
func (b *base_ent_empower) Empower(tx *sql.Tx, appid string, function_code []string, ent_id int64, ent_user_id []int64) bool {
	fields := []string{"appid", "ent_id", "ent_user_id", "function_code", "create_time"}
	nowFormat := NowFormat(Date_Full_Layout)
	values := []interface{}{}
	for _, v := range ent_user_id {
		for _, vv := range function_code {
			values = append(values, appid, ent_id, v, vv, nowFormat)
		}
	}
	r1, _ := Mysql_BaseService.InsertBatchByTx(tx, "base_ent_empower", fields, values)
	return r1 == int64(len(function_code)*len(ent_user_id))
}

//根据功能代码取消授权
func (b *base_ent_empower) CancelEmpower(tx *sql.Tx, appid string, function_code []string, ent_id int64, ent_user_id []int64) bool {
	args := []interface{}{appid, ent_id}
	wh1 := []string{}
	for _, v := range function_code {
		wh1 = append(wh1, "?")
		args = append(args, v)
	}
	wh2 := []string{}
	for _, v := range ent_user_id {
		wh2 = append(wh2, "?")
		args = append(args, v)
	}
	r1 := Mysql_BaseService.UpdateOrDeleteBySqlByTx(tx, `delete from base_ent_empower where appid=? and ent_id=? and function_code in (`+strings.Join(wh1, ",")+`) and ent_user_id in (`+strings.Join(wh2, ",")+`)`, args...)
	return r1 == int64(len(function_code)*len(ent_user_id))
}

//根据功能分类取消所有授权
func (b *base_ent_empower) CancelAllEmpower(tx *sql.Tx, appid string, function_module []string, ent_id int64, ent_user_id []int64) bool {
	args := []interface{}{appid}
	wh1 := []string{}
	for _, v := range function_module {
		wh1 = append(wh1, "?")
		args = append(args, v)
	}
	args = append(args, appid, appid, ent_id)
	wh2 := []string{}
	for _, v := range ent_user_id {
		wh2 = append(wh2, "?")
		args = append(args, v)
	}
	return Mysql_BaseService.UpdateOrDeleteBySqlByTx(tx, `delete c from base_function_module a
	inner join base_function b on (a.appid=? and a.name in (`+strings.Join(wh1, ",")+`) and a.id=b.pid and b.appid=?)
	inner join base_ent_empower c on (b.code=c.function_code and c.appid=? and c.ent_id=? and c.ent_user_id in (`+strings.Join(wh2, ",")+`))`, args...) >= 0
}

//校验功能代码
func (b *base_ent_empower) CheckEmpowerCount(tx *sql.Tx, appid string, function_code []string, ent_id int64) (int64, error) {
	m := map[string]int64{}
	for _, v := range *Base_ent_wait_empower.AllWaitEmpowers(tx, appid, ent_id) {
		if v.Empower_count < 0 {
			m[v.Function_code] = v.Empower_count
		} else {
			m[v.Function_code] = m[v.Function_code] + v.Empower_count
		}
	}
	c := map[string]int64{}
	list := Mysql_BaseService.SelectBySqlByTx(tx, `SELECT function_code,SUM(1) AS sum FROM base_ent_empower WHERE appid=? and ent_id=? GROUP BY function_code`, appid, ent_id)
	if list == nil {
		return -3, errors.New(fmt.Sprintf("企业%d查询已授权数量失败", ent_id))
	}
	for _, v := range *list {
		c[ObjToString(v["function_code"])] = Int64All(v["sum"])
	}
	for _, v := range function_code {
		if count, ok := m[v]; !ok {
			return -1, errors.New(fmt.Sprintf("企业%d没有该待授权%s功能代码", ent_id, v))
		} else if count >= 0 && c[v] > count {
			return -2, errors.New(fmt.Sprintf("企业%d功能代码%s可授权数量不足", ent_id, v))
		}
	}
	return 1, nil
}
