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

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.CustomerOrderItemRespVO;
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.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.constraints.*;
import jakarta.validation.*;
import jakarta.servlet.http.*;
import java.util.*;
import java.io.IOException;

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.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;

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

}