package cn.iocoder.foodnexus.module.erp.controller.admin.sale;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.foodnexus.framework.apilog.core.annotation.ApiAccessLog;
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.util.spring.SpringUtils;
import cn.iocoder.foodnexus.framework.excel.core.util.ExcelUtils;
import cn.iocoder.foodnexus.module.erp.api.service.ErpSupplierApi;
import cn.iocoder.foodnexus.module.erp.controller.admin.product.vo.product.ErpProductRespVO;
import cn.iocoder.foodnexus.module.erp.controller.admin.sale.vo.order.ErpSaleOrderRespVO;
import cn.iocoder.foodnexus.module.erp.controller.admin.sale.vo.returns.ErpSaleReturnPageReqVO;
import cn.iocoder.foodnexus.module.erp.controller.admin.sale.vo.returns.ErpSaleReturnRespVO;
import cn.iocoder.foodnexus.module.erp.controller.admin.sale.vo.returns.ErpSaleReturnSaveReqVO;
import cn.iocoder.foodnexus.module.erp.dal.dataobject.sale.ErpCustomerDO;
import cn.iocoder.foodnexus.module.erp.dal.dataobject.sale.ErpSaleReturnDO;
import cn.iocoder.foodnexus.module.erp.dal.dataobject.sale.ErpSaleReturnItemDO;
import cn.iocoder.foodnexus.module.erp.dal.dataobject.stock.ErpStockDO;
import cn.iocoder.foodnexus.module.erp.service.product.ErpProductService;
import cn.iocoder.foodnexus.module.erp.service.purchase.ErpPurchaseReturnService;
import cn.iocoder.foodnexus.module.erp.service.sale.ErpCustomerService;
import cn.iocoder.foodnexus.module.erp.service.sale.ErpSaleReturnService;
import cn.iocoder.foodnexus.module.erp.service.stock.ErpStockService;
import cn.iocoder.foodnexus.module.order.api.CustomerOrderApi;
import cn.iocoder.foodnexus.module.order.api.DeliveryStaffApi;
import cn.iocoder.foodnexus.module.order.dto.CustomerOrderDTO;
import cn.iocoder.foodnexus.module.order.dto.DeliveryStaffSimpleInfo;
import cn.iocoder.foodnexus.module.product.api.dto.ProductInfo;
import cn.iocoder.foodnexus.module.system.api.user.AdminUserApi;
import cn.iocoder.foodnexus.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.foodnexus.module.system.controller.admin.vo.AuditCommonReqVO;
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.servlet.http.HttpServletResponse;
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.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static cn.iocoder.foodnexus.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
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;

@Tag(name = "管理后台 - ERP 销售退货")
@RestController
@RequestMapping("/erp/sale-return")
@Validated
public class ErpSaleReturnController {

    @Resource
    private ErpSaleReturnService saleReturnService;
    @Resource
    private ErpStockService stockService;
    @Resource
    private ErpCustomerService customerService;

    @Resource
    private AdminUserApi adminUserApi;

    @Autowired
    private DeliveryStaffApi deliveryStaffApi;

    @Autowired
    private ErpSupplierApi supplierApi;

    @Autowired
    private ErpPurchaseReturnService purchaseReturnService;

    @Autowired
    private CustomerOrderApi customerOrderApi;


