package com.ruoyi.web.controller.inventory;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.entity.Materials;
import com.ruoyi.common.utils.uuid.UUID;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.inventory.domain.InboundOrderItems;
import com.ruoyi.inventory.domain.vo.InboundMaterialTotalVO;
import com.ruoyi.inventory.domain.vo.InboundTemplateVO;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.inventory.domain.InboundOrders;
import com.ruoyi.inventory.service.IInboundOrdersService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 入库单主Controller
 * 
 * @author ruoyi
 * @date 2025-12-02
 */
@RestController
@RequestMapping("/inventory/inbound")
public class InboundOrdersController extends BaseController
{
    @Autowired
    private IInboundOrdersService inboundOrdersService;

    /**
     * 查询入库单主列表
     */
    @PreAuthorize("@ss.hasPermi('inventory:inbound:list')")
    @GetMapping("/list")
    public TableDataInfo list(InboundOrders inboundOrders)
    {
        startPage();
        List<InboundOrders> list = inboundOrdersService.selectInboundOrdersList(inboundOrders);
        return getDataTable(list);
    }

    /**
     * 导出入库单主列表
     */
    @PreAuthorize("@ss.hasPermi('inventory:inbound:export')")
    @Log(title = "入库单主", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InboundOrders inboundOrders)
    {
        List<InboundOrders> list = inboundOrdersService.selectInboundOrdersList(inboundOrders);
        ExcelUtil<InboundOrders> util = new ExcelUtil<InboundOrders>(InboundOrders.class);
        util.exportExcel(response, list, "入库单主数据");
    }

    /**
     * 获取入库单主详细信息
     */
    @PreAuthorize("@ss.hasPermi('inventory:inbound:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(inboundOrdersService.selectInboundOrdersById(id));
    }

    /**
     * 新增入库单主
     */
    @PreAuthorize("@ss.hasPermi('inventory:inbound:add')")
    @Log(title = "入库单主", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody InboundOrders inboundOrders)
    {
        inboundOrders.setId(UUID.randomUUID().toString());
        return toAjax(inboundOrdersService.insertInboundOrders(inboundOrders));
    }

    /**
     * 修改入库单
     */
    @PreAuthorize("@ss.hasPermi('inventory:inbound:edit')")
    @Log(title = "入库单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody InboundOrders inboundOrders)
    {
        return toAjax(inboundOrdersService.updateInboundOrders(inboundOrders));
    }

    /**
     * 删除入库单
     */
    @PreAuthorize("@ss.hasPermi('inventory:inbound:remove')")
    @Log(title = "入库单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(inboundOrdersService.deleteInboundOrdersByIds(ids));
    }

    /**
     * 下载入库单导入模板
     */
    @PreAuthorize("@ss.hasPermi('inventory:inbound:importTemplate')")
    @Log(title = "入库导入模板", businessType = BusinessType.IMPORT)
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<InboundTemplateVO> util = new ExcelUtil<InboundTemplateVO>(InboundTemplateVO.class);
        util.importTemplateExcel(response, "入库单及入库物料明细信息");
    }

    /**
     * 导入入库单物料明细
     */
    @PreAuthorize("@ss.hasPermi('inventory:inbound:import')")
    @Log(title = "入库信息导入", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult importTemplate(@RequestParam("file") MultipartFile file,
                                     // 接收 true/false
                                     @RequestParam("updateSupport") Integer updateSupport,
                                     @RequestParam(value = "orderType", required = false) Integer orderType) throws Exception
    {
        // 防护1：校验文件非空
        if (file == null || file.isEmpty()) {
            return error("导入文件不能为空！");
        }
        // 防护2：校验文件格式
        String fileName = file.getOriginalFilename();
        if (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls")) {
            return error("仅支持Excel格式文件（.xlsx/.xls）！");
        }
        // 第二步：校验Excel列名是否匹配模板（核心！拦截非模板数据）
        List<String> templateColumns = Arrays.asList(
                "入库日期",
                "SAP No",
                "物料名称",
                "TS Code",
                "货主",
                "批号",
                "计划数量",
                "单号",
                "系统编号",
                "件重",
                "约数",
                "实际件数",
                "实发数量",
                "仓库",
                "库位",
                "标签颜色",
                "凭证号",
                "单价",
                "备注",
                "订单类型",
                "收货人",
                "物料备注"
        );
        List<String> excelColumns = ExcelUtil.getExcelHeader(file.getInputStream()); // 自定义方法读取表头
        if (CollectionUtils.isEmpty(excelColumns) || !excelColumns.containsAll(templateColumns)) {
            return AjaxResult.error("导入文件不是标准模板！请下载官方模板后填写（缺失列："
                    + getMissingColumns(templateColumns, excelColumns) + "）");
        }
        ExcelUtil<InboundTemplateVO> util = new ExcelUtil<InboundTemplateVO>(InboundTemplateVO.class);
        List<InboundTemplateVO> inboundOrders = util.importExcel(file.getInputStream());

        // 防护3：拦截空列表，避免 Service 层处理空数据
        if (CollectionUtils.isEmpty(inboundOrders)) {
            return error("Excel中未解析到有效数据，请检查模板是否正确！");
        }

        String operName = getUsername();
        String message = inboundOrdersService.importInboundOrders(inboundOrders, updateSupport, operName, orderType);
        return success(message);
    }
    // 辅助方法：获取缺失的列名
    private String getMissingColumns(List<String> template, List<String> excel) {
        return template.stream()
                .filter(col -> !excel.contains(col))
                .collect(Collectors.joining("、"));
    }

    /**
     * 首页入库次数统计api
     *
     */
    @GetMapping("/inboundCount")
    public AjaxResult inboundCount(){
        int count = inboundOrdersService.countInboundOrders();
        return AjaxResult.success(count);
    }

    /**
     * 按数量统计本月入库物料Top前10
     * @return 结果
     */
    @GetMapping("/countQuantity")
    public AjaxResult countQuantity(){
        List<InboundMaterialTotalVO> list = inboundOrdersService.countInboundMaterialQuantity();
        return AjaxResult.success(list);
    }
    /**
     * 按金额统计本月入库物料Top前10
     * @return 结果
     */
    @GetMapping("/countMoney")
    public AjaxResult countMoney(){
        List<InboundMaterialTotalVO> list = inboundOrdersService.countInboundMaterialMoney();
        return AjaxResult.success(list);
    }
}
