package com.zhyc.module.dairyProducts.service.impl;

import com.zhyc.common.annotation.DataScope;
import com.zhyc.common.utils.SecurityUtils;
import com.zhyc.module.dairyProducts.domain.NpMilkInOutStore;
import com.zhyc.module.dairyProducts.mapper.NpMilkInOutStoreMapper;
import com.zhyc.module.dairyProducts.service.INpMilkInOutStoreService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

@Service
public class NpMilkInOutStoreServiceImpl implements INpMilkInOutStoreService {

    @Autowired
    private NpMilkInOutStoreMapper mapper;

    @Override
    @DataScope(deptAlias = "s", userAlias = "s") // 启用数据权限注解
    public List<Map<String, Object>> selectWithDynamicColumns(NpMilkInOutStore query) {
        List<String> feed = mapper.selectFeedSources();
        List<String> sale = mapper.selectSaleDestinations();
        // 将实体对象传递给 Mapper
        return mapper.selectWithColumns(query, feed, sale);
    }

    @Override
    public List<Map<String, Object>> getAllColumnOptions() {
        Map<String,Object> m = new HashMap<>();
        m.put("feed", mapper.selectFeedSources());
        m.put("sale", mapper.selectSaleDestinations());
        return Collections.singletonList(m);
    }

    @Override
    public List<Map<String, Object>> parseImportExcel(MultipartFile file) throws Exception {
        // 用 Apache POI 解析 Excel 第一行标题，动态映射列名跟 unit cells
        InputStream in = file.getInputStream();
        Workbook wb = WorkbookFactory.create(in);
        Sheet sheet = wb.getSheetAt(0);
        Row header = sheet.getRow(0);
        int cols = header.getLastCellNum();
        List<String> titles = new ArrayList<>();
        for (int i = 0; i < cols; i++) titles.add(header.getCell(i).getStringCellValue());
        List<Map<String,Object>> rows = new ArrayList<>();
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null) continue;
            Map<String,Object> map = new LinkedHashMap<>();
            for (int c = 0; c < cols; c++) {
                Cell cell = row.getCell(c);
                map.put(titles.get(c), cell == null ? null : cell.toString());
            }
            rows.add(map);
        }
        return rows;
    }

    @Override
    public void batchInsertFromRows(List<Map<String, Object>> rows) throws Exception {
        Long userId = SecurityUtils.getUserId();
        Long deptId = SecurityUtils.getDeptId();

        for (Map<String,Object> row : rows) {
            // 提取主表字段
            NpMilkInOutStore store = new NpMilkInOutStore();
            // 这里假设 Excel 中的"日期"格式是标准的 yyyy-MM-dd，如果格式不对可能会报错，建议加 try-catch 或格式化处理
            store.setDatetime(java.sql.Date.valueOf(row.get("日期").toString()));
            store.setNum(Integer.valueOf(row.get("羊数").toString()));

            // 手动填充其它主表字段，这里省略了具体的 get 调用，请根据您的 Excel 列名自行补充
            // store.setColostSheep(...);

            store.setUserId(userId);
            store.setDeptId(deptId);

            mapper.insertStore(store);
            Integer sid = store.getId();

            // 其余列为动态饲喂或销售，根据字典决定分类：
            for (Map.Entry<String,Object> ent: row.entrySet()) {
                String col = ent.getKey();
                // 跳过固定列
                if (col.equals("日期") || col.equals("羊数") || col.equals("id")) continue;
                if (ent.getValue() == null || "".equals(ent.getValue().toString())) continue;

                BigDecimal amt = new BigDecimal(ent.getValue().toString());

                if (mapper.selectFeedSources().contains(col)) {
                    mapper.insertFeedRecord(sid, col, amt, userId, deptId);
                } else if (mapper.selectSaleDestinations().contains(col)) {
                    mapper.insertSaleRecord(sid, col, amt, userId, deptId);
                }
            }
        }
    }
}