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

import cn.iocoder.foodnexus.framework.apilog.core.annotation.ApiAccessLog;
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.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.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 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 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.math.BigDecimal;
import java.util.List;
import java.util.Map;

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/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()));
        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, item -> this.transform(item, supplierApi.querySettlementFloatingRate(orderPageReqVo.getSupplierId()))));
    }

    @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()));
        orderPageReqVo.setOrderStatusList(CommonUtil.asList(CustomerOrderStatus.SIGN_RECEIPT.getKey(), CustomerOrderStatus.FINISH.getKey(), CustomerOrderStatus.RETURN.getKey()));
        PageResult<ErpPurchaseOrderDO> pageResult = purchaseOrderService.getPurchaseOrderPage(orderPageReqVo);
        purchaseOrderService.reconciliation(pageResult.getList(), orderPageReqVo.getSupplierId());
        return success(Boolean.TRUE);
    }

    private void transform(SupplierMonthOrderDetailsRespVO purchaseOrder, BigDecimal supplierSettlementRate) {
        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(), supplierSettlementRate));

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



    @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, supplierApi.querySupplierIdByUserId(getLoginUserId())).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(supplierApi.querySupplierIdByUserId(getLoginUserId()));
        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, item ->
                this.transform(item, supplierApi.querySettlementFloatingRate(orderPageReqVo.getSupplierId()))).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()));
                }));
    }
}
