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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qs.mp.admin.domain.Goods;
import com.qs.mp.admin.domain.param.ChannelGoodsOrderQueryParam;
import com.qs.mp.admin.domain.param.ChannelGoodsOrderShipParam;
import com.qs.mp.admin.service.IGoodsService;
import com.qs.mp.channel.domain.Channel;
import com.qs.mp.channel.domain.ChannelGoods;
import com.qs.mp.channel.domain.ChannelGoodsOrder;
import com.qs.mp.channel.domain.ChannelGoodsOrderItem;
import com.qs.mp.channel.domain.excel.ChannelGoodsOrderExcel;
import com.qs.mp.channel.domain.vo.ChannelGoodsOrderInfoVO;
import com.qs.mp.channel.domain.vo.ChannelGoodsOrderItemVO;
import com.qs.mp.channel.domain.vo.ChannelGoodsOrderVO;
import com.qs.mp.channel.service.IChannelGoodsOrderItemService;
import com.qs.mp.channel.service.IChannelGoodsOrderService;
import com.qs.mp.channel.service.IChannelGoodsService;
import com.qs.mp.channel.service.IChannelService;
import com.qs.mp.common.annotation.Log;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.core.page.TableDataInfo;
import com.qs.mp.common.domain.DeliveryCompany;
import com.qs.mp.common.enums.*;
import com.qs.mp.common.service.IDeliveryCompanyService;
import com.qs.mp.common.utils.DateUtils;
import com.qs.mp.utils.ExcelUtil;
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 lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author zhangkaikai
 * @create 2023-06-05 3:12 PM
 **/

@Api(tags = "门店采购商品订单管理")
@RestController
@RequestMapping("/api/v1/mp/admin/channel/goods/order")
@AllArgsConstructor
public class ChannelGoodsOrderMgrController extends BaseApiController {

    @Autowired
    private IChannelGoodsOrderService channelGoodsOrderService;

    @Autowired
    private IChannelGoodsOrderItemService channelGoodsOrderItemService;

    @Autowired
    private IChannelService channelService;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private IDeliveryCompanyService deliveryCompanyService;

    @Autowired
    private IChannelGoodsService channelGoodsService;

    @Autowired
    private MapperFacade mapperFacade;

    /**
     * 采购商品订单列表
     */
    @PostMapping("/list")
    @ApiOperation(value = "订单列表", notes = "获取所有订单信息")
    @PreAuthorize("@ss.hasPermi('channelGoods:channel:list')")
    @ApiResponses(
            @ApiResponse(code = 200, message = "success", response = ChannelGoodsOrderVO.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.getStatus(), "t1.`status`", queryParam.getStatus());
        queryWrapper.eq(null != queryParam && StringUtils.isNotBlank(queryParam.getTel()), "t1.`tel`", queryParam.getTel());
        queryWrapper.ge(null != queryParam && null != queryParam.getStartTime(), "t1.created_time", queryParam.getStartTime());
        queryWrapper.le(null != queryParam && null != queryParam.getEndTime(), "t1.created_time", queryParam.getEndTime());
        queryWrapper.eq(null != queryParam && null != queryParam.getSupplierId(), "t3.supplier_id", queryParam.getSupplierId());
        queryWrapper.eq(null != queryParam && null != queryParam.getChannelId(), "t4.channel_id", queryParam.getChannelId());
        queryWrapper.like(null != queryParam && StringUtils.isNotBlank(queryParam.getTitle()), "t2.title", queryParam.getTitle());
        queryWrapper.orderByDesc("t1.created_time", "t1.order_id");
        List<ChannelGoodsOrderVO> list = channelGoodsOrderService.selectChannelGoodsOrderVOList(queryWrapper);
        for (ChannelGoodsOrderVO channelGoodsOrderVO : list) {
            QueryWrapper<ChannelGoodsOrderItem> goodsOrderItemQueryWrapper = new QueryWrapper<>();
            goodsOrderItemQueryWrapper.eq("t1.order_id", channelGoodsOrderVO.getOrderId());
            List<ChannelGoodsOrderItemVO> orderItemVOList = channelGoodsOrderItemService.selectChannelGoodsOrderItemVOList(goodsOrderItemQueryWrapper);
            channelGoodsOrderVO.setItems(orderItemVOList);
        }
        return getDataTable(list);
    }

