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

import cn.iocoder.foodnexus.framework.common.enums.UserSystemEnum;
import cn.iocoder.foodnexus.framework.common.pojo.CommonResult;
import cn.iocoder.foodnexus.framework.common.pojo.PageParam;
import cn.iocoder.foodnexus.framework.common.pojo.PageResult;
import cn.iocoder.foodnexus.framework.common.util.CommonUtil;
import cn.iocoder.foodnexus.framework.common.util.collection.MapUtils;
import cn.iocoder.foodnexus.framework.common.util.object.BeanUtils;
import cn.iocoder.foodnexus.framework.common.validation.InEnum;
import cn.iocoder.foodnexus.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.foodnexus.module.erp.controller.admin.sale.vo.order.DeliveryMyCountRespVO;
import cn.iocoder.foodnexus.module.erp.controller.admin.sale.vo.order.DeliveryOrderPageReqVO;
import cn.iocoder.foodnexus.module.erp.controller.admin.sale.vo.order.ErpSaleOrderPageReqVO;
import cn.iocoder.foodnexus.module.erp.controller.admin.sale.vo.out.ErpSaleOutRespVO;
import cn.iocoder.foodnexus.module.erp.dal.dataobject.sale.ErpSaleOrderDO;
import cn.iocoder.foodnexus.module.erp.dal.dataobject.sale.ErpSaleOutDO;
import cn.iocoder.foodnexus.module.erp.dal.dataobject.sale.ErpSaleOutItemDO;
import cn.iocoder.foodnexus.module.erp.dal.dataobject.stock.ErpStockDO;
import cn.iocoder.foodnexus.module.erp.enums.SaleOrderPickUpStatus;
import cn.iocoder.foodnexus.module.erp.service.sale.ErpSaleOrderService;
import cn.iocoder.foodnexus.module.erp.service.sale.ErpSaleOutService;
import cn.iocoder.foodnexus.module.erp.service.stock.ErpStockService;
import cn.iocoder.foodnexus.module.operations.service.deliverystaffcustomer.DeliveryStaffCustomerService;
import cn.iocoder.foodnexus.module.order.api.DeliveryStaffApi;
import cn.iocoder.foodnexus.module.order.controller.admin.customerorder.vo.CustomerOrderRespVO;
import cn.iocoder.foodnexus.module.order.controller.admin.customerorderitem.vo.CustomerOrderItemRespVO;
import cn.iocoder.foodnexus.module.order.controller.app.delivery.vo.DeliveryOrderArrivalDetails;
import cn.iocoder.foodnexus.module.order.controller.app.delivery.vo.DeliveryOrderDetails;
import cn.iocoder.foodnexus.module.order.controller.app.delivery.vo.DeliverySaleOrderRespVO;
import cn.iocoder.foodnexus.module.erp.controller.admin.sale.vo.order.DeliveryStatusCountRespVO;
import cn.iocoder.foodnexus.module.order.dto.DeliveryOrderUpdateReqVO;
import cn.iocoder.foodnexus.module.order.service.customerorder.CustomerOrderService;
import cn.iocoder.foodnexus.module.order.service.customerorderitem.CustomerOrderItemService;
import cn.iocoder.foodnexus.module.product.dal.dataobject.spu.ProductSpuDO;
import cn.iocoder.foodnexus.module.product.service.spu.ProductSpuService;
import cn.iocoder.foodnexus.module.system.annotations.AppSystemAuth;
import cn.iocoder.foodnexus.module.system.controller.admin.dept.vo.dept.DeptSimpleRespVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;

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;
import static cn.iocoder.foodnexus.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * @author : yanghao
 * create at:  2025/10/14  17:56
 * @description: 配送员 - 订单
 */
@Tag(name = "配送员 - 订单")
@RestController
@RequestMapping("/delivery/sale-order")
@Validated
@AppSystemAuth(UserSystemEnum.DELIVERY)
public class DeliverySaleOrderController {

    @Autowired
    private DeliveryStaffApi deliveryStaffApi;

    @Autowired
    private DeliveryStaffCustomerService deliveryStaffCustomerService;

    @Autowired
    private ErpSaleOrderService saleOrderService;

    @Autowired
    private CustomerOrderService customerOrderService;

    @Autowired
    private CustomerOrderItemService customerOrderItemService;

    @Autowired
    private ErpSaleOutService saleOutService;

    @GetMapping("/my-count")
    @Operation(summary = "个人中心 - 配送订单数")
    public CommonResult<DeliveryMyCountRespVO> queryMyCount() {
        return success(saleOrderService.queryMyCount(deliveryStaffApi.queryStaffIdByUserId(getLoginUserId())));
    }

    @GetMapping("/status-count")
    @Operation(summary = "接单大厅 - 配送状态订单数统计")
    public CommonResult<List<DeliveryStatusCountRespVO>> statusCount() {
        List<DeptSimpleRespVO> deptSimpleRespVOS = deliveryStaffCustomerService.queryDeptListByStaffId(deliveryStaffApi.queryStaffIdByUserId(getLoginUserId()));
        Set<Long> deptIds = CommonUtil.listConvertSet(deptSimpleRespVOS, DeptSimpleRespVO::getId);
        return success(saleOrderService.statusCount(getLoginUserId(), deptIds));
    }

