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

import cn.iocoder.foodnexus.framework.common.pojo.ImportResult;
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.controller.admin.sale.vo.customer.ErpCustomerSimpleRespVO;
import cn.iocoder.foodnexus.module.operations.controller.admin.inquirepriceitem.vo.InquirePriceItemExportVO;
import cn.iocoder.foodnexus.module.operations.controller.admin.inquirepriceitem.vo.InquirePriceItemImportVO;
import cn.iocoder.foodnexus.module.operations.controller.admin.inquirepriceitem.vo.InquirePriceItemRespVO;
import cn.iocoder.foodnexus.module.operations.controller.admin.inquirepriceitem.vo.InquirePriceItemSaveReqVO;
import cn.iocoder.foodnexus.module.operations.service.inquirecustomerpush.InquireCustomerPushService;
import cn.iocoder.foodnexus.module.operations.service.inquirepriceitem.InquirePriceItemService;
import cn.iocoder.foodnexus.module.product.service.spu.ProductSpuService;
import cn.iocoder.foodnexus.module.system.controller.admin.user.vo.user.UserImportExcelVO;
import cn.iocoder.foodnexus.module.system.controller.admin.user.vo.user.UserImportRespVO;
import cn.iocoder.foodnexus.module.system.service.user.AdminUserService;
import io.swagger.v3.oas.annotations.Parameters;
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.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.operations.controller.admin.inquireprice.vo.*;
import cn.iocoder.foodnexus.module.operations.dal.dataobject.inquireprice.InquirePriceDO;
import cn.iocoder.foodnexus.module.operations.service.inquireprice.InquirePriceService;
import org.springframework.web.multipart.MultipartFile;

@Tag(name = "管理后台 - 询价管理")
@RestController
@RequestMapping("/operations/inquire-price")
@Validated
public class InquirePriceController {

    @Resource
    private InquirePriceService inquirePriceService;

    @Autowired
    private InquirePriceItemService inquirePriceItemService;

    @Autowired
    private ProductSpuService productService;

    @Autowired
    private InquireCustomerPushService inquireCustomerPushService;

    @Autowired
    private AdminUserService userService;

