package cn.iocoder.foodnexus.module.order.controller.admin.supplier;

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.number.MoneyUtils;
import cn.iocoder.foodnexus.framework.common.util.number.NumberUtils;
import cn.iocoder.foodnexus.framework.common.util.object.BeanUtils;
import cn.iocoder.foodnexus.framework.excel.core.util.ExcelUtils;
import cn.iocoder.foodnexus.module.erp.api.enums.ErpDeliveryStatus;
import cn.iocoder.foodnexus.module.erp.api.service.ErpSupplierApi;
import cn.iocoder.foodnexus.module.erp.controller.admin.purchase.vo.order.*;
import cn.iocoder.foodnexus.module.erp.dal.dataobject.purchase.ErpPurchaseOrderDO;
import cn.iocoder.foodnexus.module.erp.service.purchase.ErpPurchaseOrderService;
import cn.iocoder.foodnexus.module.order.controller.admin.customerorder.vo.CustomerOrderReconExportRespVO;
import cn.iocoder.foodnexus.module.order.controller.admin.customerorder.vo.CustomerOrderReconPageRespVO;
import cn.iocoder.foodnexus.module.order.dal.dataobject.customerorder.CustomerOrderDO;
import cn.iocoder.foodnexus.module.order.dal.dataobject.customerorderitem.CustomerOrderItemDO;
import cn.iocoder.foodnexus.module.order.enums.CustomerOrderStatus;
import cn.iocoder.foodnexus.module.order.service.customerorder.CustomerOrderService;
import cn.iocoder.foodnexus.module.order.service.customerorderitem.CustomerOrderItemService;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

import static cn.iocoder.foodnexus.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.foodnexus.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.foodnexus.framework.common.pojo.CommonResult.success;
import static cn.iocoder.foodnexus.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * @author : yanghao
 * create at:  2025/10/16  14:25
 * @description: 管理后台 - 供应商 - 对账
 */
@Tag(name = "管理后台 - 供应商 - 对账")
@RestController
@RequestMapping("/operation/reconciliation")
@Validated
public class OperaSupplierPurchaseOrderController {

    @Resource
    private ErpPurchaseOrderService purchaseOrderService;

    @Autowired
    private CustomerOrderItemService customerOrderItemService;

    @Autowired
    private CustomerOrderService customerOrderService;

    @Autowired
    private ErpSupplierApi supplierApi;

    @GetMapping("/page-month")
    @Operation(summary = "分页获取月度账单")
    public CommonResult<PageResult<SupplierMonthOrderRespVO>> pageMonth(SupplierMonthOrderPageReqVO pageReqVO) {
        return success(purchaseOrderService.pageMonth(pageReqVO, null));
    }

    @GetMapping("/page-by-month")
    @Operation(summary = "月度账单明细")
    public CommonResult<PageResult<SupplierMonthOrderDetailsRespVO>> listByMonth(SupplierMonthOrderPageReqVO pageReqVO) {
        if (CommonUtil.isEmpty(pageReqVO.getMonth())) {
            throw exception("月份不能为空");
        }
        ErpPurchaseOrderPageReqVO orderPageReqVo = new ErpPurchaseOrderPageReqVO();
        orderPageReqVo.setPageSize(pageReqVO.getPageSize());
        orderPageReqVo.setPageNo(pageReqVO.getPageNo());
        orderPageReqVo.setSupplierId(pageReqVO.getSupplierId());
        orderPageReqVo.setSupplierName(pageReqVO.getSupplierName());
        orderPageReqVo.setCreateMonth(pageReqVO.getMonth());
        orderPageReqVo.setDeliveryStatusList(CommonUtil.asList(ErpDeliveryStatus.ARRIVAL.getStatus(), ErpDeliveryStatus.RECONCILIATION.getStatus()));
        orderPageReqVo.setOrderStatusList(CommonUtil.asList(CustomerOrderStatus.SIGN_RECEIPT.getKey(), CustomerOrderStatus.FINISH.getKey(), CustomerOrderStatus.RETURN.getKey()));
        PageResult<ErpPurchaseOrderDO> pageResult = purchaseOrderService.getPurchaseOrderPage(orderPageReqVo);
        return success(BeanUtils.toBean(pageResult, SupplierMonthOrderDetailsRespVO.class, this::transform));
    }

    @GetMapping("/page-month/export-excel")
    @Operation(summary = "导出月度账单 Excel")
    @ApiAccessLog(operateType = EXPORT)
    public void pageMonthExportExcel(SupplierMonthOrderPageReqVO pageReqVO,
                            HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<SupplierMonthOrderRespVO> list = purchaseOrderService.pageMonth(pageReqVO, null).getList();
        // 导出 Excel
        ExcelUtils.write(response, "月度账单.xls", "数据", SupplierMonthOrderExportVO.class,
                BeanUtils.toBean(list, SupplierMonthOrderExportVO.class, item -> {
                    item.setOrderPriceYuan(MoneyUtils.fenToYuan(item.getOrderPrice()));
                    item.setPayablePriceYuan(MoneyUtils.fenToYuan(item.getPayablePrice()));
                    item.setSettlementPriceYuan(MoneyUtils.fenToYuan(item.getSettlementPrice()));
                    item.setStatusStr(CommonUtil.isNotEmpty(item.getStatus()) && item.getStatus() ? "已对账" : "未对账");
                }));
    }

