package com.czg.service.account.service.impl;

import com.czg.account.entity.ShopStaffPagePermission;
import com.czg.account.service.ShopStaffPagePermissionService;
import com.czg.resp.CzgResult;
import com.czg.sa.StpKit;
import com.czg.service.account.mapper.ShopStaffPagePermissionMapper;
import com.czg.service.account.mapper.ShopStaffPermissionMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.czg.account.entity.ShopPagePath;
import com.czg.account.service.ShopPagePathService;
import com.czg.service.account.mapper.ShopPagePathMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *  服务层实现。
 *
 * @author zs
 * @since 2025-04-02
 */
@Service
public class ShopPagePathServiceImpl extends ServiceImpl<ShopPagePathMapper, ShopPagePath> implements ShopPagePathService{
    @Resource
    private ShopStaffPagePermissionMapper shopStaffPagePermissionMapper;

    @Override
    public List<ShopPagePath> detail(Long staffId) {
        List<ShopStaffPagePermission> shopStaffPagePermissions = shopStaffPagePermissionMapper.selectListByQuery(new QueryWrapper().eq(ShopStaffPagePermission::getShopId,
                StpKit.USER.getShopId()).eq(ShopStaffPagePermission::getStaffId, staffId));
        if (shopStaffPagePermissions.isEmpty()) {
            list().forEach(item -> {
                ShopStaffPagePermission permission = new ShopStaffPagePermission();
                permission.setShopId(StpKit.USER.getShopId());
                permission.setStaffId(staffId);
                permission.setPagePathId(item.getId());
                permission.setIsUse(1);
                shopStaffPagePermissionMapper.insert(permission);
            });
            return list();
        }

        Set<Long> pageIdList = shopStaffPagePermissions.stream().filter(item -> item.getIsUse() == 1).map(ShopStaffPagePermission::getPagePathId).collect(Collectors.toSet());
        return pageIdList.isEmpty() ? new ArrayList<>() : list(new QueryWrapper().in(ShopPagePath::getId, pageIdList));
    }
}