    @PostMapping("/create")
    @Operation(summary = "创建询价管理")
    @PreAuthorize("@ss.hasPermission('operations:inquire-price:create')")
    public CommonResult<Long> createInquirePrice(@Valid @RequestBody InquirePriceSaveReqVO createReqVO) {
        return success(inquirePriceService.createInquirePrice(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新询价管理")
    @PreAuthorize("@ss.hasPermission('operations:inquire-price:update')")
    public CommonResult<Boolean> updateInquirePrice(@Valid @RequestBody InquirePriceSaveReqVO updateReqVO) {
        inquirePriceService.updateInquirePrice(updateReqVO);
        return success(true);
    }

    @PostMapping("/push")
    @Operation(summary = "推送")
    @PreAuthorize("@ss.hasPermission('operations:inquire-price:update')")
    public CommonResult<Boolean> pushInquirePrice(@Valid @RequestBody InquirePricePushReqVO pushReqVO) {
        inquirePriceService.pushInquirePrice(pushReqVO);
        return success(Boolean.TRUE);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除询价管理")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('operations:inquire-price:delete')")
    public CommonResult<Boolean> deleteInquirePrice(@RequestParam("id") Long id) {
        inquirePriceService.deleteInquirePrice(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除询价管理")
                @PreAuthorize("@ss.hasPermission('operations:inquire-price:delete')")
    public CommonResult<Boolean> deleteInquirePriceList(@RequestParam("ids") List<Long> ids) {
        inquirePriceService.deleteInquirePriceListByIds(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得询价管理")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('operations:inquire-price:query')")
    public CommonResult<InquirePriceRespVO> getInquirePrice(@RequestParam("id") Long id) {
        InquirePriceDO inquirePrice = inquirePriceService.getInquirePrice(id);
        return success(BeanUtils.toBean(inquirePrice, InquirePriceRespVO.class, item -> {
            item.setItems(BeanUtils.toBean(inquirePriceItemService.queryByInquireId(item.getId()), InquirePriceItemRespVO.class, inquireItem -> {
                inquireItem.setProductName(productService.queryName(inquireItem.getProductId()));
            }));
            item.setPushCustomerInfo(inquireCustomerPushService.getSimpCustomer(item.getId()));
        }));
    }

    @GetMapping("/page")
    @Operation(summary = "获得询价管理分页")
    @PreAuthorize("@ss.hasPermission('operations:inquire-price:query')")
    public CommonResult<PageResult<InquirePriceRespVO>> getInquirePricePage(@Valid InquirePricePageReqVO pageReqVO) {
        PageResult<InquirePriceDO> pageResult = inquirePriceService.getInquirePricePage(pageReqVO);
        Map<Long, List<ErpCustomerSimpleRespVO>> customerMap = inquireCustomerPushService.getSimpCustomerMap(CommonUtil.listConvert(pageResult.getList(), InquirePriceDO::getId));
        return success(BeanUtils.toBean(pageResult, InquirePriceRespVO.class, item -> {
            MapUtils.findAndThen(customerMap, item.getId(), item::setPushCustomerInfo);
        }));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出询价管理 Excel")
    @PreAuthorize("@ss.hasPermission('operations:inquire-price:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportInquirePriceExcel(@Valid InquirePricePageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<InquirePriceDO> list = inquirePriceService.getInquirePricePage(pageReqVO).getList();
        // 导出 Excel
        Map<String, String> nameMap = userService.getUserNicknameMap(CommonUtil.listConvertSet(list, item -> Long.parseLong(item.getCreator())));
        ExcelUtils.write(response, "询价管理.xls", "数据", InquirePriceExportVO.class,
                        BeanUtils.toBean(list, InquirePriceExportVO.class, item -> {
                            item.setIsPushStr(CommonUtil.isNotEmpty(item.getIsPush()) && item.getIsPush() ? "已推送" : "未推送");
                            item.setPushCustomerStr(String.join(",", CommonUtil.listConvert(item.getPushCustomerInfo(), ErpCustomerSimpleRespVO::getName)));
                            MapUtils.findAndThen(nameMap, item.getCreator(), item::setCreatorName);
                        }));

    }

    @GetMapping("/export-excel/items")
    @Operation(summary = "导出询价管理items Excel")
    @PreAuthorize("@ss.hasPermission('operations:inquire-price:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportInquirePriceItemsExcel(@RequestParam("id") Long id,
                                        HttpServletResponse response) throws IOException {
        List<InquirePriceItemRespVO> list = BeanUtils.toBean(inquirePriceItemService.queryByInquireId(id), InquirePriceItemRespVO.class, inquireItem -> {
            inquireItem.setProductName(productService.queryName(inquireItem.getProductId()));
        });
        ExcelUtils.write(response, "询价记录表.xls", "数据", InquirePriceItemExportVO.class, BeanUtils.toBean(list ,InquirePriceItemExportVO.class, item -> {
            item.setMarketPriceYuan(MoneyUtils.fenToYuan(item.getMarketPrice()));
        }));
    }


    @PostMapping("/import")
    @Operation(summary = "导入items")
    @Parameters({@Parameter(name = "file", description = "Excel 文件", required = true)})
    public CommonResult<ImportResult<InquirePriceItemSaveReqVO>> importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        List<InquirePriceItemImportVO> list = ExcelUtils.read(file, InquirePriceItemImportVO.class);
        return success(inquirePriceService.importItems(list));
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获得导入items模版")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        List<InquirePriceItemImportVO> list = Collections.singletonList(
                InquirePriceItemImportVO.builder().productName("商品A").categoryName("分类A").productStandard("规格123")
                        .marketPrice("9.99").productUnit("个").build());
        // 输出
        ExcelUtils.write(response, "添加询价记录表.xls", "添加询价记录表", InquirePriceItemImportVO.class, list);
    }
}