package com.czg.controller.admin;

import com.czg.account.dto.pagepath.PagePathPermissionAddDTO;
import com.czg.account.entity.ShopPagePath;
import com.czg.account.entity.ShopStaffPagePermission;
import com.czg.account.service.ShopPagePathService;
import com.czg.account.service.ShopStaffPagePermissionService;
import com.czg.resp.CzgResult;
import com.czg.sa.StpKit;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 收银机页面权限相关
 * @author Administrator
 */
@RestController
@RequestMapping("/admin/shopPagePermission")
public class ShopPagePermissionController {
    @Resource
    private ShopPagePathService shopPagePathService;
    @Resource
    private ShopStaffPagePermissionService shopStaffPagePermissionService;

    /**
     * 获取所有页面路径
     * @return 页面路径
     */
    @GetMapping
    public CzgResult<List<ShopPagePath>> page() {
        return CzgResult.success(shopPagePathService.list());
    }

    /**
     * 保存修改权限
     * @return 是否成功
     */
    @PostMapping
    public CzgResult<Boolean> add(@RequestBody @Validated PagePathPermissionAddDTO pagePathPermissionAddDTO) {
        if (StpKit.USER.isStaff()) {
            return CzgResult.failure("员工无权限");
        }
        return CzgResult.success(shopStaffPagePermissionService.add(StpKit.USER.getShopId(), pagePathPermissionAddDTO));
    }

    /**
     * 获取员工拥有页面路径
     * @param staffId 员工ID
     */
    @GetMapping("/detail")
    public CzgResult<List<ShopPagePath>> detail(@RequestParam Long staffId) {
        if (StpKit.USER.isStaff() && StpKit.USER.getLoginIdAsLong() != staffId) {
            return CzgResult.failure("员工无权限");
        }
        return CzgResult.success(shopPagePathService.detail(staffId));
    }

    /**
     * 获取当前员工已拥有页面路径权限
     */
    @GetMapping("/mine")
    public CzgResult<List<ShopPagePath>> mine() {
        Set<Long> pageIdList = shopStaffPagePermissionService.list(new QueryWrapper().eq(ShopStaffPagePermission::getShopId, StpKit.USER.getShopId()).eq(ShopStaffPagePermission::getIsUse, 1)
                .eq(ShopStaffPagePermission::getStaffId, StpKit.USER.getLoginIdAsLong())).stream().map(ShopStaffPagePermission::getPagePathId).collect(Collectors.toSet());
        if (pageIdList.isEmpty()) {
            return CzgResult.success(new ArrayList<>());
        }
        return CzgResult.success(shopPagePathService.list(new QueryWrapper().in(ShopPagePath::getId, pageIdList)));
    }
}
