package com.qs.mp.web.controller.api.admin;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.qs.mp.admin.domain.param.ChannelGoodsOrderQueryParam;
import com.qs.mp.channel.domain.ChannelGoods;
import com.qs.mp.channel.domain.ChannelGoodsOrder;
import com.qs.mp.channel.domain.ChannelGoodsSettleOrder;
import com.qs.mp.channel.domain.ChannelGoodsSettleOrderItem;
import com.qs.mp.channel.domain.param.PushChannelGoodsSettleParam;
import com.qs.mp.channel.domain.vo.ChannelGoodsOrderVO;
import com.qs.mp.channel.domain.vo.ChannelGoodsSettleVO;
import com.qs.mp.channel.domain.vo.ChannelOrderSettleVO;
import com.qs.mp.channel.service.IChannelGoodsOrderService;
import com.qs.mp.channel.service.IChannelGoodsService;
import com.qs.mp.channel.service.IChannelGoodsSettleOrderItemService;
import com.qs.mp.channel.service.IChannelGoodsSettleOrderService;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.core.page.TableDataInfo;
import com.qs.mp.common.enums.ChannelGoodsOrderStatusEnum;
import com.qs.mp.common.exception.ServiceException;
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 org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 结算门店采购商品
 * @author zhangkaikai
 * @create 2023-06-07 2:18 PM
 **/
@Api(tags = "门店库存管理")
@RestController
@RequestMapping("/api/v1/mp/admin/channel/goods/*")
public class ChannelGoodsSettleMgrController extends BaseApiController {

    @Autowired
    private IChannelGoodsOrderService channelGoodsOrderService;

    @Autowired
    private IChannelGoodsService channelGoodsService;

    @Autowired
    private IChannelGoodsSettleOrderService settleOrderService;

    @Autowired
    private IChannelGoodsSettleOrderItemService settleOrderItemService;


    @PostMapping("/list")
    @ApiOperation(value = "门店库存结算列表")
    @PreAuthorize("@ss.hasPermi('business:channelGoods:list')")
    @ApiResponses(
            @ApiResponse(code = 200, message = "成功", response = ChannelGoodsSettleVO.class)
    )
    public TableDataInfo list(@RequestBody ChannelGoodsOrderQueryParam queryParam) {
        startPage();
        QueryWrapper<ChannelGoodsOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(null != queryParam && StringUtils.isNotBlank(queryParam.getOrderId()), "t1.order_id", queryParam.getOrderId());
        queryWrapper.eq(null != queryParam && null != queryParam.getChannelId(), "t1.`channel_id`", queryParam.getChannelId());
        queryWrapper.eq(null != queryParam && StringUtils.isNotBlank(queryParam.getTel()), "t1.`tel`", queryParam.getTel());
        queryWrapper.eq(null != queryParam && StringUtils.isNotBlank(queryParam.getSettleStatus()), "t3.status", queryParam.getSettleStatus());
        queryWrapper.eq("t1.status", ChannelGoodsOrderStatusEnum.FINISHED.getValue());
        queryWrapper.ge(null != queryParam && null != queryParam.getMinStock(), "t3.remain_qty", queryParam.getMinStock());
        queryWrapper.le(null != queryParam && null != queryParam.getMaxStock(), "t3.remain_qty", queryParam.getMaxStock());
        queryWrapper.ge(null != queryParam && null != queryParam.getStartTime(), "t3.created_time", queryParam.getStartTime());
        queryWrapper.le(null != queryParam && null != queryParam.getEndTime(), "t3.created_time", queryParam.getEndTime());
        queryWrapper.like(null != queryParam && StringUtils.isNotBlank(queryParam.getTitle()), "t1.title", queryParam.getTitle());
        queryWrapper.orderByDesc("t1.created_time", "t1.order_id");

        List<ChannelGoodsSettleVO> channelGoodsOrderSettleVOS = channelGoodsOrderService.selectChannelGoodsSettleList(queryWrapper);
        for (ChannelGoodsSettleVO channelGoodsOrderSettleVO : channelGoodsOrderSettleVOS) {
            List<ChannelGoods> channelGoodsList = channelGoodsService.list(
                    new QueryWrapper<ChannelGoods>().eq("order_id", channelGoodsOrderSettleVO.getOrderId())
                            .like(null != queryParam && StringUtils.isNotBlank(queryParam.getTitle()), "title", queryParam.getTitle()));
            channelGoodsOrderSettleVO.setItems(channelGoodsList);
            if (CollectionUtils.isNotEmpty(channelGoodsList)) {
                channelGoodsOrderSettleVO.setTotalQuantity(channelGoodsList.stream().mapToInt(ChannelGoods::getQuantity).sum());
                channelGoodsOrderSettleVO.setTotalRemainQty(channelGoodsList.stream().mapToInt(ChannelGoods::getRemainQty).sum());
                channelGoodsOrderSettleVO.setTotalSettleQty(channelGoodsList.stream().mapToInt(ChannelGoods::getSettleQty).sum());
                channelGoodsOrderSettleVO.setTotalVerifyQty(channelGoodsList.stream().mapToInt(ChannelGoods::getVerifyQty).sum());
                Integer totalPurchaseCost = 0;
                for (ChannelGoods channelGoods : channelGoodsList) {
                    totalPurchaseCost += channelGoods.getPurchaseCost() * channelGoods.getRemainQty();
                }
                channelGoodsOrderSettleVO.setTotalPurchaseCost(totalPurchaseCost);
                channelGoodsOrderSettleVO.setStatus(channelGoodsList.get(0).getStatus());
            }
        }
        return getDataTable(channelGoodsOrderSettleVOS);
    }

