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

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.CommonUtil;
import cn.iocoder.foodnexus.framework.common.util.object.BeanUtils;
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.dal.dataobject.customerorder.CustomerOrderDO;
import cn.iocoder.foodnexus.module.order.dal.dataobject.customerorderitem.CustomerOrderItemDO;
import cn.iocoder.foodnexus.module.order.service.customerorder.CustomerOrderService;
import cn.iocoder.foodnexus.module.order.service.customerorderitem.CustomerOrderItemService;
import cn.iocoder.foodnexus.module.system.annotations.AppSystemAuth;
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 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.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/11  10:28
 * @description: 供应商 - 对账
 */
@Tag(name = "供应商 - 对账")
@RestController
@RequestMapping("/supplier/reconciliation")
@Validated
@AppSystemAuth(UserSystemEnum.SUPPLIER)
public class SupplierPurchaseOrderController {

    @Resource
    private ErpPurchaseOrderService purchaseOrderService;

    @Autowired
    private ErpSupplierApi supplierApi;

    @Autowired
    private CustomerOrderItemService customerOrderItemService;

    @Autowired
    private CustomerOrderService customerOrderService;

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

    @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(supplierApi.querySupplierIdByUserId(getLoginUserId()));
        orderPageReqVo.setCreateMonth(pageReqVO.getMonth());
        orderPageReqVo.setDeliveryStatusList(CommonUtil.asList(ErpDeliveryStatus.ARRIVAL.getStatus(), ErpDeliveryStatus.RECONCILIATION.getStatus()));
        PageResult<ErpPurchaseOrderDO> pageResult = purchaseOrderService.getPurchaseOrderPage(orderPageReqVo);
        return success(BeanUtils.toBean(pageResult, SupplierMonthOrderDetailsRespVO.class, this::transform));
    }

    @PostMapping("reconciliation")
    @Operation(summary = "确认对账")
    @Parameter(name = "month", description = "月份（yyyy-MM）", required = true)
    public CommonResult<Boolean> reconciliation(@RequestParam("month") String month) {
        ErpPurchaseOrderPageReqVO orderPageReqVo = new ErpPurchaseOrderPageReqVO();
        orderPageReqVo.setPageSize(-1);
        orderPageReqVo.setPageNo(1);
        orderPageReqVo.setSupplierId(supplierApi.querySupplierIdByUserId(getLoginUserId()));
        orderPageReqVo.setCreateMonth(month);
        orderPageReqVo.setDeliveryStatusList(CommonUtil.asList(ErpDeliveryStatus.ARRIVAL.getStatus(), ErpDeliveryStatus.RECONCILIATION.getStatus()));
        PageResult<ErpPurchaseOrderDO> pageResult = purchaseOrderService.getPurchaseOrderPage(orderPageReqVo);
        purchaseOrderService.reconciliation(pageResult.getList(), orderPageReqVo.getSupplierId());
        return success(Boolean.TRUE);
    }

    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());
        // TODO 待定
        // purchaseOrder.setPayablePrice();
        purchaseOrder.setSignedTotal(customerOrderItemDOS.stream().mapToInt(CustomerOrderItemDO::getSignedTotal).sum());
        purchaseOrder.setReturnsTotal(customerOrderItemDOS.stream().mapToInt(CustomerOrderItemDO::getReturnsTotal).sum());

        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());
    }
}
