package com.youchain.basicdata.service.impl;

import com.youchain.basicdata.domain.Area;
import com.youchain.basicdata.domain.Item;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.repository.ItemRepository;
import com.youchain.basicdata.repository.PointRepository;
import com.youchain.basicdata.service.*;
import com.youchain.businessdata.inputJson.imports.ItemImport;
import com.youchain.businessdata.inputJson.imports.PointImport;
import com.youchain.exception.BadRequestException;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class ImportItemServiceImpl implements ImportItemService {

    private final ItemRepository itemRepository;

    private final ItemService itemService;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importData(MultipartFile file) {

        // 验证模板类型是否正确
        isValidTemplateType(file);

        // 根据模板类型进行不同的处理
        baseImportTemplate(file);
    }

    // 处理标准模板
    @Transactional
    public void baseImportTemplate(MultipartFile file) {
        // 读取sheet数据
        List<ItemImport> dataList = FastExcelUtil.readExcelData(file, ItemImport.class, 0, 1);

        //批量导入
        importItemData(dataList);
    }

    /**
     * 处理批量导入
     */
    private void importItemData(List<ItemImport> dataList) {
        // TODO: 实现批量导入逻辑
        log.info("处理批量导入，数据条数: {}", dataList.size());

        //获取文件中所有的库位编码
        List<String> itemcodes = dataList.stream().map(ItemImport::getCode).collect(Collectors.toList());
        itemcodes = itemcodes.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
        Map<String, Item> exitPointMap = validateItem(itemcodes);

        for (ItemImport data : dataList) {
            Item item = exitPointMap.get(data.getCode());
            if (item == null) {
                item=new Item();
                item.setCode(data.getCode());
                item.setDept(UserUtils.getDept());
                item.setCreateBy(SecurityUtils.getCurrentUsername());
                item.setCreateTime(new Timestamp(new Date().getTime()));
                item.setEnabled(Boolean.TRUE);
            }
            item.setName(data.getName());
            item.setSrs(data.getSrs());
            item.setAc(data.getAc());
            item.setContents(data.getContents());
            item.setXz(data.getXz());
            item.setExtendD3(data.getSrs()+0d);
            item.setLength(data.getLength());
            item.setWidth(data.getWidth());
            item.setHeight(data.getHeight());
            item.setExtendStr2(data.getExtendStr2());
            itemRepository.save(item);
        }
    }

    //验证库位
    private Map<String, Item> validateItem(List<String> codes) {
        Map<String, Item> existMap = itemService.queryByItemCodesToMap(codes);
        return existMap;
    }


    //验证模板是否使用正确
    private void isValidTemplateType(MultipartFile file) {
        // 根据模板类型进行不同的处理
        List<String> requiredColumns = Arrays.asList(
                "品番",
                "品名",
                 "A/C",
                "加工内容",
                "箱种",
                "收容数",
                "长",
                "宽",
                "高",
                "保管期限"
        );
        List<String> headers = FastExcelUtil.readHeadContent(file, 0, 0);
        if (!SmartStringUtil.containsAllIgnoreCase(requiredColumns, headers)) {
            throw new BadRequestException("标准导入模板不正确,请确认模板信息");
        }
    }
}
