package com.uas.platform.b2b.manage.service.impl;

import com.alibaba.fastjson.JSON;
import com.uas.platform.b2b.manage.model.InviteProdInfo;
import com.uas.platform.b2b.manage.service.ProductService;
import com.uas.platform.b2b.manage.support.CollectionUtil;
import com.uas.platform.core.util.serializer.FlexJsonUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

/**
 * 物料访问接口方法
 *
 * @author hejq
 * @date 2018-08-20 15:56
 */
@Service
public class ProductServiceImpl implements ProductService {

    private final RestTemplate restTemplate;

    @Autowired
    public ProductServiceImpl(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 公共物料访问接口
     */
    private static final String PRODUCT_URL = "http://api-product.usoftchina.com/";

    private static final Logger LOGGER = Logger.getLogger(ProductServiceImpl.class);

    /**
     * 通过企业UU号查询企业注册物料信息
     *
     * @param enUUList 企业UU
     * @return List InviteProdInfo
     */
    @Override
    public Map<Long, InviteProdInfo> findByEnUUList(List<Long> enUUList) {
        List<List<Long>> enUULists = CollectionUtil.splitAry(enUUList, CollectionUtil.PRODUCT_MAX_ID_SIZE);
        Map<Long, InviteProdInfo> resultMap = new HashedMap();
        for (List<Long> enUUs : enUULists) {
            Map<String, String> map = new HashedMap();
            map.put("enUUList", FlexJsonUtils.toJsonDeep(enUUs));
            try {
                String str = restTemplate.getForObject(PRODUCT_URL + "product/get/getCountAndTime?enUUList={enUUList}", String.class, map);
                List<InviteProdInfo> infoList = JSON.parseArray(str, InviteProdInfo.class);
                for (InviteProdInfo info : infoList) {
                    resultMap.put(info.getEnUU(), info);
                }
            } catch (RuntimeException e) {
                LOGGER.error("获取数据失败", e);
            }
        }
        return resultMap;
    }
}
