package com.ruoyi.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.enums.user.UserEnums;
import com.ruoyi.frequency.banner.entity.Banner;
import com.ruoyi.frequency.banner.service.BannerService;
import com.ruoyi.frequency.customer.service.UserService;
import com.ruoyi.response.ResponseData;
import com.ruoyi.vo.BodyIdReq;
import com.ruoyi.vo.RyController;
import com.ruoyi.vo.UserInfo;
import com.ruoyi.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 轮播图
 */
@CrossOrigin
@RestController
@RequestMapping("/api/banner")
@Api(tags = "轮播图")
public class ApiBannerController extends RyController {


    @Autowired
    private BannerService bannerService;

    @Autowired
    private UserService userService;

    @PostMapping("/bannerList")
    @ApiOperation(value = "轮播图", notes = "轮播图")
    public ResponseData<List<Banner>> bannerList(@RequestBody(required = false) Integer position) {

        List<Banner> banners = bannerService.list(new QueryWrapper<Banner>().lambda()
                .eq(Banner::getDelFlag, PublicCommon.启用)
                .eq(ObjectUtil.isNotEmpty(position), Banner::getPosition, position)
                .orderByAsc(Banner::getSort)
        );

        if (!banners.isEmpty()){
            Set<UserVo> userVoSet = banners.stream().filter(s->s.getType() == 4 || s.getType() == 5)
                    .map(s -> new UserVo(s.getType() == 4? UserEnums.customer.getCode():UserEnums.store.getCode(), Long.valueOf(s.getContent())))
                    .collect(Collectors.toSet());
            //查询用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet,null);

            banners.stream().forEach(s ->{
                if (s.getType() == 4 || s.getType() == 5) {
                    s.setUserInfo(userMap.get(new UserVo(s.getType() == 4 ? UserEnums.customer.getCode() : UserEnums.store.getCode(), Long.valueOf(s.getContent()))));
                }
            });
        }

        return ResponseData.success(banners);
    }

    @PostMapping("/detail")
    @ApiOperation(value = "轮播图详情", notes = "轮播图详情")
    public ResponseData<Banner> detail(@Valid @NotNull(message = "id不能为空") @RequestBody BodyIdReq req) {
        return ResponseData.success(this.bannerService.getById(req.getId()));
    }

}
