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.ImportAsnDetailService;
import com.youchain.basicdata.service.ImportItemService;
import com.youchain.basicdata.service.ItemService;
import com.youchain.basicdata.service.PointService;
import com.youchain.businessdata.domain.Asn;
import com.youchain.businessdata.domain.AsnDetail;
import com.youchain.businessdata.inputJson.imports.AsnDetailImport;
import com.youchain.businessdata.inputJson.imports.ItemImport;
import com.youchain.businessdata.inputJson.imports.PointImport;
import com.youchain.businessdata.repository.AsnDetailRepository;
import com.youchain.businessdata.repository.AsnRepository;
import com.youchain.businessdata.service.AsnDetailService;
import com.youchain.businessdata.service.AsnService;
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.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 ImportAsnDetailServiceImpl implements ImportAsnDetailService {

    private final ItemRepository itemRepository;

    private final AsnRepository asnRepository;

    private final AsnDetailRepository asnDetailRepository;

    private final ItemService itemService;

    private final PointService pointService;

    private final AsnService asnService;

    private final AsnDetailService asnDetailService;



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

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

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

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

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

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

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

        //获取文件中所有的库位编码
        List<String> pointcodes = dataList.stream().map(AsnDetailImport::getPointCode).collect(Collectors.toList());
        pointcodes = pointcodes.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
        Map<String, Point> exitPointMap = validatePoint(pointcodes);
        Dept dept=UserUtils.getDept();
        Double asnQty=asn.getOrderQuantity();
        for (AsnDetailImport data : dataList) {
            Item item = exitItemMap.get(data.getItemCode());
            Point point=exitPointMap.get(data.getPointCode());
            AsnDetail asnDetail=new AsnDetail();
            asnDetail.setAsn(asn);
            asnDetail.setItem(item);
            asnDetail.setPoint(point);
            asnDetail.setOrderQty(data.getQty()+0d);
            asnDetail.setPropC2(data.getBonded());
            asnDetail.setStatus(BizStatus.OPEN);
            asnDetail.setRemark(data.getRemark());
            asnDetail.setDept(dept);
            asnDetailRepository.save(asnDetail);
            asnQty+=asnDetail.getOrderQty();
        }
        asn.setOrderQuantity(asnQty);
        asnRepository.save(asn);
    }

    //验证库位
    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("标准导入模板不正确,请确认模板信息");
        }
    }
}
