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.DcBaseStockFba;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.example.DcBaseStockExample;
import com.bailuntec.domain.example.DcBaseStockFbaExample;
import com.bailuntec.domain.pojo.FbaStockData;
import com.bailuntec.domain.pojo.FbaStockInfo;
import com.bailuntec.mapper.DcBaseStockFbaMapper;
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.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;
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);

                                DcBaseStockFba dcBaseStockFba = new DcBaseStockFba();
                                try {
                                    BeanUtils.copyProperties(dcBaseStockFba, fbaStockInfo);
                                } catch (Exception e) {
                                    throw new RuntimeException("BeanUtils.copyPropertiesFBA库存数据失败");
                                }
                                dcBaseStockFba.setGmtModified(LocalDateTime.now());
                                try {
                                    DcBaseStockFbaMapper mapper = SessionUtil.getSession().getMapper(DcBaseStockFbaMapper.class);
                                    int i = mapper.updateByExampleSelective(dcBaseStockFba, DcBaseStockFbaExample.newAndCreateCriteria().andBailunSkuEqualTo(dcBaseStockFba.getBailunSku()).andWarehouseCodeEqualTo(dcBaseStockFba.getWarehouseCode()).example());
                                    if (i == 0) {
                                        mapper.insertSelective(dcBaseStockFba);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    throw new RuntimeException("MYBATIS操作DB存DcBaseStockFba失败", e);
                                } finally {
                                    SessionUtil.closeSession();
                                }
                            }
                        }
                    }
                }else {
                    throw new RuntimeException("调用wms系统FBA库存接口失败");
                }
            }else {
                throw new RuntimeException("调用wms系统FBA库存接口失败");
            }
            jobPointLog.setPageIndex(jobPointLog.getPageIndex() + 1);
        } while (jobPointLog.getPageIndex() <= totalPage);
        jobPointLog.setPageIndex(1);
        try {
            DcBaseStockMapper mapper = SessionUtil.getSession().getMapper(DcBaseStockMapper.class);
            hashmap.forEach(((skuWarehouse, dcBaseStock) -> {
                dcBaseStock.setGmtModified(LocalDateTime.now());
                int i = mapper.updateByExampleSelective(dcBaseStock, DcBaseStockExample.newAndCreateCriteria().andBailunSkuEqualTo(dcBaseStock.getBailunSku()).andWarehouseCodeEqualTo(dcBaseStock.getWarehouseCode()).example());
                if (i == 0) {
                    mapper.insertSelective(dcBaseStock);
                }

            }));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("MYBATIS操作DB失败", e);
        } finally {
            SessionUtil.closeSession();
        }
    }
}
