package com.youchain.basicdata.service.impl;

import com.youchain.basicdata.domain.*;
import com.youchain.basicdata.repository.AreaRepository;
import com.youchain.basicdata.repository.BigItemRepository;
import com.youchain.basicdata.repository.ItemRepository;
import com.youchain.basicdata.repository.ProductionPlanRepository;
import com.youchain.basicdata.service.*;
import com.youchain.businessdata.inputJson.imports.ItemImport;
import com.youchain.businessdata.inputJson.imports.ProductionPlanImport;
import com.youchain.exception.BadRequestException;
import com.youchain.utils.*;
import lombok.Data;
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 ImportProductionPlanServiceImpl implements ImportProductionPlanService {

    private final BigItemRepository bigItemRepository;

    private final ProductionPlanRepository productionPlanRepository;

    private final AreaRepository areaRepository;

    private final ProductionPlanService productionPlanService;

    private final BigItemService bigItemService;

    private final AreaService areaService;



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

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

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

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

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

    /**
     * 处理批量导入
     */
    private void importProductionPlanData(List<ProductionPlanImport> dataList) {
        // TODO: 实现批量导入逻辑
        log.info("处理批量导入，数据条数: {}", dataList.size());
        //获取文件中所有的库位编码
        List<String> bigitemcodes = dataList.stream()
                .map(item -> item.getBigItemCode().replace("-", ""))
                .collect(Collectors.toList());
        bigitemcodes = bigitemcodes.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
        Map<String, BigItem> exitBigItemMap = validateBigItem(bigitemcodes); //校验机型是否存在
        List<String> areaNames = dataList.stream().map(ProductionPlanImport::getZcdx).collect(Collectors.toList());
        areaNames = areaNames.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
        Map<String, Area> exitAreaMap = validateArea(areaNames);//校验库区是否存在
        //得到每个工位最小序号，查找最小序号IDNO是否有已消耗数据，有则异常，没有则删除导入新数据
        HashMap<String,String> maps=new HashMap<>();
        Map<String, Long> map = new HashMap<String, Long>();////职场+工件，序号
        for (ProductionPlanImport data : dataList) {
            String zcdx=data.getZcdx();
            String IDNO=data.getKyh();
//            String makeLine=data.getMakeLine();
            String machineNo=data.getGj();
            if(!maps.containsKey(zcdx+machineNo)){
                Long orderNo = productionPlanRepository.getMaxOrderNo(zcdx,machineNo);
                if (orderNo==null) {
                    map.put(zcdx+machineNo, 1L);
                }else{
                    map.put(zcdx+machineNo, orderNo+1);
                }
                maps.put(zcdx+machineNo,IDNO);
            }
            //如果IDNO为自编码，则不校验直接存储
            if(IDNO.indexOf("-")<0) {
                int hyCount = productionPlanRepository.existsGwHyIdno(IDNO, zcdx, machineNo);
                if (hyCount > 0) {
                    throw new BadRequestException("大于" + IDNO + "存在已耗用数据");
                } else {
                    List<ProductionPlan> productionPlans = productionPlanRepository.findByGwIdnoList(IDNO, zcdx, machineNo);
                    productionPlanRepository.deleteAll(productionPlans);
                }
            }
        }

        for (ProductionPlanImport data : dataList) {
            String zcdx=data.getZcdx();
            String machineNo=data.getGj();
            Area area=exitAreaMap.get(zcdx);
            Long orderNo=map.get(zcdx+machineNo);
            map.put(zcdx+machineNo,orderNo+1);
            BigItem bigItem = exitBigItemMap.get(data.getBigItemCode().replace("-",""));
            ProductionPlan productionPlan = new ProductionPlan();
            productionPlan.setBigItem(bigItem);
//            productionPlan.setType(bigItem.getOutboundType());
            productionPlan.setWorkingStation(zcdx);
            productionPlan.setRkArea(area);
            productionPlan.setDept(UserUtils.getDept());
            productionPlan.setEnabled(true);
            productionPlan.setNo(Integer.valueOf(data.getXh()));
            productionPlan.setMachineNo(data.getGj());
            productionPlan.setMakeLine(data.getMakeLine());
            Date downDate=DateUtil.md_date(data.getHjOut());
            productionPlan.setDownlineDate( new Timestamp(downDate.getTime()));
            productionPlan.setIdno(data.getKyh());
            productionPlan.setImportDate(new Timestamp (new Date ().getTime()));
            productionPlan.setStatue(BizStatus.UN_CONSUME);
            productionPlan.setOrderNo(orderNo);
            productionPlanRepository.save(productionPlan);
        }
    }

    private Map<String, BigItem> validateBigItem(List<String> codes) {
        Map<String, BigItem> existMap = bigItemService.queryByBigItemCodesToMap(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 Map<String, Area> validateArea(List<String> names) {
        Map<String, Area> existMap = areaService.queryByAreaCodesToMap(names);
        if (existMap.isEmpty()) {
            throw new BadRequestException(names+"库区不存在或已失效");
        }
        List<String> existCodes = new ArrayList(existMap.keySet());
        // 获取两个集合的非交集说明品番不存在或失效，直接提示
        List<String> difference = SmartStringUtil.getDifference(names, existCodes);
        if (CollectionUtils.isNotEmpty(difference)) {
            throw new BadRequestException(difference + "库区不存在或已失效");
        }
        return existMap;
    }


    //验证模板是否使用正确
    private void isValidTemplateType(MultipartFile file) {
        // 根据模板类型进行不同的处理
        List<String> requiredColumns = Arrays.asList(
                "ライン№",
                "序号",
                "ID NO.\n" + "/刻印号",
                "机型代码",
                "机型名称",
                "工件",
                "焊接OUT",
                "对象职场"
        );
        List<String> headers = FastExcelUtil.readHeadContent(file, 0, 0);
        if (!SmartStringUtil.containsAllIgnoreCase(requiredColumns, headers)) {
            throw new BadRequestException("标准导入模板不正确,请确认模板信息");
        }
    }
}