    @PostMapping("/create")
    @Operation(summary = "创建销售退货")
    @PreAuthorize("@ss.hasPermission('erp:sale-return:create')")
    public CommonResult<Long> createSaleReturn(@Valid @RequestBody ErpSaleReturnSaveReqVO createReqVO) {
        return success(saleReturnService.createSaleReturn(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新销售退货")
    @PreAuthorize("@ss.hasPermission('erp:sale-return:update')")
    public CommonResult<Boolean> updateSaleReturn(@Valid @RequestBody ErpSaleReturnSaveReqVO updateReqVO) {
        saleReturnService.updateSaleReturn(updateReqVO);
        return success(true);
    }

    @PutMapping("/update-status")
    @Operation(summary = "更新销售退货的状态(确认退货)")
    public CommonResult<Boolean> updateSaleReturnStatus(@RequestBody AuditCommonReqVO auditCommonReqVO) {
        saleReturnService.updateSaleReturnStatus(auditCommonReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除销售退货")
    @Parameter(name = "ids", description = "编号数组", required = true)
    @PreAuthorize("@ss.hasPermission('erp:sale-return:delete')")
    public CommonResult<Boolean> deleteSaleReturn(@RequestParam("ids") List<Long> ids) {
        saleReturnService.deleteSaleReturn(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得销售退货")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:sale-return:query')")
    public CommonResult<ErpSaleReturnRespVO> getSaleReturn(@RequestParam("id") Long id) {
        ErpSaleReturnDO saleReturn = saleReturnService.getSaleReturn(id);
        if (saleReturn == null) {
            return success(null);
        }
        List<ErpSaleReturnItemDO> saleReturnItemList = saleReturnService.getSaleReturnItemListByReturnId(id);
        Map<Long, String> supplierMap = supplierApi.queryNameMapByIds(CommonUtil.listConvertSet(saleReturnItemList, ErpSaleReturnItemDO::getSupplierId));
        Map<Long, String> prNoMap = purchaseReturnService.queryNoMap(CommonUtil.listConvertSet(saleReturnItemList, ErpSaleReturnItemDO::getPurchaseReturnOrderId));
        return success(BeanUtils.toBean(saleReturn, ErpSaleReturnRespVO.class, saleReturnVO -> {
            String customerName = Optional.ofNullable(customerService.getCustomer(saleReturnVO.getCustomerId())).map(ErpCustomerDO::getName).orElse("");
            String creatorName = Optional.ofNullable(adminUserApi.getUser(Long.parseLong(saleReturnVO.getCreator()))).map(AdminUserRespDTO::getNickname).orElse("");
            saleReturnVO.setCustomerName(customerName);
            saleReturnVO.setCreatorName(creatorName);
            saleReturnVO.setDeliveryStaffInfo(deliveryStaffApi.querybyStaffId(saleReturnVO.getDeliveryStaffId()));
            String orderCode = Optional.ofNullable(customerOrderApi.queryById(saleReturnVO.getCustomerOrderId())).map(CustomerOrderDTO::getCode).orElse("");
            saleReturnVO.setCustomerOrderCode(orderCode);
            saleReturnVO.setItems(BeanUtils.toBean(saleReturnItemList, ErpSaleReturnRespVO.Item.class, item -> {
                ErpStockDO stock = stockService.getStock(item.getProductId(), item.getWarehouseId());
                item.setStockCount(stock != null ? stock.getCount() : BigDecimal.ZERO);
                MapUtils.findAndThen(supplierMap, item.getSupplierId(), item::setSupplierName);
                MapUtils.findAndThen(prNoMap, item.getPurchaseReturnOrderId(), item::setPurchaseReturnOrderNo);
            }));
            CommonResult<ErpSaleOrderRespVO> saleOrder = SpringUtils.getBean(ErpSaleOrderController.class).getSaleOrder(saleReturn.getOrderId());
            saleReturnVO.setSaleOrderItems(saleOrder.getData().getItems());
        }));
    }

    @GetMapping("/page")
    @Operation(summary = "获得销售退货分页")
    @PreAuthorize("@ss.hasPermission('erp:sale-return:query')")
    public CommonResult<PageResult<ErpSaleReturnRespVO>> getSaleReturnPage(@Valid ErpSaleReturnPageReqVO pageReqVO) {
        PageResult<ErpSaleReturnDO> pageResult = saleReturnService.getSaleReturnPage(pageReqVO);
        return success(buildSaleReturnVOPageResult(pageResult));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出销售退货 Excel")
    @PreAuthorize("@ss.hasPermission('erp:sale-return:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportSaleReturnExcel(@Valid ErpSaleReturnPageReqVO pageReqVO,
                                    HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ErpSaleReturnRespVO> list = buildSaleReturnVOPageResult(saleReturnService.getSaleReturnPage(pageReqVO)).getList();
        // 导出 Excel
        ExcelUtils.write(response, "销售退货.xls", "数据", ErpSaleReturnRespVO.class, list);
    }

    private PageResult<ErpSaleReturnRespVO> buildSaleReturnVOPageResult(PageResult<ErpSaleReturnDO> pageResult) {
        if (CollUtil.isEmpty(pageResult.getList())) {
            return PageResult.empty(pageResult.getTotal());
        }
        // 1.1 退货项
        List<ErpSaleReturnItemDO> saleReturnItemList = saleReturnService.getSaleReturnItemListByReturnIds(
                convertSet(pageResult.getList(), ErpSaleReturnDO::getId));
        Map<Long, List<ErpSaleReturnItemDO>> saleReturnItemMap = convertMultiMap(saleReturnItemList, ErpSaleReturnItemDO::getReturnId);
        // 1.3 客户信息
        Map<Long, ErpCustomerDO> customerMap = customerService.getCustomerMap(
                convertSet(pageResult.getList(), ErpSaleReturnDO::getCustomerId));
        // 1.4 管理员信息
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(
                convertSet(pageResult.getList(), saleReturn -> Long.parseLong(saleReturn.getCreator())));
        Map<Long, DeliveryStaffSimpleInfo> deliveryMap = deliveryStaffApi.getMap(CommonUtil.listConvertSet(pageResult.getList(), ErpSaleReturnDO::getDeliveryStaffId));
        Map<Long, String> codeMap = customerOrderApi.getCodeMap(CommonUtil.listConvertSet(pageResult.getList(), ErpSaleReturnDO::getCustomerOrderId));

        // 2. 开始拼接
        return BeanUtils.toBean(pageResult, ErpSaleReturnRespVO.class, saleReturn -> {
            saleReturn.setItems(BeanUtils.toBean(saleReturnItemMap.get(saleReturn.getId()), ErpSaleReturnRespVO.Item.class));
            saleReturn.setProductNames(CollUtil.join(saleReturn.getItems(), "，", item ->
                    Optional.ofNullable(item.getProductInfo()).map(ProductInfo::getName).orElse("")));
            MapUtils.findAndThen(customerMap, saleReturn.getCustomerId(), supplier -> saleReturn.setCustomerName(supplier.getName()));
            MapUtils.findAndThen(userMap, Long.parseLong(saleReturn.getCreator()), user -> saleReturn.setCreatorName(user.getNickname()));
            MapUtils.findAndThen(deliveryMap, saleReturn.getDeliveryStaffId(), saleReturn::setDeliveryStaffInfo);
            MapUtils.findAndThen(codeMap, saleReturn.getCustomerOrderId(), saleReturn::setCustomerOrderCode);
        });
    }

}