    @GetMapping("/my-page")
    @Operation(summary = "个人中心 - 订单")
    public CommonResult<PageResult<DeliverySaleOrderRespVO>> queryMyPage(@Valid DeliveryOrderPageReqVO reqVO) {
        reqVO.setDeliveryStaffId(deliveryStaffApi.queryStaffIdByUserId(getLoginUserId()));
        ErpSaleOrderPageReqVO pageReqVO = BeanUtils.toBean(reqVO, ErpSaleOrderPageReqVO.class);
        return success(BeanUtils.toBean(saleOrderService.getSaleOrderPage(pageReqVO), DeliverySaleOrderRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "接单大厅 - 查询配送单")
    @Parameter(name = "type", description = "0-待接单 1-待配送 2-配送中", required = true, example = "1024")
    public CommonResult<PageResult<DeliverySaleOrderRespVO>> getSaleOrderPage(@Valid PageParam pageReq,
                                                                              @RequestParam("type")
                                                                              Integer type) {
        ErpSaleOrderPageReqVO pageReqVO = new ErpSaleOrderPageReqVO();
        pageReqVO.setPageNo(pageReq.getPageNo());
        pageReqVO.setPageSize(pageReq.getPageSize());
        if (type < 0 || type > 2) {
            return success(new PageResult<>());
        }
        if (type == 0) {
            List<DeptSimpleRespVO> deptSimpleRespVOS = deliveryStaffCustomerService.queryDeptListByStaffId(deliveryStaffApi.queryStaffIdByUserId(getLoginUserId()));
            pageReqVO.setCustomerDeptIds(CommonUtil.listConvert(deptSimpleRespVOS, DeptSimpleRespVO::getId));
            pageReqVO.setPickUpStatusList(CommonUtil.asList(SaleOrderPickUpStatus.PICK_UP.getType(),
                    SaleOrderPickUpStatus.RETURNS_APPROVE.getType()));
        } else {
            pageReqVO.setDeliveryStaffId(deliveryStaffApi.queryStaffIdByUserId(getLoginUserId()));
            if (type == 1) {
                pageReqVO.setPickUpStatusList(CommonUtil.asList(SaleOrderPickUpStatus.ACCEPT.getType(),
                        SaleOrderPickUpStatus.RETURNS_STAFF_ACCEPT.getType()));
            }
            if (type == 2) {
                pageReqVO.setPickUpStatusList(CommonUtil.asList(SaleOrderPickUpStatus.ALREADY.getType(),
                        SaleOrderPickUpStatus.RETURNS_STAFF_ALREADY.getType()));
            }
        }
        return success(BeanUtils.toBean(saleOrderService.getSaleOrderPage(pageReqVO), DeliverySaleOrderRespVO.class));
    }

    @GetMapping("/get")
    @Operation(summary = "配送单详情")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<DeliveryOrderDetails<DeliverySaleOrderRespVO>> getSaleOrder(@RequestParam("id") Long id) {
        ErpSaleOrderDO saleOrder = saleOrderService.getSaleOrder(id);
        if (saleOrder == null) {
            return success(null);
        }
        DeliveryOrderDetails<DeliverySaleOrderRespVO> result = new DeliveryOrderDetails<>();
        result.setDeliveryInfo(BeanUtils.toBean(saleOrder, DeliverySaleOrderRespVO.class));
        result.setCustomerOrderInfo(BeanUtils.toBean(customerOrderService.getCustomerOrder(saleOrder.getCustomerOrderId()),
                CustomerOrderRespVO.class, item ->
                        item.setOrderItems(BeanUtils.toBean(customerOrderItemService.queryByOrderId(item.getId()), CustomerOrderItemRespVO.class))));
        return success(result);
    }

    @PostMapping("/accept")
    @Operation(summary = "确认接单")
    @Parameter(name = "id", description = "配送单id(deliveryInfo.id)", required = true)
    public CommonResult<Boolean> accept(@RequestParam("id") Long id) {
        saleOrderService.accept(id, deliveryStaffApi.queryStaffIdByUserId(getLoginUserId()));
        return success(Boolean.TRUE);
    }

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

    // 订单到货
    @PostMapping("/arrival")
    @Operation(summary = "订单到货")
    public CommonResult<Boolean> arrival(@RequestBody @Valid DeliveryOrderUpdateReqVO reqVO) {
        saleOrderService.arrival(reqVO, deliveryStaffApi.queryStaffIdByUserId(getLoginUserId()));
        return success(Boolean.TRUE);
    }

    @GetMapping("/arrival")
    @Operation(summary = "配货单 - 订单到货 详情")
    @Parameter(name = "id", description = "客户订单id(customerOrderInfo.id)", required = true)
    public CommonResult<List<DeliveryOrderArrivalDetails>> getSaleOut(@RequestParam("id") Long id) {
        ErpSaleOutDO saleOut = saleOutService.getSaleOutByCustomerOrderId(id);
        if (saleOut == null) {
            return success(null);
        }
        List<ErpSaleOutItemDO> saleOutItemList = saleOutService.getSaleOutItemListByOutId(saleOut.getId());
        return success(BeanUtils.toBean(saleOutItemList, DeliveryOrderArrivalDetails.class));
    }


}
