package com.qs.mp.web.controller.api.channel;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qs.mp.admin.domain.Goods;
import com.qs.mp.admin.domain.GoodsSku;
import com.qs.mp.admin.domain.vo.GoodsVO;
import com.qs.mp.admin.service.IGoodsService;
import com.qs.mp.admin.service.IGoodsSkuService;
import com.qs.mp.channel.domain.ChannelGoods;
import com.qs.mp.channel.domain.ChannelGoodsSettleOrderItem;
import com.qs.mp.channel.domain.param.SiteGoodsForChannelQueryParam;
import com.qs.mp.channel.domain.param.SiteGoodsQueryParam;
import com.qs.mp.channel.domain.vo.ChannelGoodsVO;
import com.qs.mp.channel.service.IChannelGoodsService;
import com.qs.mp.channel.service.IChannelGoodsSettleOrderItemService;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.core.page.TableDataInfo;
import com.qs.mp.common.enums.ChannelGoodsSettleStatusTypeEnum;
import com.qs.mp.common.enums.GoodsStatusEnum;
import com.qs.mp.utils.SecurityUtils;
import com.qs.mp.web.controller.common.BaseApiController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;


import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangkaikai
 * @create 2023-06-01 5:04 PM
 **/
@Api(tags = "门店采购商品管理")
@RestController
@RequestMapping("/api/v1/mp/channel/*")
@Component
public class ChannelGoodsController extends BaseApiController {

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private IGoodsSkuService goodsSkuService;

    @Autowired
    private IChannelGoodsService channelGoodsService;

    @Autowired
    private IChannelGoodsSettleOrderItemService settleOrderItemService;

    @Autowired
    private MapperFacade mapperFacade;

    @PostMapping("/site/goods/list")
    @ApiOperation("采购商品列表")
    @ApiResponses(
            @ApiResponse(code = 200, message = "成功", response = GoodsVO.class)
    )
    public TableDataInfo siteGoodsList(@RequestBody SiteGoodsQueryParam param) {

        startPage();
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<Goods>();
        queryWrapper.eq("type", param.getType())
                .eq("status", GoodsStatusEnum.PUT_ON)
                .orderByDesc("created_time");
        List<Goods> goodsList = goodsService.list(queryWrapper);

        List<GoodsVO> goodsVOList = mapperFacade.mapAsList(goodsList, GoodsVO.class);

        for (GoodsVO goodsVO : goodsVOList) {
            List<GoodsSku> skuList = goodsSkuService.list(new QueryWrapper<GoodsSku>().eq("goods_id", goodsVO.getGoodsId()));
            goodsVO.setSkuList(skuList);
        }

        return getDataTable(goodsVOList);
    }

    @PostMapping("/site/goods/detail/{goodsId}")
    @ApiOperation("采购商品详情")
    @ApiResponses(
            @ApiResponse(code = 200, message = "成功", response = GoodsVO.class)
    )
    public AjaxResult siteGoodsDetail(@PathVariable("goodsId") Integer goodsId) {
        Goods goods = goodsService.getById(goodsId);
        List<GoodsSku> skuList = goodsSkuService.list(new QueryWrapper<GoodsSku>().eq("goods_id", goodsId));
        GoodsVO goodsVO = mapperFacade.map(goods, GoodsVO.class);
        goodsVO.setSkuList(skuList);
        return AjaxResult.success(goodsVO);
    }

    @PostMapping("/goods/list/channel")
    @ApiOperation("门店铺设商品列表")
    @ApiResponses(
            @ApiResponse(code = 200, message = "成功", response = ChannelGoodsVO.class)
    )
    public TableDataInfo goodsListChannel(@RequestBody SiteGoodsForChannelQueryParam param) {
        Long channelId = SecurityUtils.getLoginUser().getChannelId();
        if (param.getChannelId() != null) {
            channelId = param.getChannelId();
        }
        QueryWrapper<ChannelGoods> wrapper = new QueryWrapper<ChannelGoods>()
                .eq("t1.channel_id", channelId)
                .eq("t1.status", param.getSettleStatus());
        if (ChannelGoodsSettleStatusTypeEnum.NO.equals(param.getSettleStatus())) {
            wrapper.orderByAsc("t1.remain_qty");
            wrapper.orderByDesc("t1.created_time");
        } else {
            wrapper.orderByDesc("t1.settle_time");
        }
        List<ChannelGoodsVO> channelGoodsList = channelGoodsService.listChannelGoods(wrapper);
        for (ChannelGoodsVO channelGoodsVO : channelGoodsList) {
            if (ChannelGoodsSettleStatusTypeEnum.DOING.equals(channelGoodsVO.getStatus())) {
                List<ChannelGoodsSettleOrderItem> items = settleOrderItemService.list(new QueryWrapper<ChannelGoodsSettleOrderItem>().eq("channel_goods_id", channelGoodsVO.getId()));
                channelGoodsVO.setSettleOrderId(items.get(0).getOrderId());
                channelGoodsVO.setPurchaseOrderId(channelGoodsVO.getOrderId());
            }
        }
        return getDataTable(channelGoodsList);
    }

    @PostMapping("goods/list/under/channel")
    @ApiResponses(
            @ApiResponse(code = 200, message = "成功", response = ChannelGoodsVO.class)
    )
    @ApiOperation("渠道下门店库存列表")
    public TableDataInfo goodsListUnderChannel() {
        startPage();
        Long channelId = SecurityUtils.getLoginUser().getChannelId();
        QueryWrapper<ChannelGoods> wrapper = new QueryWrapper<ChannelGoods>()
                .eq("t3.channel_id", channelId);
        List<ChannelGoodsVO> channelGoodsVOs = channelGoodsService.listChannelGoodsUnderChannel(wrapper);
        Map<Long, List<ChannelGoodsVO>> map = channelGoodsVOs.stream().collect(Collectors.groupingBy(ChannelGoodsVO::getChannelId));
        List<ChannelGoodsVO> channelGoodsVOList = new ArrayList<>();
        for (Map.Entry<Long, List<ChannelGoodsVO>> entry : map.entrySet()) {
            ChannelGoodsVO channelGoodsVO = new ChannelGoodsVO();
            List<ChannelGoodsVO> value = entry.getValue();
            int totalQuantity = value.stream().mapToInt(ChannelGoods::getQuantity).sum();
            int totalVerQuantity = value.stream().mapToInt(ChannelGoods::getVerifyQty).sum();
            int remainTotalQuantity = value.stream().mapToInt(ChannelGoodsVO::getRemainQty).sum();
            List<ChannelGoodsVO> NoSettleGoods = value.stream().filter(g -> ChannelGoodsSettleStatusTypeEnum.NO.equals(g.getStatus())).collect(Collectors.toList());
            int deepQuantity = NoSettleGoods.stream().mapToInt(ChannelGoods::getRemainQty).min().orElse(0);
            channelGoodsVO.setTotalQuantity(totalQuantity);
            channelGoodsVO.setTotalVerQuantity(totalVerQuantity);
            channelGoodsVO.setRemainTotalQuantity(remainTotalQuantity);
            channelGoodsVO.setDeepQuantity(deepQuantity);
            channelGoodsVO.setChannelId(value.get(0).getChannelId());
            channelGoodsVO.setChannelName(value.get(0).getChannelName());
            channelGoodsVOList.add(channelGoodsVO);
        }
        TableDataInfo info = getDataTable(channelGoodsVOs);
        info.setRows(channelGoodsVOList);
        return info;
    }







}
