package com.ruoyi.web.controller.api;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.ApiResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mall.domain.MallGoodsClass;
import com.ruoyi.mall.domain.MallGoodsGoods;
import com.ruoyi.mall.domain.MallGoodsProduct;
import com.ruoyi.mall.domain.MallImg;
import com.ruoyi.mall.domain.vo.GoodsProductVO;
import com.ruoyi.mall.domain.vo.IndexGoodsVO;
import com.ruoyi.mall.domain.vo.MallGoodsClassVO;
import com.ruoyi.mall.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName ApiGoodsController
 * @Description 请描述类的业务用途
 * @Author linlinee
 * @Date 2021/11/29 10:17 AM
 * @Version 1.0
 **/
@RestController
@RequestMapping("/api/Goods")
@ResponseBody
public class ApiGoodsController {

    @Autowired
    IMallGoodsClassService classService;

    @Autowired
    IMallGoodsGoodsService goodsService;

    @Autowired
    IMallGoodsProductService productService;

    @Autowired
    IMallMemberUserService userService;

    @Autowired
    IMallOrderCommentService orderCommentService;

    @Autowired
    IMallImgService imgService;

    /*
    * 获取所有分类
    * */
    @GetMapping("/getClasses")
    public ApiResult getGoodsClasses(){
        List<MallGoodsClass> list = classService.selectDefaultMallGoodsClasses();
        if (CollectionUtils.isNotEmpty(list)){
            return ApiResult.ok().put("data",buildTree(list));
        }
        return ApiResult.ok().put("data",list);
    }

    /*
    * 根据条件查商品列表
    * */
    @GetMapping("/getGoodsByParams")
    public ApiResult getGoodsByParams(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            , @RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,MallGoodsGoods goodsModel,String userId){
        PageInfo<IndexGoodsVO> pageInfo = goodsService.selectMallGoodsGoodsListByPage(pageNum,pageSize,goodsModel,userId);
        return ApiResult.ok().put("data",pageInfo);
    }

    /*
     * 根据id查商品
     * */
    @GetMapping("/getGoodById")
    public ApiResult getGoodById(@RequestParam Map<String, Object> params){
        if (!params.containsKey("goodsId")
                ){
            return ApiResult.error("参数异常");
        }

        if (StringUtils.isNotBlank(MapUtils.getString(params, "userId"))){
            //添加足迹
            userService.insertIntoFoodMarkBD(params);
        }

        IndexGoodsVO good = goodsService.selectMallGoodsGoodsByIdVO(params);
        if (good != null){
            return ApiResult.ok().put("data",good);
        }else {
            return ApiResult.error("查无数据").put("data","");
        }
    }

    /*
     * 根据商品id 查GoodProduct
     * */
    @GetMapping("/getGoodMsgByParams")
    public ApiResult getGoodMsgByParams(String goodsId){
        MallGoodsProduct pro = new MallGoodsProduct();
        pro.setGoodsId(Long.valueOf(goodsId));
        List<GoodsProductVO> list = productService.selectMallGoodProByParams(pro);
        return ApiResult.ok().put("data",list);
    }

    /*
     * 根据商品id 查评价
     * */
    @GetMapping("/getCommentList")
    public ApiResult getCommentList(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            , @RequestParam(value="pageSize",defaultValue="10",required = false) Integer pageSize,@RequestParam Map<String, Object> params){
        if (!params.containsKey("goodsId")
                ){
            return ApiResult.error("参数异常");
        }

        PageHelper.startPage(pageNum,pageSize);
        List<Map<String, Object>>list = orderCommentService.selectCommentListByGoodsId(Long.valueOf(params.get("goodsId").toString()));
        for (Map<String, Object> map: list) {
            String commentId = map.get("id").toString();
            MallImg img = new MallImg();
            img.setType("2");
            img.setResId(Long.parseLong(commentId));
            List <String> imgList = imgService.selectMallImgUrlVoList(img);
            map.put("urls",imgList);
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo(list);
        return ApiResult.ok().put("data",pageInfo);
    }


    /**
     * 将扁平化的列表转换为树形结构
     *
     * @param flatList 扁平化的列表
     * @return 树形结构的根节点列表
     */
    public static  List<MallGoodsClassVO> buildTree(List<MallGoodsClass> flatList) {
        List<MallGoodsClassVO> rootNodes = new ArrayList<>();
        Map<Long, List<MallGoodsClass>> map = new HashMap<>();
        List<MallGoodsClass> collect = flatList.stream().filter(
                f -> f.getParentId() == null || f.getParentId() == 0).collect(Collectors.toList());
        List<MallGoodsClass> collect1 = flatList.stream().filter(
                f -> f.getParentId() != null && f.getParentId() != 0).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(collect1)){
            map = collect1.stream().collect(Collectors.groupingBy(MallGoodsClass::getParentId));
        }


        // 将所有节点放入Map中，方便通过id快速查找
        for (MallGoodsClass node : collect) {
            MallGoodsClassVO vo = new  MallGoodsClassVO();
            BeanUtils.copyProperties(node , vo);
            List<MallGoodsClass> mallGoodsClasses = map.get(node.getId());
            if(CollectionUtils.isNotEmpty(mallGoodsClasses)){
                vo.setMallGoodsClassVOS(mallGoodsClasses.stream().map(
                        m -> {
                            MallGoodsClassVO vo1 = new  MallGoodsClassVO();
                            BeanUtils.copyProperties(m , vo1);
                            return vo1;
                        }).collect(Collectors.toList()));
            }
            rootNodes.add(vo);
        }
        return rootNodes;
    }
}