    /**
     * 采购商品订单详情
     */
    @PostMapping("/detail")
    @ApiOperation(value = "订单详情", notes = "在订单列表页面查看详情")
    @PreAuthorize("@ss.hasPermi('channelGoods:channel:query')")
    @ApiResponses(
            @ApiResponse(code = 200, message = "success", response = ChannelGoodsOrderInfoVO.class)
    )
    public AjaxResult query(@RequestBody ChannelGoodsOrder order) {
        if (null == order || StringUtils.isBlank(order.getOrderId())) {
            return error(ErrorCodeEnum.ERROR_CODE_1001);
        }
        ChannelGoodsOrder channelGoodsOrder = channelGoodsOrderService.getById(order.getOrderId());
        ChannelGoodsOrderInfoVO goodsOrderInfoVO = mapperFacade.map(channelGoodsOrder, ChannelGoodsOrderInfoVO.class);

        if (null != goodsOrderInfoVO && null != goodsOrderInfoVO.getChannelId()) {
            Channel channel = channelService.getById(goodsOrderInfoVO.getChannelId());
            goodsOrderInfoVO.setChannelName(channel.getName());
        }
        if (null != goodsOrderInfoVO && null != goodsOrderInfoVO.getDeliveryId()) {
            DeliveryCompany deliveryCompany = deliveryCompanyService.getById(goodsOrderInfoVO.getDeliveryId());
            goodsOrderInfoVO.setDeliveryCompany(deliveryCompany);
        }
        QueryWrapper<ChannelGoodsOrderItem> goodsOrderItemQueryWrapper = new QueryWrapper<>();
        goodsOrderItemQueryWrapper.eq("t1.order_id", order.getOrderId());
        List<ChannelGoodsOrderItemVO> orderItemVOList = channelGoodsOrderItemService.selectChannelGoodsOrderItemVOList(goodsOrderItemQueryWrapper);
//        goodsOrderInfoVO.setDeliverList(userDeliverOrderItemService.getChannelGoodsDeliverItemList(order.getOrderId(), orderItemVOList));
        goodsOrderInfoVO.setItems(orderItemVOList);
        return AjaxResult.success(goodsOrderInfoVO);
    }

