package ppt

import (
	"errors"
	"eta/eta_api/models"
	"strconv"
	"strings"
	"time"
)

// GrantPpt 授权ppt
func GrantPpt(pptId, grantType int, grantAdminIdStr string, sysUserId int) (err error, errMsg string) {
	list := make([]*models.PptV2Grant, 0)

	switch grantType {
	case 1:
		departmentId := 1 //ficc研究员部门
		tmpV := &models.PptV2Grant{
			//GrantId:      0,
			PptId:        int64(pptId),
			DepartmentId: int64(departmentId),
			GrantAdminId: 0,
			CreateTime:   time.Now(),
		}
		list = append(list, tmpV)

	case 2:
		if grantAdminIdStr == `` {
			errMsg = `请选择用户`
			return
		}
		grantAdminIdStrList := strings.Split(grantAdminIdStr, ",")
		lenGrantAdminIdStrList := len(grantAdminIdStrList) //指定用户的人数
		for _, v := range grantAdminIdStrList {
			grantAdminId, tmpErr := strconv.Atoi(v)
			if tmpErr != nil {
				errMsg = `数据异常`
				err = errors.New("用户转int失败," + tmpErr.Error())
				return
			}
			//如果只选择了自己作为指定的人，那么就提示他报错。如果多人，那么就过滤自己
			if grantAdminId == sysUserId {
				if lenGrantAdminIdStrList == 1 {
					errMsg = `不允许选择本人作为共享用户`
					return
				}
				continue
			}
			tmpV := &models.PptV2Grant{
				//GrantId:      0,
				PptId: int64(pptId),
				//DepartmentId: int64(departmentId),
				GrantAdminId: int64(grantAdminId),
				CreateTime:   time.Now(),
			}
			list = append(list, tmpV)
		}
	}
	if len(list) <= 0 {
		errMsg = `请选择用户`
		return
	}

	err = models.MultiAddPptV2Grant(pptId, list)
	if err != nil {
		errMsg = "设置失败"
	}
	return
}

// DeleteGrantPpt 移除授权ppt
func DeleteGrantPpt(pptId int) (err error, errMsg string) {
	err = models.DeletePptV2Grant(pptId)
	if err != nil {
		errMsg = "取消失败"
	}

	return
}
