package com.izouma.nineth.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.izouma.nineth.domain.BlindBoxItem;
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.CreateBlindBox;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.dto.collection.SecondCollectionExcelDTO;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.CollectionRepo;
import com.izouma.nineth.service.AssetService;
import com.izouma.nineth.service.CollectionService;
import com.izouma.nineth.service.LikeService;
import com.izouma.nineth.utils.SecurityUtils;
import com.izouma.nineth.utils.excel.ExcelUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/collection")
@AllArgsConstructor
public class CollectionController extends BaseController {
    private CollectionService collectionService;
    private CollectionRepo collectionRepo;
    private LikeService likeService;
    private AssetService assetService;

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public Collection save(@RequestBody Collection record) {
        return collectionService.update(record);
    }
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/create")
    public Collection create(@RequestBody Collection record) {
        Collection collection = collectionService.create(record);
        //初始化藏品编号池
        collectionService.initCollectionNumberPool(collection);
        return collection;
    }

    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<CollectionDTO> all(@RequestBody PageQuery pageQuery) {
        final User user = SecurityUtils.getAuthenticatedUser();
        Page<Collection> all = collectionService.all(pageQuery);
        return collectionService.allCollection(user,all);
    }

    /**
     * 所有二手藏品
     * @param pageQuery
     * @return
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/allSecondCollection")
    public Page<CollectionDTO> allSecondCollection(@RequestBody PageQuery pageQuery) {
        Page<CollectionDTO> page = collectionService.allSecondCollection(pageQuery);
        return page;
    }


    /**
     * 批量下架藏品
     * @param reqData
     * @return
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("batchCancelConsignment")
    public JSONObject batchCancelConsignment(@RequestBody JSONObject reqData){
        JSONObject result = new JSONObject();
        JSONArray dataList = reqData.getJSONArray("dataList");
        AtomicInteger count = new AtomicInteger();
        for(int i =0; i < dataList.size(); i++){
            JSONObject itemObj = dataList.getJSONObject(i);
            Long assetId = itemObj.getLong("assetId");
            Long userId = itemObj.getLong("userId");
            assetService.cancelConsignment(userId, assetId);
            count.addAndGet(1);
        }

        result.put("count", count);

        return result;
    }


    @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);
    }
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
//        collectionRepo.softDelete(id);
        throw new BusinessException("藏品不可删除");
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, @RequestBody PageQuery pageQuery) throws IOException {
        List<Collection> data = collectionService.all(pageQuery).getContent();
        ExcelUtils.export(response, data);
    }


    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/excelSecond")
    @ResponseBody
    public void excelSecond(HttpServletResponse response, @RequestBody PageQuery pageQuery) throws IOException {
        List<CollectionDTO> data = collectionService.allSecondCollection(pageQuery).getContent();
        //构建导出视图
        List<SecondCollectionExcelDTO> viewList = new ArrayList<>();
        data.forEach( item ->{
            viewList.add(new SecondCollectionExcelDTO(item));
        });

        ExcelUtils.export(response, viewList);
    }



    @GetMapping("/{id}/like")
    @ApiOperation("点赞")
    public void like(@PathVariable Long id) {
        likeService.like(SecurityUtils.getAuthenticatedUser().getId(), id);
    }

    @GetMapping("/{id}/unlike")
    @ApiOperation("取消点赞")
    public void unlike(@PathVariable Long id) {
        likeService.unlike(SecurityUtils.getAuthenticatedUser().getId(), id);
    }

    @GetMapping("/myLikes")
    @ApiOperation("我收藏的")
    public List<CollectionDTO> myLikes() {
        return collectionService.toDTO(collectionRepo.userLikes(SecurityUtils.getAuthenticatedUser().getId()));
    }
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/createBlindBox")
    public Collection createBlindBox(@RequestBody CreateBlindBox createBlindBox) {
        Collection blindBoxCollection = collectionService.createBlindBox(createBlindBox);
        //子藏品建立成功时，需要减少缓存库存
        for (BlindBoxItem item : createBlindBox.getItems()) {
            collectionService.increaseStockCache(item.getCollectionId(), -item.getTotal());
        }
        return blindBoxCollection;
    }

    @PostMapping("/appointment")
    public void appointment(@RequestParam Long id) {
        collectionService.appointment(id, SecurityUtils.getAuthenticatedUser().getId());
    }

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


    /**
     * 手动初始化藏品编号池
     *
     * @param collectionId
     * @return
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/initCollectionNumberPool")
    public Map<String, Object> initCollectionNumberPool(@RequestParam Long collectionId) {

        Collection collection = collectionRepo.findById(collectionId).orElseThrow(new BusinessException("藏品未找到"));
        //初始化藏品编号池
        collectionService.initCollectionNumberPool(collection);

        Map<String, Object> res = new HashMap<>();
        res.put("collectionId", collection.getId());
        res.put("name", collection.getName());
        res.put("stock", collection.getStock());
        return res;
    }

}

