package services

import (
	"encoding/json"
	"eta/eta_api/models"
	excel3 "eta/eta_api/models/data_manage/excel"
	"eta/eta_api/models/system"
	"eta/eta_api/services/data/data_manage_permission"
	"eta/eta_api/utils"
	"fmt"
	"time"
)

// UpdateExcelEditMark 更新表格当前更新状态
// status 枚举值 1:编辑中,0:完成编辑, 2:只做查询
func UpdateExcelEditMark(excelInfoId, nowUserId, status int, nowUserName string) (ret models.MarkReportResp, err error) {
	//更新标记key
	key := fmt.Sprint(`crm:excel:edit:`, excelInfoId)
	opUserId, e := utils.Rc.RedisInt(key)
	var opUser models.MarkReportItem
	if e != nil {
		opUserInfoStr, tErr := utils.Rc.RedisString(key)
		if tErr == nil {
			tErr = json.Unmarshal([]byte(opUserInfoStr), &opUser)
			if tErr == nil {
				opUserId = opUser.AdminId
			}
		}
	}
	if opUserId > 0 && opUserId != nowUserId {
		editor := opUser.Editor
		if editor == "" {
			//查询账号的用户姓名
			otherInfo, e := system.GetSysAdminById(opUserId)
			if e != nil {
				err = fmt.Errorf("查询其他编辑者信息失败")
				return
			}
			editor = otherInfo.RealName
		}

		ret.Status = 1
		ret.Msg = fmt.Sprintf("当前%s正在编辑中", editor)
		ret.Editor = editor
		return
	}
	if status == 1 {
		nowUser := &models.MarkReportItem{AdminId: nowUserId, Editor: nowUserName}
		bt, e := json.Marshal(nowUser)
		if e != nil {
			err = fmt.Errorf("格式化编辑者信息失败")
			return
		}
		if opUserId > 0 {
			utils.Rc.Do("SETEX", key, int64(300), string(bt)) //3分钟缓存
		} else {
			utils.Rc.SetNX(key, string(bt), time.Second*60*3) //3分钟缓存
		}
	} else if status == 0 {
		//清除编辑缓存
		_ = utils.Rc.Delete(key)
	}
	return
}

// GetBalanceExcelIdsByAdminId 获取用户有权限的平衡表excelIds
func GetBalanceExcelIdsByAdminId(adminId int, condition string, pars []interface{}, permissionEdbIdList, permissionClassifyIdList []int) (authIds []int, err error) {
	//找到当前协作人相关的表格ID
	obj := new(excel3.ExcelWorker)
	existList, err := obj.GetBySysUserId(adminId)
	if err != nil {
		//br.Msg = "获取表格协作人失败!"
		//br.ErrMsg = "获取表格协作人失败,Err:" + err.Error()
		return
	}
	var excelIds []int
	newCondition := condition
	newPars := pars
	if len(existList) > 0 {
		for _, v := range existList {
			excelIds = append(excelIds, v.ExcelInfoId)
		}
		newCondition += fmt.Sprintf(` AND  ( excel_info_id IN (%s)  or sys_user_id = ?)`, utils.GetOrmInReplace(len(excelIds)))
		newPars = append(newPars, excelIds, adminId)
	} else {
		newCondition += ` AND  sys_user_id = ? `
		newPars = append(newPars, adminId)
	}

	//获取表格信息
	tmpList, e := excel3.GetNoContentExcelListByConditionNoPage(newCondition, newPars)
	if e != nil && !utils.IsErrNoRow(e) {
		//br.Success = true
		//br.Msg = "获取表格信息失败"
		//br.ErrMsg = "获取表格信息失败,Err:" + e.Error()
		return
	}
	classifyIdListTmp := make([]int, 0)
	for _, v := range tmpList {
		classifyIdListTmp = append(classifyIdListTmp, v.ExcelClassifyId)
	}
	classifyMap := make(map[int]*excel3.ExcelClassify)

	// 分类信息
	if len(classifyIdListTmp) > 0 {
		classifyListTmp, e := excel3.GetClassifyByIdList(classifyIdListTmp)
		if e != nil {
			//br.Msg = "获取表格分类信息失败"
			//br.ErrMsg = "获取表格分类列表数据失败,Err:" + e.Error()
			return
		}
		for _, v := range classifyListTmp {
			classifyMap[v.ExcelClassifyId] = v
		}
	}
	excelIds = make([]int, 0)
	for _, v := range tmpList {
		// 数据权限
		if classifyInfo, ok := classifyMap[v.ExcelClassifyId]; ok {
			v.HaveOperaAuth = data_manage_permission.CheckExcelPermissionByPermissionIdList(v.IsJoinPermission, classifyInfo.IsJoinPermission, v.ExcelInfoId, v.ExcelClassifyId, permissionEdbIdList, permissionClassifyIdList)
			if v.HaveOperaAuth {
				excelIds = append(excelIds, v.ExcelInfoId)
			}
		}
	}
	authIds = excelIds
	return
}

// GetTradeAnalysisTableOpButton 获取持仓分析表格的操作权限
func GetTradeAnalysisTableOpButton(belongUserId, sysUserId int, roleTypeCode string, haveOperaAuth bool) (button excel3.ExcelInfoDetailButton) {
	// 这部分没有加到数据权限里,这里先注释掉
	//if !haveOperaAuth {
	//	return
	//}
	// 非管理员角色查看其他用户创建的表格,可刷新、另存为、下载表格;
	button.RefreshButton = true
	button.CopyButton = true
	button.DownloadButton = true

	// 创建人、管理员有权限编辑和删除
	if belongUserId == sysUserId || roleTypeCode == utils.ROLE_TYPE_CODE_ADMIN || roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
		button.OpButton = true
		button.DeleteButton = true
	}
	return
}