package com.youchain.basicdata.service.impl;

import com.youchain.basicdata.domain.Item;
import com.youchain.basicdata.repository.ItemRepository;
import com.youchain.basicdata.service.ImportXppPlanService;
import com.youchain.basicdata.service.ItemService;
import com.youchain.businessdata.domain.XppPlan;
import com.youchain.businessdata.inputJson.imports.XppPlanImport;
import com.youchain.businessdata.repository.XppPlanRepository;
import com.youchain.businessdata.service.XppPlanService;
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 ImportXppPlanServiceImpl implements ImportXppPlanService {

    private final XppPlanRepository xppPlanRepository;

    private final ItemRepository itemRepository;

    private final ItemService itemService;

    private final XppPlanService xppPlanService;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importData(MultipartFile file) {
        // 根据模板类型进行不同的处理
        List<String> requiredColumns = Arrays.asList(
                "项目名",
                "工厂",
                "品番",
                "定单编号",
                "分支号",
                "受入受領ＮＯ",
                "创建日期",
                "端末ＮＯ",
                "検収受入数",
                "早遅日"
        );
        // 验证模板类型是否正确
        isValidTemplateType(file,requiredColumns);

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

    // 处理标准模板
    @Transactional
    public void baseImportTemplate(MultipartFile file) {
        // 读取sheet数据,从第三行开始读取
        List<XppPlanImport> dataList = FastExcelUtil.readExcelData(file, XppPlanImport.class, 0, 3);
        //批量导入
        importPointData(dataList);
    }

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

        //获取文件中所有的库位编码
//        List<String> itemcodes = dataList.stream().map(XppPlanImport::getPf).collect(Collectors.toList());
        List<String> itemcodes = dataList.stream()
                .map(XppPlanImport::getPf)
                .filter(Objects::nonNull)
                .map(pf -> pf.length() >= 10 ? pf.substring(0, 10) : pf)
                .collect(Collectors.toList());
        itemcodes = itemcodes.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
        Map<String, Item> exitItemMap = validateItem(itemcodes);
        for (XppPlanImport data : dataList) {
            String pf=data.getPf().length() >= 10 ? data.getPf().substring(0, 10) : data.getPf();
            Item item = exitItemMap.get(pf);
            Timestamp cjrq = Timestamp.valueOf(data.getCjrq());
            Timestamp gxrq = Timestamp.valueOf(data.getGxrq());
            XppPlan xppPlan=new XppPlan();
            xppPlan.setItem(item);
            xppPlan.setItemCode(pf);
            xppPlan.setRelaCode(data.getXmm());
            xppPlan.setAreaCode(data.getGc());
            xppPlan.setDdbh(data.getDdbh());
            xppPlan.setFzh(data.getFzh());
            xppPlan.setZf(data.getSrsl());
            xppPlan.setNrDate(gxrq);
            xppPlan.setCjDate(cjrq);
            xppPlan.setCjr(data.getDmno());
            xppPlan.setNrs(Integer.parseInt(data.getSrs()));
            xppPlan.setShQuantity(data.getZcr());
            xppPlanRepository.save(xppPlan);
        }
    }
    //验证品番
    private Map<String, Item> validateItem(List<String> codes) {
        Map<String, Item> existMap = itemService.queryByItemCodesToMap(codes);
        if (existMap.isEmpty()) {
            throw new BadRequestException("品番不存在或已失效");
        }
        List<String> existCodes = new ArrayList(existMap.keySet());
        // 获取两个集合的非交集说明品番不存在或失效，直接提示
//        List<String> difference = SmartStringUtil.getDifference(codes, existCodes);
//        if (CollectionUtils.isNotEmpty(difference)) {
//            throw new BadRequestException(difference + "品番不存在或已失效");
//        }
        return existMap;
    }


    //验证模板是否使用正确
    private List<String> isValidTemplateType(MultipartFile file,List<String> requiredColumns) {
        List<String> headers = FastExcelUtil.readHeadContent(file, 0, 2);
        if (!SmartStringUtil.containsAllIgnoreCase(requiredColumns, headers)) {
            throw new BadRequestException("标准导入模板不正确,请确认模板信息");
        }
        return headers;
    }


}
