package services

import (
	"fmt"
	"hongze/hongze_task/models"
	"hongze/hongze_task/utils"
	"time"
)


//产品试用权限  ->  产品权限关闭
func CompanyReportPermissionClose() (err error) {
	//fmt.Println("开始进入产品试用权限  ->  产品权限关闭")
	endDate := time.Now().AddDate(0,0,-1).Format(utils.FormatDate)
	items, err := models.GetCompanyReportPermissionNeedClose(endDate)

	if err != nil {
		utils.FileLog.Info("GetCompanyReportPermissionNeedClose Err:%s" + err.Error())
		return
	}

	//待处理的用户产品权限列表（主要目的是为了多个产品项的去重，避免冻结产品时的多余sql操作）
	freezeCompanyProductList := make(map[string]*models.CompanyReportPermission)

	for _, v := range items {
		//fmt.Println(k, v)
		//continue
		//查看是否有审批单，如果有审批单，那么就退出当前循环，进入下一循环
		count, err := models.GetCompanyApprovalCount(v.CompanyId,v.ProductId)
		if err != nil {
			continue
		}
		if count > 0 {
			continue
		}

		//关闭用户产品权限
		err = models.CompanyReportPermissionClose(v.CompanyReportPermissionId,v.CompanyId, v.ProductId)
		if err != nil {
			utils.FileLog.Info("CompanyReportPermissionClose Err:%s" + err.Error())
			continue
		}
		//添加关闭用户产品权限日志
		_ = AddCompanyReportPermissionLog(v.CompanyReportPermissionId,v.CompanyId,v.ProductId,utils.AdminId,v.ProductName,utils.RealName,"试用转关闭","close",v.Status)

		//如果不存在该数据，那么将该数据放入待处理用户产品权限列表
		mapKey := fmt.Sprintf("%v_%v",v.CompanyId,v.ProductId)
		if _,ok := freezeCompanyProductList[mapKey];ok==false{
			freezeCompanyProductList[mapKey] = v
		}

	}

	//遍历待处理的用户产品权限列表，查询用户产品权限信息并冻结用户产品
	for _,companyReportPermission := range freezeCompanyProductList{
		go queryAndFreezeCompanyProduct(companyReportPermission)
	}
	return
}

//查询用户产品权限信息并冻结用户产品
func queryAndFreezeCompanyProduct(companyReportPermission *models.CompanyReportPermission){
	//查询该用户名下是否存在还在使用的权限
	count,err := models.GetCompanyReportPermissionCount(companyReportPermission.CompanyId, companyReportPermission.ProductId)
	if err != nil {
		utils.FileLog.Info("CompanyReportPermissionClose query other permission Err:%s" + err.Error())
	}
	//如果还存在使用（不管是正式还是试用）的权限，那么都直接退出当前循环，不冻结用户产品
	if count > 0 {
		return
	}

	//冻结该用户产品
	err = models.CompanyFreeze(companyReportPermission.CompanyId, companyReportPermission.ProductId)
	if err != nil {
		go utils.SendEmail(utils.APPNAME+"失败提醒"+utils.RunMode+";冻结该用户产品", "services:queryAndFreezeCompanyProduct;Err"+err.Error(), utils.EmailSendToUsers)
		return
	}

	//查询用户产品信息
	companyProduct ,err := models.GetCompanyProduct(companyReportPermission.CompanyId,companyReportPermission.ProductId)
	//if err!=nil && err.Error() != utils.ErrNoRow() {
	if err != nil {
		go utils.SendEmail(utils.APPNAME+"失败提醒"+utils.RunMode+";查询用户产品信息", "services:queryAndFreezeCompanyProduct;Err"+err.Error(), utils.EmailSendToUsers)
		return
	}
	//添加操作日志
	remark := "试用转冻结"
	operation := "freeze"
	approveContent := "冻结"
	err = AddCompanyOperationRecord(companyReportPermission.CompanyId, utils.AdminId, companyReportPermission.ProductId, utils.AdminId, companyProduct.CompanyName,
		companyProduct.ProductName, utils.RealName, remark, operation, approveContent, utils.RealName, "", companyProduct.Status)
	if err != nil {
		go utils.SendEmail(utils.APPNAME+"失败提醒"+utils.RunMode+";添加冻结操作日志", "services:queryAndFreezeCompanyProduct;Err"+err.Error(), utils.EmailSendToUsers)
		return
	}
	return
}

//添加用户权限操作日志
func AddCompanyReportPermissionLog(companyReportPermissionId int64,companyId,productId,sysUserId int,productName string,sysUserName,remark,operation,status string) (err error) {
	record := models.CompanyReportPermissionLog{
		CompanyReportPermissionId : companyReportPermissionId,
		CompanyId : companyId,
		ProductId : productId,
		ProductName : productName,
		SysUserId : sysUserId,
		SysUserName : sysUserName,
		Remark : remark,
		Operation : operation,
		Status : status,
		CreateTime : time.Now(),
	}
	_, err = models.AddCompanyReportPermissionLog(&record)
	if err != nil{
		go utils.SendEmail(utils.APPNAME+"失败提醒"+utils.RunMode, "services:AddCompanyReportPermissionLog;Err"+err.Error(), utils.EmailSendToUsers)
	}
	return
}