package com.izouma.nineth.web.mobile.open.v1;


import com.izouma.nineth.domain.Collection;
import com.izouma.nineth.domain.FileObject;
import com.izouma.nineth.domain.User;
import com.izouma.nineth.dto.CollectionDTO;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.enums.BuyCollectionStatus;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.CollectionRepo;
import com.izouma.nineth.service.CollectionService;
import com.izouma.nineth.utils.SecurityUtils;
import com.izouma.nineth.web.BaseController;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/collection/v1")
@AllArgsConstructor
public class CollectionControllerOpenV1{
    private CollectionService collectionService;
    private CollectionRepo collectionRepo;


    @PostMapping("/all")
    public Page<CollectionDTO> all(@RequestBody PageQuery pageQuery) {
        Map<String, Object> query = pageQuery.getQuery();
        String buyCollectionStatus = (String) query.get("buyCollectionStatus");
        if (StringUtils.hasText(buyCollectionStatus) && BuyCollectionStatus.BUY.name().equals(buyCollectionStatus)){
            query.put("soldOut", 0);
            query.remove("buyCollectionStatus");
        }else {
            query.remove("soldOut");
        }
        final User user = SecurityUtils.getAuthenticatedUser();
        Page<Collection> all = collectionService.all(pageQuery);
        return collectionService.allCollection(user,all);
    }


    @GetMapping("/get/{id}")
    public CollectionDTO get(@PathVariable String id) {
        if (!NumberUtils.isDigits(id)) {
            throw new BusinessException("请求信息错误 -" + id);
        }
        final User user = SecurityUtils.getAuthenticatedUser();
        return collectionService.getById(id,user);
    }


    @GetMapping("/recommend")
    public List<CollectionDTO> recommend(@RequestParam String type, @RequestParam(defaultValue = "0") int projectId) {
        List<CollectionDTO> collectionDTOS = collectionService.toDTO(collectionRepo.recommend(type, projectId).stream().map(rc -> {
            if (StringUtils.hasText(rc.getRecommend().getPic())) {
                rc.getCollection().setPic(Collections.singletonList(new FileObject(null, rc.getRecommend()
                        .getPic(), null, null)));
            }
            return rc.getCollection();
        }).collect(Collectors.toList()));
        collectionDTOS.forEach(item -> item.setBuyCollectionStatus(collectionService.checkBuyStatus(item)));
        return collectionDTOS;
    }



}

