package com.youchain.basicdata.service.impl;

import cn.hutool.json.JSONUtil;
import com.youchain.basicdata.domain.*;
import com.youchain.basicdata.repository.*;
import com.youchain.basicdata.service.*;
import com.youchain.businessdata.inputJson.imports.BomAccountImport;
import com.youchain.businessdata.inputJson.imports.ItemImport;
import com.youchain.domain.Log;
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.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class ImportBomAccountServiceImpl implements ImportBomAccountService {
    private final ItemService itemService;
    private final BigItemService bigItemService;
    private final PointService pointService;
    private final ItemRepository itemRepository;
    private final BigItemRepository bigItemRepository;
    private final BomAccountRepository bomAccountRepository;
    private final BomAccountLogService bomAccountLogService;

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

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

        baseImportTemplate(file);
    }

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

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

        baseImportTemplate2(file);
    }

    @Transactional
    public void baseImportTemplate2(MultipartFile file) {
        // 读取sheet数据
        List<BomAccountImport> dataListBi = FastExcelUtil.readExcelData(file, BomAccountImport.class, 0, 1);
        List<BomEntity> dataList=new ArrayList<>();
        for(BomAccountImport bi:dataListBi){
            BomEntity be=new BomEntity();
            be.setPf(bi.getPf());
            be.setNs(bi.getNs());
            be.setPm(bi.getPm());
            be.setGys(bi.getGys());
            be.setAc(bi.getAc());
            be.setJgnr(bi.getJgnr());
            be.setZcfq(bi.getZcfq());
            be.setHw(bi.getHw());
            be.setXz(bi.getXz());
            be.setSrs(Integer.parseInt(bi.getSrs()));
            be.setTckw(bi.getTckw());
            be.setDxw(bi.getDxw());
            be.setSb(bi.getSb());
            be.setJx(bi.getJx());
            be.setJxdm(bi.getJxdm());
            be.setTyl(bi.getTyl());
            be.setKyh(bi.getKyh());
            dataList.add(be);
        }
        //批量导入
        importBomAccountData(dataList);
    }

    // 处理标准模板
    @Transactional
    public void baseImportTemplate(MultipartFile file) {
        // 读取sheet数据
        //13个开始4个一循环


        List<Map<Integer, Object>> list=FastExcelUtil.readExcelData2(file,2);
        log.info("开始导入list:"+list.size());
        List<BomEntity> dataList =new ArrayList<>();

        for (Map<Integer, Object> map: list ) {
            BomEntity bomAccountImport=new BomEntity();
            bomAccountImport.setPf(map.get(0) != null ? map.get(0).toString() : "");
            bomAccountImport.setNs(map.get(1) != null ? map.get(1).toString() : "");
            bomAccountImport.setPm(map.get(2) != null ? map.get(2).toString() : "");
            bomAccountImport.setGys(map.get(3) != null ? map.get(3).toString() : "");
            bomAccountImport.setAc(map.get(4) != null ? map.get(4).toString() : "");
            bomAccountImport.setJgnr(map.get(5) != null ? map.get(5).toString() : "");
            bomAccountImport.setZcfq(map.get(6) != null ? map.get(6).toString() : "");
            bomAccountImport.setHw(map.get(7) != null ? map.get(7).toString() : "");
            bomAccountImport.setXz(map.get(8) != null ? map.get(8).toString() : "");
            bomAccountImport.setSrs(map.get(9) != null ? Integer.parseInt(map.get(9).toString()) : 0);
            bomAccountImport.setTckw(map.get(10) != null ? map.get(10).toString() : "");
            bomAccountImport.setDxw(map.get(11) != null ? map.get(11).toString() : "");
            bomAccountImport.setSb(map.get(12) != null ? map.get(12).toString() : "");
            boolean cgsj=Boolean.TRUE;
//            if(bomAccountImport.getZcfq().equals("制造库位")) {
                for (int ccc=0;ccc<50;ccc++){
                    BomEntity bomAccountImport_new=new BomEntity();
                    int index=ccc*4+12;
                    String tyl=(map.get((index+4)) != null ? map.get((index+4)).toString() : "");
                    if (tyl.length() > 0) {
                        cgsj=Boolean.FALSE;
                        bomAccountImport_new.setJxdm((map.get((index+1)) != null ? map.get((index+1)).toString() : ""));
                        bomAccountImport_new.setJx((map.get((index+2)) != null ? map.get((index+2)).toString() : ""));
                        bomAccountImport_new.setKyh((map.get((index+3)) != null ? map.get((index+3)).toString() : ""));
                        bomAccountImport_new.setTyl(tyl);
                        log.error(bomAccountImport_new.getJx()+"---"+bomAccountImport_new.getTyl()+"---"+bomAccountImport_new.getKyh());

                        bomAccountImport_new.setPf(bomAccountImport.getPf());
                        bomAccountImport_new.setNs(bomAccountImport.getNs());
                        bomAccountImport_new.setPm(bomAccountImport.getPm());
                        bomAccountImport_new.setGys(bomAccountImport.getGys());
                        bomAccountImport_new.setAc(bomAccountImport.getAc());
                        bomAccountImport_new.setJgnr(bomAccountImport.getJgnr());
                        bomAccountImport_new.setZcfq(bomAccountImport.getZcfq());
                        bomAccountImport_new.setHw(bomAccountImport.getHw());
                        bomAccountImport_new.setXz(bomAccountImport.getXz());
                        bomAccountImport_new.setSrs(bomAccountImport.getSrs());
                        bomAccountImport_new.setTckw(bomAccountImport.getTckw());
                        bomAccountImport_new.setDxw(bomAccountImport.getDxw());
                        bomAccountImport_new.setSb(bomAccountImport.getSb());
                        dataList.add(bomAccountImport_new);
                    }
                }
//            }
            if(cgsj){
                bomAccountImport.setJxdm(BaseStatus.DEFAULT_CG_BIG);
                bomAccountImport.setJx(BaseStatus.DEFAULT_CG_BIG);
                bomAccountImport.setTyl("0");
                dataList.add(bomAccountImport);
            }
        }
        log.error(JSONUtil.toJsonStr(dataList));

        Map<String, BomEntity> existBomAccountMap =new HashMap<>();
        for(BomEntity ba:dataList){
            String key=ba.pf+"]"+ba.jxdm+"]"+ba.ns+"]"+ ba.hw+"]"+ba.sb;
//            if(existBomAccountMap.containsKey(key)){
//                log.info(JSONUtil.toJsonStr(ba));
//            }
            existBomAccountMap.put(key,ba);
        }

        dataList = new ArrayList<>(existBomAccountMap.values());
        // List<BomAccountImport> dataList = FastExcelUtil.readExcelData(file, BomAccountImport.class, 0, 1);

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


    /**
     * 处理批量导入
     */
    @Transactional
    public void importBomAccountData(List<BomEntity> bomEntitys) {
        // TODO: 实现批量导入逻辑
//        log.info("处理批量导入，数据条数: {}", dataList.size());
        Map<String,ItemEntity> itemEntitys=new HashMap<>();

        Map<String,BigItemEntity> biEntitys=new HashMap<>();

        for (BomEntity data : bomEntitys) {
            ItemEntity it=new ItemEntity();
            it.setAc(data.getAc());
            it.setPf(data.getPf());
            it.setXz(data.getXz());
            it.setPm(data.getPm());
            it.setSrs(data.getSrs()+"");
            it.setJgnr(data.getJgnr());
            itemEntitys.put(data.getPf(),it);

            BigItemEntity be=new BigItemEntity();
            be.setCode(data.getJxdm());
            be.setName(data.jx);
            biEntitys.put(data.getJxdm(),be);
        }
        //验证品番
        Map<String, Item> existItemMap = validateItem(itemEntitys);
        //获取文件中所有的完成品
//        List<String> bigItemNames = bomEntitys.stream().map(BomEntity::getJx).collect(Collectors.toList());
//        bigItemNames = bigItemNames.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
//        //验证完成品品番
//        Map<String, BigItem> existBigItemMap = validateBigItem(bigItemNames);
        //验证完成品品番
        Map<String, BigItem> existBigItemMap = validateBigItem(biEntitys);
        //获取文件中所有的库位
        List<String> hwCodes = bomEntitys.stream().map(BomEntity::getHw).collect(Collectors.toList());
        hwCodes = hwCodes.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
        //验证库位
        Map<String, Point> existPointMap = validatePoint(hwCodes);
        List<BomAccount> createBomList = new ArrayList<>();//批量新增BomAccount
        List<BomAccount> updateBomList = new ArrayList<>();//批量修改BomAccount
//        Area outArea=areaRepository.getByCode(BaseStatus.DEFAULT_AREA);
        log.info("开始校验");
        int i=0;
        List<BomAccount> bomAccounts=bomAccountRepository.findAll();
        Map<String, BomAccount> existBomAccountMap =new HashMap<>();
        for(BomAccount ba:bomAccounts){
            existBomAccountMap.put(ba.getBigItem().getId()+"]"+ba.getItem().getId()+"]"+ba.getNs()+"]"+ ba.getZPoint().getId()+"]"+ba.getBonded(),ba);
        }
        for (BomEntity entity : bomEntitys) {
//            log.info("开始校验"+i+++"行");
            //品番
            Item item = existItemMap.get(entity.getPf());
            //货位
            Point point=existPointMap.get(entity.getHw());
            //完成品品番
            BigItem bigItem=existBigItemMap.get(entity.getJxdm());
            BomAccount existBom =existBomAccountMap.get(bigItem.getId()+"]"+item.getId()+"]"+entity.ns+"]"+ point.getId()+"]"+entity.sb);
            if(existBom!=null){
                BomAccount ba=this.BaEntity(existBom,entity,bigItem,item,point,Integer.parseInt(entity.tyl),null);
                ba.setId(existBom.getId());
                updateBomList.add(ba);
            }else {
                existBom=new BomAccount();
                BomAccount ba = this.BaEntity(existBom, entity, bigItem,item, point, Integer.parseInt(entity.tyl),null);
                createBomList.add(ba);
            }
      /*      if (isNew) {
               bomAccountService.create(bomAccount);
                bomAccountLogService.copyBomAccount(bomAccount.getId(), "import_add");
           } else {
                bomAccountService.update(bomAccount);
                bomAccountLogService.copyBomAccount(bomAccount.getId(), "import_update");
            }*/
        }
        log.info("校验完成，开始批量保存拉。。。。新增"+createBomList.size()+"修改"+updateBomList.size());
        if(CollectionUtils.isNotEmpty(createBomList)){
            bomAccountRepository.saveAll(createBomList);
        }
        if(CollectionUtils.isNotEmpty(updateBomList)){
            bomAccountRepository.saveAll(updateBomList);
        }
    }

    //验证品番
    private Map<String,Item> validateItem(Map<String,ItemEntity> entitys) {
        List<String> allCodes = entitys.values().stream()
                .map(ItemEntity::getPf)
                .collect(Collectors.toList());
        Map<String, Item> existMap = itemService.queryByItemCodesToMap(allCodes);
        Map<String, Item> totalMap = new HashMap<>();
        //已存在更新，不存在创建
        for(String code:allCodes){
            ItemEntity itemEntity=entitys.get(code);
            Item it=existMap.get(code);
            if(it==null){
                it=new Item();
                it.setDept(UserUtils.getDept());
                it.setCode(code);
                it.setEnabled(Boolean.TRUE);
            }
            it.setName(itemEntity.pm);
            it.setXz(itemEntity.xz);
            it.setSrs(Integer.parseInt(itemEntity.srs));
            it.setExtendD3(Double.parseDouble(itemEntity.srs));
            it.setAc(itemEntity.ac);
            it.setContents(itemEntity.jgnr);
            itemRepository.save(it);
            totalMap.put(it.getCode(),it);
        }
//        Map<String, Item> createMap = new HashMap<>();
//        List<String> existCodes = new ArrayList<>(existMap.keySet());
//        // 获取两个集合的非交集说明品番不存在或失效，直接提示
//        List<String> difference = SmartStringUtil.getDifference(allCodes, existCodes);
//        List<Item> creteItems=new ArrayList<>();
//        for(String pf:difference){
//            ItemEntity it=entitys.get(pf);
//            Item entity=new Item();
//            entity.setCode(pf);
//            entity.setName(it.pm);
//            entity.setExtendD3(Double.parseDouble(it.srs));
//            entity.setDept(UserUtils.getDept());
//            creteItems.add(entity);
//        }
//        if(CollectionUtils.isNotEmpty(creteItems)){
//            List<Item> createEntityList=  itemRepository.saveAll(creteItems);
//            for (Item it:createEntityList){
//                createMap.put(it.getCode(),it);
//            }
//        }
//        if (existMap != null) {
//            totalMap.putAll(existMap);
//        }
//        totalMap.putAll(createMap);
        return  totalMap;
    }

    //验证完成品番
    private Map<String,BigItem> validateBigItem(Map<String,BigItemEntity> entitys) {
        List<String> allCodes = entitys.values().stream()
                .map(BigItemEntity::getCode)
                .collect(Collectors.toList());
        Map<String, BigItem> existMap = bigItemService.queryByBigItemCodesToMap(allCodes);
        Map<String, BigItem> totalMap = new HashMap<>();
        for(String code:allCodes){
            BigItemEntity bigItemEntity=entitys.get(code);
            BigItem bigItem=existMap.get(code);
            if(bigItem==null){
                bigItem=new BigItem();
                bigItem.setCode(code);
                bigItem.setDeptId(UserUtils.getDept().getId());
                bigItem.setEnabled(true);
                bigItem.setDeptId(UserUtils.getDept().getId());
            }
            bigItem.setName(bigItemEntity.getName());//更新名称
            bigItem.setMasterName(bigItemEntity.getName());
            bigItemRepository.save(bigItem);
            totalMap.put(code,bigItem);
        }
        return  totalMap;
    }
    //验证库位
    private Map<String, Point> validatePoint(List<String> codes) {
        Map<String, Point> existMap = pointService.queryByPointCodesToMap(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 void isValidTemplateType(MultipartFile file) {
        List<String> requiredColumns = Arrays.asList(
                "子品番",
                "纳所",
                "品名（多国语）",
                "本国语供应商1（多国语）",
                "A/C",
                "加工内容",
                "制材区分",
                "货位",
                "箱种",
                "收容数",
                "工程(台车库位)",
                "大小物",
                "税别",
                "机型",
                "机型代码",
                "组顺/刻印号前2位",
                "台用量"
        );
        List<String> headers = FastExcelUtil.readHeadContent(file, 0, 0);
        List<String> difference = SmartStringUtil.getDifference(requiredColumns, headers);
        if (!SmartStringUtil.containsAllIgnoreCase(requiredColumns, headers)) {
            throw new BadRequestException(difference+"标准导入模板不正确,请确认模板信息");
        }
    }
    @Data
    public  class ItemEntity{
        private String pf;

        private String pm;

        private String ac;

        private String jgnr;

        private String xz;

        private String srs;
    }

    @Data
    public  class BigItemEntity{
        private String code;
        private String name;
    }

    @Data
    public  class BomEntity{
        private String pf;
        private String ns;
        private String pm;
        private String gys;
        private String ac;
        private String jgnr;
        private String zcfq;
        private String hw;
        private String xz;
        private int srs;
        private String tckw;
        private String dxw;
        private String sb;

        private String jx;
        private String jxdm;
        private String kyh;
        private String tyl;
    }

    public BomAccount BaEntity(BomAccount ba,BomEntity data,BigItem bigItem,Item it,Point point,int dyl,Area outArea){
        ba.setBigItem(bigItem);
        ba.setItem(it);
        ba.setRArea(point.getArea());
        ba.setDept(point.getArea().getDept());
        ba.setZPoint(point);
        ba.setBp_type(data.getDxw());
        ba.setStationType(data.getTckw());
        ba.setCArea(outArea);
        ba.setAc(data.getAc());
        ba.setContents(data.getJgnr());
        ba.setEnabled(true);
        ba.setSingles(dyl);
        ba.setOutType("大");
        ba.setSupplier(data.getGys());
        ba.setBonded(data.getSb());
        ba.setSrs(data.getSrs());
        ba.setXz(data.getXz());
        ba.setNs(data.getNs());
        ba.setDept(UserUtils.getDept());
        ba.setZcfq(data.getZcfq());
        ba.setTckw(data.getTckw());
        ba.setBigItemName(data.getJx());
        ba.setBigItemCode(data.getJxdm());
        ba.setKyQz(data.getKyh());
        return  ba;
    }
}
