package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bailuntec.domain.entity.DcBaseStock;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.pojo.FbaStockData;
import com.bailuntec.domain.pojo.FbaStockInfo;
import com.bailuntec.mapper.DcBaseStockMapper;
import com.bailuntec.support.PointJob;
import com.bailuntec.utils.OkHttpUtil;
import com.bailuntec.utils.PropertiesUtil;
import com.bailuntec.utils.SessionUtil;
import com.dangdang.ddframe.job.api.ShardingContext;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;

public class FbaStockJob extends PointJob {
    private PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("const");

    @Override
    public void executeJob(ShardingContext shardingContext, JobPointLog jobPointLog) {
        Integer totalPage = null;
        HashMap<String, DcBaseStock> hashmap = new HashMap<>();
        do {
            OkHttpClient client = OkHttpUtil.getInstance();
            MediaType mediaType = MediaType.parse("application/json");
            LinkedHashMap<String, Object> map = new LinkedHashMap<>(3);
            map.put("PageIndex", jobPointLog.getPageIndex());
            map.put("PageRow", jobPointLog.getPageSize());
            RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(map));
            Request request = new Request.Builder()
                    .url(propertiesUtil.getPropertyAsString("STOCK_FBA_URL"))
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = null;
            String resultStr = null;
            try {
                response = client.newCall(request).execute();
                resultStr = response.body().string();
            } catch (IOException e) {
                throw new RuntimeException("调用wms系统FBA库存接口失败", e);
            } finally {
                if (response != null) {
                    response.close();
                }
            }
            if (StringUtils.isNotBlank(resultStr)) {
                JSONObject jsonObject = JSON.parseObject(resultStr);
                if (jsonObject.get("isSuccess") != null && jsonObject.getBooleanValue("isSuccess")) {
                    FbaStockData fbaStockData = jsonObject.getObject("data", FbaStockData.class);
                    if (fbaStockData != null && fbaStockData.getStocks() != null && fbaStockData.getStocks().size() > 0) {
                        totalPage = fbaStockData.getPageTotal();
                        for (FbaStockInfo fbaStockInfo : fbaStockData.getStocks()) {
                            if (StringUtils.isNotBlank(fbaStockInfo.getBailunSku())) {
                                DcBaseStock dcBaseStockInMap = hashmap.get(fbaStockInfo.getBailunSku() + fbaStockInfo.getWarehouseCode());
                                DcBaseStock dcBaseStock = new DcBaseStock();
                                dcBaseStock.setBailunSku(fbaStockInfo.getBailunSku());
                                dcBaseStock.setWarehouseCode(fbaStockInfo.getWarehouseCode());
                                dcBaseStock.setInWarehouse(fbaStockInfo.getInWarehouse());
                                dcBaseStock.setUsableStock(fbaStockInfo.getUsableStock());
                                dcBaseStock.setOwnerCode("NONE");
                                if (dcBaseStockInMap != null) {
                                    dcBaseStock.setInWarehouse(dcBaseStockInMap.getInWarehouse() + fbaStockInfo.getInWarehouse());
                                    dcBaseStock.setUsableStock(dcBaseStockInMap.getUsableStock() + fbaStockInfo.getUsableStock());
                                }
                                hashmap.put(dcBaseStock.getBailunSku() + dcBaseStock.getWarehouseCode(), dcBaseStock);
                            }
                        }
                    }
                }else {
                    throw new RuntimeException("调用wms系统FBA库存接口失败");
                }
            }else {
                throw new RuntimeException("调用wms系统FBA库存接口失败");
            }
            jobPointLog.setPageIndex(jobPointLog.getPageIndex() + 1);
        } while (jobPointLog.getPageIndex() <= totalPage);
        if (jobPointLog.getPageIndex() > totalPage) jobPointLog.setPageIndex(1);
        try {
            DcBaseStockMapper mapper = SessionUtil.getSession().getMapper(DcBaseStockMapper.class);
            hashmap.forEach(((skuWarehouse, dcBaseStock) -> {
                mapper.upsertSelective(dcBaseStock);
                SessionUtil.getSession().commit();
            }));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("MYBATIS操作DB失败", e);
        } finally {
            SessionUtil.closeSession();
        }
    }
}
