package com.jwipc.order.api.logic.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jwipc.api.constant.RestCode;
import com.jwipc.api.dto.ApiResult;
import com.jwipc.order.api.convert.PurchaseOrderBomApiConvert;
import com.jwipc.order.api.dto.PurchaseOrderBomApiDTO;
import com.jwipc.order.api.dto.PurchaseOrderBomItemDTO;
import com.jwipc.order.api.logic.PurchaseOrderBomApiLogic;
import com.jwipc.order.entity.PurchaseOrderBom;
import com.jwipc.order.service.IPurchaseOrderBomService;
import com.jwipc.sys.client.FactoryClient;
import com.jwipc.sys.client.ProductClient;
import com.jwipc.sys.client.dto.FactoryDTO;
import com.jwipc.sys.client.dto.ProductInfoDTO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static com.baomidou.dynamic.datasource.support.DdConstants.SLAVE;

@Service
@RequiredArgsConstructor
@DS(SLAVE)
public class PurchaseOrderBomApiLogicImpl implements PurchaseOrderBomApiLogic {

    private final IPurchaseOrderBomService purchaseOrderBomService;
    private final PurchaseOrderBomApiConvert purchaseOrderBomApiConvert;
    private final FactoryClient factoryClient;
    private final ProductClient productClient;
    /**
     * 物料保存或更新
     *
     * @param param 接口参数
     * @return 结果
     */
    @Override
    @Transactional
    public ApiResult saveOrUpdate(PurchaseOrderBomItemDTO param) {
        List<PurchaseOrderBomApiDTO> purchaseOrderBomApiDTOS =
                param.getPurchaseOrderBomApiDTOS();
        if (CollectionUtil.isNotEmpty(purchaseOrderBomApiDTOS)) {
            //工厂
            final List<FactoryDTO> all = factoryClient.getAll();
            final Map<String, FactoryDTO> factoryCache = all.stream()
                    .collect(Collectors.toMap(FactoryDTO::getFactory, a -> a));
            final Set<String> factoryCodes = factoryCache.keySet();
            for (PurchaseOrderBomApiDTO purchaseOrderBomApiDTO : purchaseOrderBomApiDTOS) {
                if (StringUtils.isEmpty(purchaseOrderBomApiDTO.getFactoryCode())) {
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("请传入工厂").build();
                }
                if (!factoryCodes.contains(purchaseOrderBomApiDTO.getFactoryCode())) {
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message(StrUtil.format("工厂：{}在系统中不存在", purchaseOrderBomApiDTO.getFactoryCode())).build();
                }
                PurchaseOrderBom purchaseOrderBom = purchaseOrderBomApiConvert.purchaseOrderBomApiDTO2Entity(purchaseOrderBomApiDTO);
                //这里因为分片算法，无法批量保存更新，且更新必须带上分片键
                ProductInfoDTO productInfoDTO = productClient.getByMaterialCodeAndFactoryCode(purchaseOrderBom.getMaterialCode(), purchaseOrderBom.getFactoryCode());
                if (Objects.isNull(productInfoDTO)) {
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message(StrUtil.format("套件物料编码：{},工厂：{},在系统中不存在",purchaseOrderBom.getMaterialCode(), purchaseOrderBomApiDTO.getFactoryCode())).build();
                }
                purchaseOrderBom.setMaterialName(productInfoDTO.getMaterialName());
                ProductInfoDTO productInfoDTOComponent = productClient.getByMaterialCodeAndFactoryCode(purchaseOrderBom.getComponentCode(), purchaseOrderBom.getFactoryCode());

                if (Objects.isNull(productInfoDTOComponent)) {
                    return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message(StrUtil.format("子件物料编码：{},工厂：{},在系统中不存在",purchaseOrderBom.getComponentCode(), purchaseOrderBomApiDTO.getFactoryCode())).build();
                }
                purchaseOrderBom.setComponentName(productInfoDTOComponent.getMaterialName());

                PurchaseOrderBom getOneData = purchaseOrderBomService.getOne(new LambdaQueryWrapper<PurchaseOrderBom>()
                        .eq(PurchaseOrderBom::getMaterialCode, purchaseOrderBom.getMaterialCode())
                        .eq(PurchaseOrderBom::getComponentCode, purchaseOrderBom.getComponentCode())
                        .eq(PurchaseOrderBom::getFactoryCode, purchaseOrderBom.getFactoryCode())
                );
                if (Objects.isNull(getOneData)) {
                    purchaseOrderBom.setCreateTime(LocalDateTime.now());
                    purchaseOrderBomService.save(purchaseOrderBom);
                } else {
                    purchaseOrderBom.setId(getOneData.getId());
                    purchaseOrderBom.setCreateTime(getOneData.getCreateTime());
                    purchaseOrderBom.setUpdateTime(LocalDateTime.now());
                    purchaseOrderBomService.updateById(purchaseOrderBom);
                }
            }

        }
        return ApiResult.builder().code(RestCode.SAP_SUCCESS.getCode()).message("").build();
    }
}