    /**
     * 订单发货单号修改
     */
    @Log(title = "经销商订单发货单号修改", businessType = BusinessType.UPDATE)
    @PostMapping("/ship/update")
    @ApiOperation(value = "订单发货单号修改" , notes = "在订单发货页面提交")
    @ApiResponses(
            @ApiResponse(code = 200, message = "操作成功", response = AjaxResult.class)
    )
    @PreAuthorize("@ss.hasPermi('channelGoods:channel:ship')")
    public AjaxResult updateShipInfo(@RequestBody ChannelGoodsOrderShipParam shipParam) {
        if(null == shipParam || StringUtils.isBlank(shipParam.getOrderId())) {
            return error(ErrorCodeEnum.ERROR_CODE_1001);
        }

        ChannelGoodsOrder order  = channelGoodsOrderService.getById(shipParam.getOrderId());
        if(null == order || StringUtils.isBlank(order.getOrderId())
                || null == order.getChannelId()) {
            return error(ErrorCodeEnum.ERROR_CODE_1001);
        }

        Integer deliveryType = shipParam.getDeliveryType();
        if (DeliverTypeEnum.DELIVER.getValue().equals(deliveryType)) {
            if (Objects.isNull(shipParam.getDeliveryId())) {
                return AjaxResult.error("快递公司不能为空");
            }
            if (StringUtils.isBlank(shipParam.getDeliveryFlowId())) {
                return AjaxResult.error("快递单号不能为空");
            }
        }

        boolean rtn = false;
        if (DeliverTypeEnum.NO_DELIVER.getValue().equals(deliveryType)) {
            // 无需物流，设置单号为空，物流公司为空
            rtn = channelGoodsOrderService.update(new LambdaUpdateWrapper<ChannelGoodsOrder>()
                    .set(ChannelGoodsOrder::getDeliveryId, null)
                    .set(ChannelGoodsOrder::getDeliveryFlowId, null)
                    .set(ChannelGoodsOrder::getStatus, ChannelGoodsOrderStatusEnum.FINISHED)
                    .eq(ChannelGoodsOrder::getOrderId, shipParam.getOrderId()));

            // 商品自动入库
            List<ChannelGoodsOrderItem> items = channelGoodsOrderItemService.list(new QueryWrapper<ChannelGoodsOrderItem>().eq("order_id", order.getOrderId()));
            List<ChannelGoods> goodsList = new ArrayList<>();
            for (ChannelGoodsOrderItem item : items) {
                Goods goods = goodsService.getById(item.getGoodsId());
                ChannelGoods channelGoods = new ChannelGoods();
                channelGoods.setChannelId(item.getChannelId());
                channelGoods.setGoodsId(item.getGoodsId());
                channelGoods.setOrderId(item.getOrderId());
                channelGoods.setSkuId(item.getSkuId());
                channelGoods.setProperties(item.getProperties());
                channelGoods.setTitle(item.getTitle());
                channelGoods.setPicUrl(item.getPicUrl());
                channelGoods.setStatus(ChannelGoodsSettleStatusTypeEnum.NO);
                channelGoods.setRefId(goods.getRefId());
                channelGoods.setSupplierId(item.getSupplierId());
                channelGoods.setQuantity(item.getGoodsNum());
                channelGoods.setRemainQty(item.getGoodsNum());
                channelGoods.setPurchasePrice(item.getPurchasePrice());
                channelGoods.setPurchaseCost(item.getPurchaseCost());
                goodsList.add(channelGoods);
            }
            channelGoodsService.saveBatch(goodsList);

        } else if (DeliverTypeEnum.DELIVER.getValue().equals(deliveryType)) {
            // 快递发货，原逻辑
            rtn = channelGoodsOrderService.update(new LambdaUpdateWrapper<ChannelGoodsOrder>()
                    .set(ChannelGoodsOrder::getDeliveryId, shipParam.getDeliveryId())
                    .set(ChannelGoodsOrder::getDeliveryFlowId, shipParam.getDeliveryFlowId())
                    .eq(ChannelGoodsOrder::getOrderId, shipParam.getOrderId()));
        }

        return rtn ? AjaxResult.success() : AjaxResult.error("修改失败");

    }


    /**
     * 订单发货
     */
    @Log(title = "订单发货", businessType = BusinessType.UPDATE)
    @PostMapping("/ship")
    @ApiOperation(value = "订单发货", notes = "在订单发货页面提交")
    @PreAuthorize("@ss.hasPermi('channelGoods:channel:ship')")
    public AjaxResult ship(@RequestBody ChannelGoodsOrderShipParam shipParam) {

        if(null == shipParam || StringUtils.isBlank(shipParam.getOrderId())) {
            return error(ErrorCodeEnum.ERROR_CODE_1001);
        }
        ChannelGoodsOrder order = channelGoodsOrderService.getById(shipParam.getOrderId());


        if(null == order || StringUtils.isBlank(order.getOrderId())
                || null == order.getChannelId()) {
            return error(ErrorCodeEnum.ERROR_CODE_1001);
        }
        Integer deliveryType = shipParam.getDeliveryType();

        if (DeliverTypeEnum.DELIVER.getValue().equals(deliveryType)) {
            if (Objects.isNull(shipParam.getDeliveryId())) {
                return AjaxResult.error("快递公司不能为空");
            }
            if (StringUtils.isBlank(shipParam.getDeliveryFlowId())) {
                return AjaxResult.error("快递单号不能为空");
            }
        }

        ChannelGoodsOrder goodsOrder = new ChannelGoodsOrder();
        if (DeliverTypeEnum.NO_DELIVER.getValue().equals(deliveryType)) {
            // 无需物流，设置发货时间为当前时间
            goodsOrder.setOrderId(shipParam.getOrderId());
            goodsOrder.setChannelId(order.getChannelId());
            goodsOrder.setDeliveryTime(new Date());

        } else if (DeliverTypeEnum.DELIVER.getValue().equals(deliveryType)) {
            // 快递发货，设置物流信息
            goodsOrder.setOrderId(shipParam.getOrderId());
            goodsOrder.setChannelId(order.getChannelId());
            goodsOrder.setDeliveryId(shipParam.getDeliveryId().toString());
            goodsOrder.setDeliveryFlowId(shipParam.getDeliveryFlowId());
            goodsOrder.setDeliveryTime(new Date());
        }

        boolean rst = channelGoodsOrderService.ship(goodsOrder);
        return AjaxResult.success("发货成功");

    }