    @GetMapping("/page-by-month/export-excel")
    @Operation(summary = "导出月度账单明细 Excel")
    @ApiAccessLog(operateType = EXPORT)
    public void pageByMonthExportExcel(SupplierMonthOrderPageReqVO pageReqVO,
                            HttpServletResponse response) throws IOException {
        if (CommonUtil.isEmpty(pageReqVO.getMonth())) {
            throw exception("月份不能为空");
        }
        ErpPurchaseOrderPageReqVO orderPageReqVo = new ErpPurchaseOrderPageReqVO();
        orderPageReqVo.setPageSize(pageReqVO.getPageSize());
        orderPageReqVo.setPageNo(pageReqVO.getPageNo());
        orderPageReqVo.setSupplierId(pageReqVO.getSupplierId());
        orderPageReqVo.setSupplierName(pageReqVO.getSupplierName());
        orderPageReqVo.setCreateMonth(pageReqVO.getMonth());
        orderPageReqVo.setDeliveryStatusList(CommonUtil.asList(ErpDeliveryStatus.ARRIVAL.getStatus(), ErpDeliveryStatus.RECONCILIATION.getStatus()));
        orderPageReqVo.setOrderStatusList(CommonUtil.asList(CustomerOrderStatus.SIGN_RECEIPT.getKey(), CustomerOrderStatus.FINISH.getKey(), CustomerOrderStatus.RETURN.getKey()));
        PageResult<ErpPurchaseOrderDO> pageResult = purchaseOrderService.getPurchaseOrderPage(orderPageReqVo);
        List<SupplierMonthOrderDetailsRespVO> list = BeanUtils.toBean(pageResult, SupplierMonthOrderDetailsRespVO.class, this::transform).getList();
        // 导出 Excel
        ExcelUtils.write(response, "月度账单明细.xls", "数据", SupplierMonthOrderDetailsExportVO.class,
                BeanUtils.toBean(list, SupplierMonthOrderDetailsExportVO.class, item -> {
                    item.setDeliveryModeStr(CommonUtil.isNotEmpty(item.getDeliveryMode()) ? item.getDeliveryMode().getLabel() : "");
                    item.setPayablePriceYuan(MoneyUtils.fenToYuan(item.getPayablePrice()));
                    item.setSignedTotalYuan(MoneyUtils.fenToYuan(item.getSignedTotal()));
                    item.setReturnsTotalYuan(MoneyUtils.fenToYuan(item.getReturnsTotal()));
                    item.setSettlementPriceYuan(MoneyUtils.fenToYuan(item.getSettlementPrice()));
                }));
    }

    private void transform(SupplierMonthOrderDetailsRespVO purchaseOrder) {
        CustomerOrderDO customerOrder = customerOrderService.getCustomerOrder(purchaseOrder.getCustomerOrderId());
        List<CustomerOrderItemDO> customerOrderItemDOS = customerOrderItemService.queryByOrderId(purchaseOrder.getCustomerOrderId(), purchaseOrder.getSupplierId());
        purchaseOrder.setDeliveryMode(customerOrder.getDeliveryMode());
        purchaseOrder.setPlanDeliveryStartTime(customerOrder.getPlanDeliveryStartTime());
        purchaseOrder.setPlanDeliveryEndTime(customerOrder.getPlanDeliveryEndTime());
        purchaseOrder.setSignedTotal(customerOrderItemDOS.stream().mapToInt(CustomerOrderItemDO::getSignedTotal).sum());
        purchaseOrder.setReturnsTotal(customerOrderItemDOS.stream().mapToInt(CustomerOrderItemDO::getReturnsTotal).sum());
        purchaseOrder.setPayablePrice(CommonUtil.getEls(purchaseOrder.getSignedTotal(), 0) - CommonUtil.getEls(purchaseOrder.getReturnsTotal(), 0));
        purchaseOrder.setSettlementPrice(NumberUtils.calculateFloatingPrice(purchaseOrder.getPayablePrice(), supplierApi.querySettlementFloatingRate(purchaseOrder.getSupplierId())));

        purchaseOrder.setSupplierName(customerOrderItemDOS.get(0).getSupplierName());
        StringBuilder productNames = new StringBuilder();
        for (CustomerOrderItemDO item : customerOrderItemDOS) {
            productNames.append(item.getProductName()).append("(").append(item.getOrderItemQuantity()).append(")\n");
        }
        purchaseOrder.setProductNames(productNames.toString());
    }

}
