package com.fs.kingbos.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.config.FSSysConfig;
import com.fs.common.exception.ServiceException;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.http.HttpUtils;
import com.fs.kingbos.domian.KbStockRequest;
import com.fs.kingbos.domian.KbStockResponse;
import com.fs.kingbos.service.K9StockService;
import com.fs.kingbos.util.SignUtil;
import com.fs.kingbos.util.UrlUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@AllArgsConstructor
public class K9StockServiceImpl implements K9StockService {

    private final FSSysConfig sysConfig;

    /**
     * 查看库存
     * @param request 参数
     * @return  KbStockResponse
     * @throws ServiceException 异常
     */
    @Override
    public KbStockResponse getStock(KbStockRequest request) throws ServiceException {
        // 构造参数
        String timeStep = System.currentTimeMillis() + "";
        if (StringUtils.isBlank(request.getStockCode())) {
            request.setStockCode(sysConfig.getCwarehouseCode());
        }
        String json = JSON.toJSONString(request);
        String sign = SignUtil.sign(json, sysConfig.getKingbosSecret(), sysConfig.getKingbosan(), timeStep);
        String url = sysConfig.getKingbosUrl().replace("do=k9save", "do=k9view");
        url = UrlUtil.getUrl(url, sign, timeStep);

        // 发送请求
        log.info("\n【金博网络】: getStock send request url: {}", url);
        String result = HttpUtils.doPost(url, json);
        log.info("\n【金博网络】: getStock res:{}", result);
        return JSONObject.parseObject(result, KbStockResponse.class);
    }
}
