package cn.iocoder.foodnexus.module.operations.controller.admin.inquiresupplierpush;

import cn.iocoder.foodnexus.framework.common.enums.UserSystemEnum;
import cn.iocoder.foodnexus.framework.common.util.CommonUtil;
import cn.iocoder.foodnexus.framework.common.util.collection.MapUtils;
import cn.iocoder.foodnexus.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.foodnexus.module.erp.api.service.ErpSupplierApi;
import cn.iocoder.foodnexus.module.erp.dal.dataobject.purchase.ErpSupplierDO;
import cn.iocoder.foodnexus.module.erp.service.purchase.ErpSupplierService;
import cn.iocoder.foodnexus.module.operations.controller.admin.inquirepriceitem.vo.InquirePriceItemRespVO;
import cn.iocoder.foodnexus.module.operations.controller.admin.inquiresupplierpush.vo.AppInquireSupplierPushConfirmReqVO;
import cn.iocoder.foodnexus.module.operations.controller.admin.inquiresupplierpush.vo.AppInquireSupplierPushDetailsRespVO;
import cn.iocoder.foodnexus.module.operations.controller.admin.inquiresupplierpush.vo.AppInquireSupplierPushPageReqVO;
import cn.iocoder.foodnexus.module.operations.controller.admin.inquiresupplierpush.vo.AppInquireSupplierPushRespVO;
import cn.iocoder.foodnexus.module.operations.dal.dataobject.inquirepriceitem.InquirePriceItemDO;
import cn.iocoder.foodnexus.module.operations.service.inquirepriceitem.InquirePriceItemService;
import cn.iocoder.foodnexus.module.product.controller.admin.spu.vo.ProductSpuRespVO;
import cn.iocoder.foodnexus.module.product.dal.dataobject.spu.ProductSpuDO;
import cn.iocoder.foodnexus.module.product.service.spu.ProductSpuService;
import cn.iocoder.foodnexus.module.system.annotations.AppSystemAuth;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
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 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.operations.controller.admin.inquiresupplierpush.vo.*;
import cn.iocoder.foodnexus.module.operations.dal.dataobject.inquiresupplierpush.InquireSupplierPushDO;
import cn.iocoder.foodnexus.module.operations.service.inquiresupplierpush.InquireSupplierPushService;

@Tag(name = "供应商端 - 询价推送")
@RestController
@RequestMapping("/operations/inquire-supplier-push")
@Validated
public class InquireSupplierPushController {

    @Resource
    private InquireSupplierPushService inquireSupplierPushService;

    @Autowired
    private ErpSupplierApi supplierApi;

    @Autowired
    private ProductSpuService productSpuService;

    @Autowired
    private InquirePriceItemService inquirePriceItemService;

    @Autowired
    private ErpSupplierService supplierService;


    @PostMapping("/confirm")
    @Operation(summary = "确认询价")
    @AppSystemAuth(UserSystemEnum.SUPPLIER)
    public CommonResult<Boolean> updateInquireSupplierPush(@Valid @RequestBody AppInquireSupplierPushConfirmReqVO updateReqVO) {
        updateReqVO.setSupplierId(supplierApi.querySupplierIdByUserId(SecurityFrameworkUtils.getLoginUserId()));
        inquireSupplierPushService.confirm(updateReqVO);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得询价推送")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('operations:inquire-supplier-push:query')")
    public CommonResult<InquireSupplierPushRespVO> getInquireSupplierPush(@RequestParam("id") Long id) {
        InquireSupplierPushDO inquireSupplierPush = inquireSupplierPushService.getInquireSupplierPush(id);
        Map<Long, String> nameMap = supplierApi.queryNameMapByIds(CommonUtil.asList(inquireSupplierPush.getSupplierId()));
        return success(BeanUtils.toBean(inquireSupplierPush, InquireSupplierPushRespVO.class, item ->
                MapUtils.findAndThen(nameMap, item.getSupplierId(), item::setSupplierName)));
    }

    @GetMapping("/query-supplier-list")
    @Operation(summary = "根据询价获取推送供应商")
    @Parameter(name = "inquirePriceId", description = "询价inquirePriceId", required = true, example = "1024")
    public CommonResult<List<ErpSupplierDO>> querySupplierList(@RequestParam("inquirePriceId") Long inquirePriceId) {
        List<InquireSupplierPushDO> inquireSupplierPushDOS = inquireSupplierPushService.queryByInquireId(inquirePriceId);
        if (CommonUtil.isEmpty(inquireSupplierPushDOS)) {
            return success(Lists.newArrayList());
        }
        return success(supplierService.getSupplierList(CommonUtil.listConvert(inquireSupplierPushDOS, InquireSupplierPushDO::getSupplierId)));
    }

