package purchase

import (
	"errors"
	"hongze/hongze_yb/models/response/purchase"
	activity2 "hongze/hongze_yb/services/activity"
	"hongze/hongze_yb/services/company"
	"hongze/hongze_yb/services/report"
	"hongze/hongze_yb/services/user"
	"sort"
	"sync"
)

func GetLatestReportAndActivity(user user.UserInfo) (list purchase.PurchaseList, err error)  {
	permissionIds, err := company.GetPurchasePermissionIdsByCompany2ProductId(user.CompanyID, 1)
	if err != nil {
		return
	}
	if len(permissionIds) == 0 {
		err = errors.New("用户无权限")
		return
	}

	w := sync.WaitGroup{}
	//查找最新的报告
	w.Add(1)
	go func() {
		defer w.Done()
		list, err = report.GetLatestClassReport(permissionIds, user.UserID)
	}()
	//查找最新的活动
	w.Add(1)
	var purItem *purchase.PurchaseListItem
	var err2 error
	go func() {
		defer w.Done()
		purItem, err2 = activity2.GetLatestActivity(permissionIds, user.UserID)
	}()
	w.Wait()

	if err != nil {
		return
	}
	if err2 != nil {
		err = err2
		return
	}

	list = append(list, purItem)

	if len(list) > 0 {
		sort.Sort(list)
	}
	return
}

// GetDetail 已购详情页面
func GetDetail(user user.UserInfo, classifyIdFirst int, activityId, pageIndex, pageSize int) (ret *purchase.DetailResp, err error)  {
	permissionIds, err := company.GetPurchasePermissionIdsByCompany2ProductId(user.CompanyID, 1)
	if err != nil {
		return
	}
	if len(permissionIds) <= 0 {
		err = errors.New("用户无权限")
		return
	}

	if classifyIdFirst != 0 {
		ret, err = report.GetPurchaseDetail(permissionIds, user.UserID, classifyIdFirst, pageIndex, pageSize)
	}else if activityId > 0 {
		ret, err = activity2.GetPurchaseDetail(permissionIds, user.UserID, pageIndex, pageSize)
	}
	return
}

