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

import cn.iocoder.foodnexus.framework.common.exception.ServiceException;
import cn.iocoder.foodnexus.framework.common.util.CommonUtil;
import cn.iocoder.foodnexus.framework.common.util.collection.MapUtils;
import cn.iocoder.foodnexus.framework.common.util.number.MoneyUtils;
import cn.iocoder.foodnexus.module.erp.api.service.ErpCustomerApi;
import cn.iocoder.foodnexus.module.order.api.CustomerOrderApi;
import cn.iocoder.foodnexus.module.order.controller.admin.customerorderitem.vo.CustomerOrderItemExcelVO;
import cn.iocoder.foodnexus.module.order.controller.admin.customerorderitem.vo.CustomerOrderItemRespVO;
import cn.iocoder.foodnexus.module.order.dal.dataobject.customerorderitem.CustomerOrderItemDO;
import cn.iocoder.foodnexus.module.order.service.customerorderitem.CustomerOrderItemService;
import cn.iocoder.foodnexus.module.order.service.customerorderrecord.CustomerOrderRecordService;
import cn.iocoder.foodnexus.module.system.service.dept.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import jakarta.validation.*;
import jakarta.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference;

import cn.iocoder.foodnexus.framework.common.pojo.PageParam;
import cn.iocoder.foodnexus.framework.common.pojo.PageResult;
import cn.iocoder.foodnexus.framework.common.pojo.CommonResult;
import cn.iocoder.foodnexus.framework.common.util.object.BeanUtils;

import static cn.iocoder.foodnexus.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.foodnexus.framework.common.pojo.CommonResult.success;

import cn.iocoder.foodnexus.framework.excel.core.util.ExcelUtils;

import cn.iocoder.foodnexus.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.foodnexus.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.foodnexus.module.order.controller.admin.customerorder.vo.*;
import cn.iocoder.foodnexus.module.order.dal.dataobject.customerorder.CustomerOrderDO;
import cn.iocoder.foodnexus.module.order.service.customerorder.CustomerOrderService;

@Tag(name = "管理后台 - 客户总订单")
@RestController
@RequestMapping("/order/customer-order")
@Validated
public class CustomerOrderController {

    @Resource
    private CustomerOrderService customerOrderService;

    @Resource
    private CustomerOrderItemService customerOrderItemService;

    @Autowired
    private CustomerOrderApi customerOrderApi;

    @Autowired
    private CustomerOrderRecordService customerOrderRecordService;

    @Autowired
    @Lazy
    private ErpCustomerApi customerApi;

    @Autowired
    private DeptService deptService;


/*    @DeleteMapping("/delete")
    @Operation(summary = "删除客户总订单")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('order:customer-order:delete')")
    public CommonResult<Boolean> deleteCustomerOrder(@RequestParam("id") Long id) {
        customerOrderService.deleteCustomerOrder(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除客户总订单")
                @PreAuthorize("@ss.hasPermission('order:customer-order:delete')")
    public CommonResult<Boolean> deleteCustomerOrderList(@RequestParam("ids") List<Long> ids) {
        customerOrderService.deleteCustomerOrderListByIds(ids);
        return success(true);
    }
*/

    @GetMapping("/get")
    @Operation(summary = "获得客户总订单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('order:customer-order:query')")
    public CommonResult<CustomerOrderDetailsVO> getCustomerOrder(@RequestParam("id") Long id) {
        CustomerOrderDO customerOrder = customerOrderService.getCustomerOrder(id);
        return success(BeanUtils.toBean(customerOrder, CustomerOrderDetailsVO.class, item -> {
            item.setOrderItems(
                    BeanUtils.toBean(customerOrderApi.queryItemsByOrderId(item.getId()), CustomerOrderItemRespVO.class));
            item.setCustomerName(customerApi.queryNameStrById(item.getCustomerId()));
            item.setCustomerDeptName(deptService.queryNameById(item.getCustomerDeptId()));
        }));
    }

    @GetMapping("/page")
    @Operation(summary = "获得客户总订单分页")
    @PreAuthorize("@ss.hasPermission('order:customer-order:query')")
    public CommonResult<PageResult<CustomerOrderRespVO>> getCustomerOrderPage(@Valid CustomerOrderPageReqVO pageReqVO) {
        PageResult<CustomerOrderDO> pageResult = customerOrderService.getCustomerOrderPage(pageReqVO);
        Map<Long, String> nameMap = customerApi.queryNameMapByIds(CommonUtil.listConvertSet(pageResult.getList(), CustomerOrderDO::getCustomerId));
        Map<Long, String> deptNameMap =  deptService.queryNameMapByIds(CommonUtil.listConvertSet(pageResult.getList(), CustomerOrderDO::getCustomerDeptId), Boolean.TRUE);
        return success(BeanUtils.toBean(pageResult, CustomerOrderRespVO.class, item -> {
                    MapUtils.findAndThen(nameMap, item.getCustomerId(), item::setCustomerName);
                    MapUtils.findAndThen(deptNameMap, item.getCustomerDeptId(), item::setCustomerDeptName);
                }));
    }

    @GetMapping("/record")
    @Operation(summary = "订单进度")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<List<CustomerOrderRecordMapVO>> queryRecord(@RequestParam("id") Long id) {
        return success(customerOrderRecordService.queryRecordMap(id));
    }