    @PostMapping("/detail/{orderId}")
    @ApiOperation(value = "门店库存结算详情")
    @PreAuthorize("@ss.hasPermi('business:channelGoods:query')")
    @ApiResponses(
            @ApiResponse(code = 200, message = "成功", response = ChannelGoodsSettleVO.class)
    )
    public AjaxResult detail(@PathVariable String orderId) {
        ChannelGoodsSettleVO channelGoodsOrderSettleVO = new ChannelGoodsSettleVO();
        ChannelGoodsOrderVO channelGoodsOrderVO = channelGoodsOrderService.listChannelGoodsOrder(new QueryWrapper<ChannelGoodsOrder>().eq("t1.order_id", orderId));
        List<ChannelGoods> channelGoodsList = channelGoodsService.list(new LambdaQueryWrapper<ChannelGoods>().eq(ChannelGoods::getOrderId, orderId));
        if (CollectionUtils.isNotEmpty(channelGoodsList)) {
            channelGoodsOrderSettleVO.setTotalQuantity(channelGoodsList.stream().mapToInt(ChannelGoods::getQuantity).sum());
            channelGoodsOrderSettleVO.setTotalRemainQty(channelGoodsList.stream().mapToInt(ChannelGoods::getRemainQty).sum());
            channelGoodsOrderSettleVO.setTotalSettleQty(channelGoodsList.stream().mapToInt(ChannelGoods::getSettleQty).sum());
            channelGoodsOrderSettleVO.setTotalVerifyQty(channelGoodsList.stream().mapToInt(ChannelGoods::getVerifyQty).sum());
            channelGoodsOrderSettleVO.setStatus(channelGoodsList.get(0).getStatus());
            Integer totalPurchaseCost = 0;
            for (ChannelGoods channelGoods : channelGoodsList) {
                totalPurchaseCost += channelGoods.getPurchaseCost() * channelGoods.getRemainQty();
            }
            // 未结算
            channelGoodsOrderSettleVO.setTotalPurchaseCost(totalPurchaseCost);
            ChannelGoodsSettleOrderItem settleOrderItem = settleOrderItemService.getOne(new LambdaQueryWrapper<ChannelGoodsSettleOrderItem>().eq(ChannelGoodsSettleOrderItem::getChannelGoodsId, channelGoodsList.get(0).getId()));
            if (settleOrderItem != null) {
                // 已结算
                ChannelGoodsSettleOrder settleOrder = settleOrderService.getOne(new LambdaQueryWrapper<ChannelGoodsSettleOrder>().eq(ChannelGoodsSettleOrder::getOrderId, settleOrderItem.getOrderId()));
                channelGoodsOrderSettleVO.setTotalPurchaseCost(settleOrder.getOrderAmt());
                channelGoodsOrderSettleVO.setPayAmount(settleOrder.getSettleAmt());
                channelGoodsOrderSettleVO.setPushTime(settleOrder.getCreatedTime());
                channelGoodsOrderSettleVO.setSettleTime(settleOrder.getPayTime());
            }
        }
        channelGoodsOrderSettleVO.setOrderId(orderId);
        channelGoodsOrderSettleVO.setTel(channelGoodsOrderVO.getTel());
        channelGoodsOrderSettleVO.setChannelName(channelGoodsOrderVO.getChannelName());
        channelGoodsOrderSettleVO.setItems(channelGoodsList);
        return AjaxResult.success(channelGoodsOrderSettleVO);
    }

    @PostMapping("/push/settle/order")
    @PreAuthorize("@ss.hasPermi('business:channelGoodsOrder:push')")
    @ApiOperation(value = "推送结算订单")
    public AjaxResult settleOrder(@RequestBody PushChannelGoodsSettleParam settleVO) {
        if (settleVO.getSettleAmt() <= 0) {
            throw new ServiceException("结算金额必须大于0");
        }
        String settleOrderId = settleOrderService.pushSettleOrder(settleVO);
        return AjaxResult.success(settleOrderId);
    }

}
