package com.izouma.jiashanxia.service;

import com.izouma.jiashanxia.domain.CommissionRecord;
import com.izouma.jiashanxia.domain.User;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.enums.AuthorityName;
import com.izouma.jiashanxia.repo.CommissionRecordRepo;
import com.izouma.jiashanxia.security.Authority;
import com.izouma.jiashanxia.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Set;

@Service
@AllArgsConstructor
public class CommissionRecordService {

    private CommissionRecordRepo commissionRecordRepo;

    public Page<CommissionRecord> all(PageQuery pageQuery) {
        pageQuery.setSort("createdAt,desc");
        return commissionRecordRepo.findAll(JpaUtils.toSpecification(pageQuery, CommissionRecord.class), JpaUtils.toPageRequest(pageQuery));
    }

    /*
    后台列表
     */
    public Page<CommissionRecord> backAll(PageQuery pageQuery, User user) {
        pageQuery.setSort("createdAt,desc");
        Set<Authority> authorities = user.getAuthorities();
        if (!authorities.contains(Authority.get(AuthorityName.ROLE_ADMIN)) && authorities.contains(Authority.get(AuthorityName.ROLE_CREATOR))) {
            Map<String, Object> query = pageQuery.getQuery();
            query.put("userId", user.getId());
        }
        return commissionRecordRepo.findAll(JpaUtils.toSpecification(pageQuery, CommissionRecord.class), JpaUtils.toPageRequest(pageQuery));
    }
}