    @GetMapping("/item/export-excel")
    @Operation(summary = "导出客户中订单子项目 Excel")
    @PreAuthorize("@ss.hasPermission('order:customer-order:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportCustomerOrderItemExcel(@Valid CustomerOrderPageReqVO pageReqVO,
                                             HttpServletResponse response) throws IOException {
        if (CommonUtil.isEmpty(pageReqVO.getCreateYearMonth())) {
            throw exception("月份信息不能为空");
        }
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<CustomerOrderDO> list = customerOrderService.getCustomerOrderPage(pageReqVO).getList();
        if (CommonUtil.isEmpty(list)) {
            return ;
        }
        List<CustomerOrderItemExcelVO> itemExcelList = new ArrayList<>();
        AtomicReference<Integer> allSignedTotal = new AtomicReference<>(0);
        AtomicReference<Integer> allReturnsTotal = new AtomicReference<>(0);
        AtomicReference<Integer> allOrderItemTotal = new AtomicReference<>(0);
        for (CustomerOrderDO order : list) {
            List<CustomerOrderItemDO> customerOrderItems = customerOrderItemService.queryByOrderId(order.getId());
            if (CommonUtil.isEmpty(customerOrderItems)) {
                continue;
            }
            AtomicReference<Integer> signedTotal = new AtomicReference<>(0);
            AtomicReference<Integer> returnsTotal = new AtomicReference<>(0);
            AtomicReference<Integer> orderItemTotal = new AtomicReference<>(0);
            List<CustomerOrderItemExcelVO> excelList = BeanUtils.toBean(customerOrderItems, CustomerOrderItemExcelVO.class, item -> {
                item.setOrderCode(order.getCode());
                item.setCreateDate(item.getCreateTime().toLocalDate());
                item.setIntroduction(item.getProductInfo().getIntroduction());
                item.setUnitName(item.getProductInfo().getUnitName());

                signedTotal.updateAndGet(v -> v + item.getSignedTotal());
                returnsTotal.updateAndGet(v -> v + item.getReturnsTotal());
                orderItemTotal.updateAndGet(v -> v + item.getOrderItemTotal());

                allSignedTotal.updateAndGet(v -> v + item.getSignedTotal());
                allReturnsTotal.updateAndGet(v -> v + item.getReturnsTotal());
                allOrderItemTotal.updateAndGet(v -> v + item.getOrderItemTotal());
            });
            itemExcelList.addAll(excelList);

            CustomerOrderItemExcelVO totalItem = new CustomerOrderItemExcelVO();
            totalItem.setSignedTotal(signedTotal.get());
            totalItem.setReturnsTotal(returnsTotal.get());
            totalItem.setOrderItemTotal(orderItemTotal.get());

            itemExcelList.add(totalItem);
        }
        if (CommonUtil.isNotEmpty(itemExcelList)) {
            // 处理金额
            // 计算汇总

            for (CustomerOrderItemExcelVO item : itemExcelList) {
                item.setSignedTotalYuan(MoneyUtils.fenToYuan(item.getSignedTotal()));
                item.setReturnsTotalYuan(MoneyUtils.fenToYuan(item.getReturnsTotal()));
                item.setOrderItemPriceYuan(MoneyUtils.fenToYuan(item.getOrderItemPrice()));
                item.setOrderItemTotalYuan(MoneyUtils.fenToYuan(item.getOrderItemTotal()));
            }
            CustomerOrderItemExcelVO totalItem = new CustomerOrderItemExcelVO();
            totalItem.setSignedTotal(allSignedTotal.get());
            totalItem.setReturnsTotal(allReturnsTotal.get());
            totalItem.setOrderItemTotal(allOrderItemTotal.get());
            totalItem.setSignedTotalYuan(MoneyUtils.fenToYuan(allSignedTotal.get()));
            totalItem.setReturnsTotalYuan(MoneyUtils.fenToYuan(allReturnsTotal.get()));
            totalItem.setOrderItemTotalYuan(MoneyUtils.fenToYuan(allOrderItemTotal.get()));
            itemExcelList.add(totalItem);
        }
        ExcelUtils.write(response, pageReqVO.getCreateYearMonth() + "客户对账.xls", pageReqVO.getCreateYearMonth() + "汇总表", CustomerOrderItemExcelVO.class, itemExcelList);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出客户总订单 Excel")
    @PreAuthorize("@ss.hasPermission('order:customer-order:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportCustomerOrderExcel(@Valid CustomerOrderPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<CustomerOrderDO> list = customerOrderService.getCustomerOrderPage(pageReqVO).getList();
        Map<Long, String> nameMap = customerApi.queryNameMapByIds(CommonUtil.listConvertSet(list, CustomerOrderDO::getCustomerId));
        Map<Long, String> deptNameMap =  deptService.queryNameMapByIds(CommonUtil.listConvertSet(list, CustomerOrderDO::getCustomerDeptId));
        // 导出 Excel
        ExcelUtils.write(response, "客户总订单.xls", "数据", CustomerOrderExportVO.class,
                        BeanUtils.toBean(list, CustomerOrderExportVO.class, item -> {
                            MapUtils.findAndThen(nameMap, item.getCustomerId(), item::setCustomerName);
                            MapUtils.findAndThen(deptNameMap, item.getCustomerDeptId(), item::setCustomerDeptName);
                            if (CommonUtil.isNotEmpty(item.getWarehouseInfo())) {
                                item.setWarehouseStr(item.getWarehouseInfo().getName());
                            }
                            if (CommonUtil.isNotEmpty(item.getAddressInfo())) {
                                item.setAddressStr(
                                        String.format("%s%s%s%s",
                                                item.getAddressInfo().getProvinceName(),
                                                item.getAddressInfo().getCityName(),
                                                item.getAddressInfo().getRegionName(),
                                                item.getAddressInfo().getAddress()));
                                item.setContactUser(item.getAddressInfo().getContactUser());
                                item.setContactPhone(item.getAddressInfo().getContactPhone());
                            }
                            item.setOrderAmountYuan(MoneyUtils.fenToYuan(item.getOrderAmount()));
                            item.setActualAmountYuan(MoneyUtils.fenToYuan(item.getActualAmount()));
                        }));
    }

}