    @Log(title = "订单导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @PreAuthorize("@ss.hasPermi('channelGoods:channel:export')")
    public AjaxResult export(@RequestBody ChannelGoodsOrderQueryParam queryParam) {
        Date startTime = queryParam.getStartTime();
        Date endTime = queryParam.getEndTime();
        if (startTime == null || endTime == null) {
            return AjaxResult.error("导出数据必须设置日期范围");
        }
        if (DateUtils.diff(startTime, endTime) > 30) {
            return AjaxResult.error("导出的数据不能超过31天");
        }

        List<ChannelGoodsOrderExcel> excelList = new ArrayList<>();
        List<ChannelGoodsOrderVO> listALl = new ArrayList<>();

        QueryWrapper<ChannelGoodsOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(null != queryParam && StringUtils.isNotBlank(queryParam.getOrderId()), "t1.order_id", queryParam.getOrderId());
        queryWrapper.eq(null != queryParam && null != queryParam.getStatus(), "t1.`status`", queryParam.getStatus());
        queryWrapper.eq(null != queryParam && StringUtils.isNotBlank(queryParam.getTel()), "t1.`tel`", queryParam.getTel());
        queryWrapper.ge(null != queryParam && null != queryParam.getStartTime(), "t1.created_time", queryParam.getStartTime());
        queryWrapper.le(null != queryParam && null != queryParam.getEndTime(), "t1.created_time", queryParam.getEndTime());
        queryWrapper.eq(null != queryParam && null != queryParam.getSupplierId(), "t3.supplier_id", queryParam.getSupplierId());
        queryWrapper.eq(null != queryParam && null != queryParam.getChannelId(), "t4.channel_id", queryParam.getChannelId());
        queryWrapper.like(null != queryParam && StringUtils.isNotBlank(queryParam.getTitle()), "t2.title", queryParam.getTitle());
        queryWrapper.orderByDesc("t1.created_time", "t1.order_id");
        int totalSize = channelGoodsOrderService.selectChannelGoodsOrderCount(queryWrapper);

        if (totalSize == 0) {
            return AjaxResult.error("没有符合条件的采购商品订单");
        }

        int pageSize = 2000;
        if (totalSize > pageSize) {
            int totalPage = totalSize % pageSize == 0 ? totalSize / pageSize : totalSize / pageSize + 1;
            for (int i = 0; i < totalPage; i++) {
                queryWrapper.last("limit " + (i * pageSize) + ", " + pageSize);
                List<ChannelGoodsOrderVO> channelGoodsOrderVOList = channelGoodsOrderService.selectChannelGoodsOrderVOList(queryWrapper);
                for (ChannelGoodsOrderVO channelGoodsOrderVO : channelGoodsOrderVOList) {
                    List<ChannelGoodsOrderItem> items = channelGoodsOrderItemService.list(new LambdaQueryWrapper<ChannelGoodsOrderItem>().eq(ChannelGoodsOrderItem::getOrderId, channelGoodsOrderVO.getOrderId()));
                    List<ChannelGoodsOrderItemVO> channelGoodsOrderItemVOS = mapperFacade.mapAsList(items, ChannelGoodsOrderItemVO.class);
                    for (ChannelGoodsOrderItemVO itemVO : channelGoodsOrderItemVOS) {
                        Goods goods = goodsService.getById(itemVO.getGoodsId());
                        itemVO.setTitle(goods.getTitle());
                    }
                    channelGoodsOrderVO.setItems(channelGoodsOrderItemVOS);
                }
                if (channelGoodsOrderVOList.size() > 0) {
                    listALl.addAll(channelGoodsOrderVOList);
                }
            }
        } else {
            listALl = channelGoodsOrderService.selectChannelGoodsOrderVOList(queryWrapper);
            for (ChannelGoodsOrderVO channelGoodsOrderVO : listALl) {
                List<ChannelGoodsOrderItem> items = channelGoodsOrderItemService.list(new LambdaQueryWrapper<ChannelGoodsOrderItem>().eq(ChannelGoodsOrderItem::getOrderId, channelGoodsOrderVO.getOrderId()));
                List<ChannelGoodsOrderItemVO> channelGoodsOrderItemVOS = mapperFacade.mapAsList(items, ChannelGoodsOrderItemVO.class);
                for (ChannelGoodsOrderItemVO itemVO : channelGoodsOrderItemVOS) {
                    Goods goods = goodsService.getById(itemVO.getGoodsId());
                    itemVO.setTitle(goods.getTitle());
                }
                channelGoodsOrderVO.setItems(channelGoodsOrderItemVOS);
            }
        }

        if (listALl.size() > 0) {
            for (ChannelGoodsOrderVO goodsOrderVO : listALl) {
                if (null != goodsOrderVO && StringUtils.isNotBlank(goodsOrderVO.getOrderId())
                        && StringUtils.isNotBlank(goodsOrderVO.getReceiver())
                        && StringUtils.isNotBlank(goodsOrderVO.getTel())
                        && StringUtils.isNotBlank(goodsOrderVO.getProvince())
                        && StringUtils.isNotBlank(goodsOrderVO.getCity())
                        && StringUtils.isNotBlank(goodsOrderVO.getArea())
                        && StringUtils.isNotBlank(goodsOrderVO.getAddress()) && null != goodsOrderVO.getItems()
                        && goodsOrderVO.getItems().size() > 0) {
                    for (ChannelGoodsOrderItemVO item : goodsOrderVO.getItems()) {
                        if (null != item) {
                            ChannelGoodsOrderExcel excel = new ChannelGoodsOrderExcel();
                            excel.setTitle(item.getTitle());
                            excel.setNum(item.getGoodsNum().toString());
                            excel.setSupplierName(goodsOrderVO.getSupplierName());
                            excel.setCreateTime(goodsOrderVO.getCreatedTime());
                            excel.setAddress(goodsOrderVO.getProvince() + goodsOrderVO.getCity() + goodsOrderVO.getArea() + goodsOrderVO.getAddress());
                            excel.setOrderStatus(goodsOrderVO.getStatus().getDesc());
                            excel.setShipStatus(goodsOrderVO.getStatus().getValue() > 1 ? "已发货" : "未发货”)");
                            excel.setOrderNo(goodsOrderVO.getOrderId());
                            excel.setReceiver(goodsOrderVO.getReceiver());
                            excel.setTel(goodsOrderVO.getTel());
                            excel.setMemo(goodsOrderVO.getMemo());
                            excelList.add(excel);
                        }
                    }
                }
            }
        }

        ExcelUtil<ChannelGoodsOrderExcel> util = new ExcelUtil<>(ChannelGoodsOrderExcel.class);
        return util.exportExcel(excelList, "门店采购商品订单导出",false);
     }


}
