package cn.iocoder.foodnexus.module.order.controller.app.delivery;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.foodnexus.framework.common.enums.UserSystemEnum;
import cn.iocoder.foodnexus.framework.common.pojo.CommonResult;
import cn.iocoder.foodnexus.framework.common.pojo.PageResult;
import cn.iocoder.foodnexus.framework.common.util.collection.MapUtils;
import cn.iocoder.foodnexus.framework.common.util.object.BeanUtils;
import cn.iocoder.foodnexus.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.foodnexus.module.erp.controller.admin.product.vo.product.ErpProductRespVO;
import cn.iocoder.foodnexus.module.erp.controller.admin.sale.vo.order.ErpSaleOrderPageReqVO;
import cn.iocoder.foodnexus.module.erp.controller.admin.sale.vo.order.ErpSaleOrderRespVO;
import cn.iocoder.foodnexus.module.erp.dal.dataobject.sale.ErpCustomerDO;
import cn.iocoder.foodnexus.module.erp.dal.dataobject.sale.ErpSaleOrderDO;
import cn.iocoder.foodnexus.module.erp.dal.dataobject.sale.ErpSaleOrderItemDO;
import cn.iocoder.foodnexus.module.erp.service.product.ErpProductService;
import cn.iocoder.foodnexus.module.erp.service.sale.ErpCustomerService;
import cn.iocoder.foodnexus.module.erp.service.sale.ErpSaleOrderService;
import cn.iocoder.foodnexus.module.order.api.DeliveryStaffApi;
import cn.iocoder.foodnexus.module.order.dto.DeliveryOrderUpdateReqVO;
import cn.iocoder.foodnexus.module.system.annotations.AppSystemAuth;
import cn.iocoder.foodnexus.module.system.api.user.AdminUserApi;
import cn.iocoder.foodnexus.module.system.api.user.dto.AdminUserRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

import static cn.iocoder.foodnexus.framework.common.pojo.CommonResult.success;
import static cn.iocoder.foodnexus.framework.common.util.collection.CollectionUtils.convertMultiMap;
import static cn.iocoder.foodnexus.framework.common.util.collection.CollectionUtils.convertSet;

/**
 * @author : yanghao
 * create at:  2025/9/26  09:49
 * @description: 订单 - 配送
 */
@Tag(name = "配送员 - 订单 - 配送")
@RestController
@RequestMapping("/delivery/order")
@Validated
@AppSystemAuth(UserSystemEnum.DELIVERY)
public class DeliveryOrderController {

    @Autowired
    private DeliveryStaffApi deliveryStaffApi;

    @Autowired
    private ErpSaleOrderService saleOrderService;

    @Resource
    private ErpProductService productService;
    @Resource
    private ErpCustomerService customerService;

    @Resource
    private AdminUserApi adminUserApi;

    // 查询所有已拣销售订单
    @GetMapping("/page")
    @Operation(summary = "获得销售订单分页")
    public CommonResult<PageResult<ErpSaleOrderRespVO>> getSaleOrderPage(@Valid ErpSaleOrderPageReqVO pageReqVO) {
        pageReqVO.setDeliveryStaffId(deliveryStaffApi.queryStaffIdByUserId(SecurityFrameworkUtils.getLoginUserId()));
        // pageReqVO.setPickUpStatus(SaleOrderPickUpStatus.PICK_UP);
        PageResult<ErpSaleOrderDO> pageResult = saleOrderService.getSaleOrderPage(pageReqVO);
        return success(buildSaleOrderVOPageResult(pageResult));
    }

    // TODO 配送单修改实际配送数量在哪一步？

    // 配送订单，生成销售出库单
    @PostMapping("/delivery")
    @Operation(summary = "配送订单")
    @Parameter(name = "id", description = "销售订单id", required = true)
    public CommonResult<Boolean> delivery(@RequestParam("id") Long id) {
        saleOrderService.delivery(id, deliveryStaffApi.queryStaffIdByUserId(SecurityFrameworkUtils.getLoginUserId()));
        return success(Boolean.TRUE);
    }

    // 订单到货
    @PostMapping("/arrival")
    @Operation(summary = "订单到货")
    @Parameter(name = "id", description = "销售订单id", required = true)
    public CommonResult<Boolean> arrival(@RequestBody @Valid DeliveryOrderUpdateReqVO reqVO) {
        saleOrderService.arrival(reqVO, deliveryStaffApi.queryStaffIdByUserId(SecurityFrameworkUtils.getLoginUserId()));
        return success(Boolean.TRUE);
    }


    private PageResult<ErpSaleOrderRespVO> buildSaleOrderVOPageResult(PageResult<ErpSaleOrderDO> pageResult) {
        if (CollUtil.isEmpty(pageResult.getList())) {
            return PageResult.empty(pageResult.getTotal());
        }
        // 1.1 订单项
        List<ErpSaleOrderItemDO> saleOrderItemList = saleOrderService.getSaleOrderItemListByOrderIds(
                convertSet(pageResult.getList(), ErpSaleOrderDO::getId));
        Map<Long, List<ErpSaleOrderItemDO>> saleOrderItemMap = convertMultiMap(saleOrderItemList, ErpSaleOrderItemDO::getOrderId);
        // 1.2 产品信息
        Map<Long, ErpProductRespVO> productMap = productService.getProductVOMap(
                convertSet(saleOrderItemList, ErpSaleOrderItemDO::getProductId));
        // 1.3 客户信息
        Map<Long, ErpCustomerDO> customerMap = customerService.getCustomerMap(
                convertSet(pageResult.getList(), ErpSaleOrderDO::getCustomerId));
        // 1.4 管理员信息
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(
                convertSet(pageResult.getList(), saleOrder -> Long.parseLong(saleOrder.getCreator())));
        // 2. 开始拼接
        return BeanUtils.toBean(pageResult, ErpSaleOrderRespVO.class, saleOrder -> {
            saleOrder.setItems(BeanUtils.toBean(saleOrderItemMap.get(saleOrder.getId()), ErpSaleOrderRespVO.Item.class,
                    item -> MapUtils.findAndThen(productMap, item.getProductId(), product -> item.setProductName(product.getName())
                            .setProductBarCode(product.getBarCode()).setProductUnitName(product.getUnitName()))));
            saleOrder.setProductNames(CollUtil.join(saleOrder.getItems(), "，", ErpSaleOrderRespVO.Item::getProductName));
            MapUtils.findAndThen(customerMap, saleOrder.getCustomerId(), supplier -> saleOrder.setCustomerName(supplier.getName()));
            MapUtils.findAndThen(userMap, Long.parseLong(saleOrder.getCreator()), user -> saleOrder.setCreatorName(user.getNickname()));
        });
    }
}
