package com.youchain.basicdata.service.impl;

import com.youchain.basicdata.domain.Item;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.repository.ItemRepository;
import com.youchain.basicdata.service.ImportCountDetailService;
import com.youchain.basicdata.service.ImportPickDetailService;
import com.youchain.basicdata.service.ItemService;
import com.youchain.basicdata.service.PointService;
import com.youchain.businessdata.domain.*;
import com.youchain.businessdata.inputJson.imports.CountDetailImport;
import com.youchain.businessdata.inputJson.imports.PickDetailImport;
import com.youchain.businessdata.repository.*;
import com.youchain.businessdata.service.*;
import com.youchain.exception.BadRequestException;
import com.youchain.modules.system.domain.Dept;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.http.HttpStatus;
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 ImportCountDetailServiceImpl implements ImportCountDetailService {

    private final ItemRepository itemRepository;

    private final ItemKeyRepository itemKeyRepository;

    private final InventoryRepository inventoryRepository;

    private final CountMoveDetailRepository countMoveDetailRepository;

    private final CountMoveRepository countMoveRepository;

    private final ItemService itemService;

    private final ItemKeyService itemKeyService;

    private final PointService pointService;

    private final CountDetailService countDetailService;

    private final CountMoveService countMoveService;



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

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

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

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

        //批量导入
        importData(moveId,dataList);
    }

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

        CountMove countMove=countMoveRepository.getById(moveId);
        if(countMove==null||!countMove.getStatus().equals(BizStatus.OPEN)){
            throw new BadRequestException("移位单据状态不正确");
        }
        //获取文件中所有的品番编码
        List<String> itemcodes = dataList.stream().map(CountDetailImport::getItemCode).collect(Collectors.toList());
        itemcodes = itemcodes.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
        Map<String, Item> exitItemMap = validateItem(itemcodes);

        //获取文件中所有的库位编码
        List<String> srcPointcodes = dataList.stream().map(CountDetailImport::getSrcPointCode).collect(Collectors.toList());
        srcPointcodes = srcPointcodes.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
        Map<String, Point> exitSrcPointMap = validatePoint(srcPointcodes);

        //获取文件中所有目标的库位编码
        List<String> dstPointcodes = dataList.stream().map(CountDetailImport::getDstPointCode).collect(Collectors.toList());
        dstPointcodes = dstPointcodes.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
        Map<String, Point> exitDstPointMap = validatePoint(dstPointcodes);

        Dept dept=UserUtils.getDept();
        Double orderQty=countMove.getOrderQty();
        int i=1;
        for (CountDetailImport data : dataList) {
            i++;
            String bonded=data.getBonded();
            String pch=data.getPc();
            String stockCode=data.getStockCode();
            if(data.getBonded()==null){
                throw new BadRequestException("税别不能为空");
            }
            Item item = exitItemMap.get(data.getItemCode());
            Point srcPoint=exitSrcPointMap.get(data.getSrcPointCode());
            Point dstPoint=exitDstPointMap.get(data.getDstPointCode());
            List<ItemKey> itemKeyList = new ArrayList<>();
            if(srcPoint.getType().equals(BaseStatus.ZZKW)){
                itemKeyList=itemKeyRepository.getItemKeyNotPc(item.getId(),bonded);
            }else{
                itemKeyList=itemKeyRepository.getItemKeyPc(item.getId(),pch,bonded);
            }
            if (itemKeyList.size() == 0) {
                throw new BadRequestException(i  + "行" + data.getItemCode() + "不存在库存");
            }
            ItemKey ik = itemKeyList.get(0);
            //查找库存
            List<Inventory> inventoryList = new ArrayList<>();
            if(srcPoint.getType().equals(BaseStatus.ZZKW)){
                inventoryList=inventoryRepository.queryInvPdNotXd(srcPoint.getId(),ik.getId(),BaseStatus.ZZKW);
            }else{
                if(stockCode!=null&&!stockCode.equals("")){
                    inventoryList=inventoryRepository.queryInvPdXd(srcPoint.getId(),ik.getId(),BaseStatus.CH,stockCode);
                }else{
                    inventoryList=inventoryRepository.queryInvPdNotXd(srcPoint.getId(),ik.getId(),BaseStatus.CH);
                }
            }
            if (inventoryList.size() == 0) {
                throw new BadRequestException( i  + "行" + data.getItemCode() + "不存在库存");
            }
            Inventory inventory= inventoryList.get(0);
            if(inventory.getQueuedQty()>0){
                throw new BadRequestException(i +  "行" + data.getItemCode() + "有占用，不能移位");
            }
            countMoveService.createCountDetail(countMove,inventory, ik, dstPoint);
        }
    }

    //验证库位
    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 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(
                "品番",
                "源库位",
                "目标库位",
                "批次号",
                "箱单号",
                "税别"
        );
        List<String> headers = FastExcelUtil.readHeadContent(file, 0, 0);
        if (!SmartStringUtil.containsAllIgnoreCase(requiredColumns, headers)) {
            throw new BadRequestException("标准导入模板不正确,请确认模板信息");
        }
    }
}