    @GetMapping("/page")
    @Operation(summary = "获得询价推送分页")
    @PreAuthorize("@ss.hasPermission('operations:inquire-supplier-push:query')")
    public CommonResult<PageResult<InquireSupplierPushRespVO>> getInquireSupplierPushPage(@Valid InquireSupplierPushPageReqVO pageReqVO) {
        PageResult<InquireSupplierPushDO> pageResult = inquireSupplierPushService.getInquireSupplierPushPage(pageReqVO);
        Map<Long, String> nameMap = supplierApi.queryNameMapByIds(pageResult.getList().stream().map(InquireSupplierPushDO::getSupplierId).toList());
        Map<Long, ProductSpuDO> spuMap = productSpuService.getSpuMap(pageResult.getList().stream().map(InquireSupplierPushDO::getProductId).toList());
        Map<Long, InquirePriceItemDO> itemMap = inquirePriceItemService.queryMap(pageResult.getList().stream().map(InquireSupplierPushDO::getInquirePriceItemId).toList());
        return success(BeanUtils.toBean(pageResult, InquireSupplierPushRespVO.class, item ->{
                    MapUtils.findAndThen(nameMap, item.getSupplierId(), item::setSupplierName);
                    MapUtils.findAndThen(itemMap, item.getInquirePriceItemId(), priceItem ->
                            item.setInquirePriceItem(BeanUtils.toBean(priceItem, InquirePriceItemRespVO.class)));
                    MapUtils.findAndThen(spuMap, item.getProductId(), productSpu ->
                            item.setProductSpu(BeanUtils.toBean(productSpu, ProductSpuRespVO.class)));
        }));
    }

    @GetMapping("/inquirePrice/get")
    @Operation(summary = "inquirePrice获得询价推送")
    @Parameter(name = "id", description = "询价主题id", required = true, example = "1024")
    @AppSystemAuth(UserSystemEnum.SUPPLIER)
    public CommonResult<AppInquireSupplierPushDetailsRespVO> getInquireSupplierPushDetails(@RequestParam("id") Long id) {
        AppInquireSupplierPushPageReqVO pageReqVO = new AppInquireSupplierPushPageReqVO();
        pageReqVO.setInquirePriceId(id);
        pageReqVO.setSupplierId(supplierApi.querySupplierIdByUserId(SecurityFrameworkUtils.getLoginUserId()));
        PageResult<AppInquireSupplierPushRespVO> result = inquireSupplierPushService.getAppInquireSupplierPushPage(pageReqVO);
        if (CommonUtil.isNotEmpty(result) && CommonUtil.isNotEmpty(result.getList())) {
            AppInquireSupplierPushRespVO inquirePrice = result.getList().get(0);
            return success(BeanUtils.toBean(inquirePrice, AppInquireSupplierPushDetailsRespVO.class, item -> {
                item.setSupplierItems(inquirePriceItemService.queryListWithSupplierQuote(item.getId(), pageReqVO.getSupplierId()));
            }));
        }
        return success(new AppInquireSupplierPushDetailsRespVO());
    }

    @GetMapping("/inquirePrice/page")
    @Operation(summary = "inquirePrice获得询价推送分页")
    @AppSystemAuth(UserSystemEnum.SUPPLIER)
    public CommonResult<PageResult<AppInquireSupplierPushRespVO>> getInquireSupplierPushPage(@Valid AppInquireSupplierPushPageReqVO pageReqVO) {
        pageReqVO.setSupplierId(supplierApi.querySupplierIdByUserId(SecurityFrameworkUtils.getLoginUserId()));
        return success(inquireSupplierPushService.getAppInquireSupplierPushPage(pageReqVO));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出询价推送 Excel")
    @PreAuthorize("@ss.hasPermission('operations:inquire-supplier-push:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportInquireSupplierPushExcel(@Valid InquireSupplierPushPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<InquireSupplierPushDO> list = inquireSupplierPushService.getInquireSupplierPushPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "询价推送.xls", "数据", InquireSupplierPushRespVO.class,
                        BeanUtils.toBean(list, InquireSupplierPushRespVO.class));
    }

}