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.example.DcBaseStockExample;
import com.bailuntec.domain.pojo.*;
import com.bailuntec.mapper.DcBaseStockMapper;
import com.bailuntec.mapper.DcBaseWarehouseMapper;
import com.bailuntec.mapper.JobPointLogMapper;
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 lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

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

    @Override
    public void executeJob(ShardingContext shardingContext, JobPointLog jobPointLog) {
        Data data = new Data();
        Page page = new Page();
        Search search = new Search();
        Root root = new Root();
        data.setPage(page);
        data.setSearch(search);
        root.setData(data);
        page.setRows(jobPointLog.getPageSize());
        search.setWarehouseCodes(listWmsStockWarehouse());
        //不传时间查全表
        search.setLastModificationTime_start(jobPointLog.getStartTime().minusMinutes(5));
        Integer totalPage = 0;
        LocalDateTime now = LocalDateTime.now();
        do {
            OkHttpClient client = OkHttpUtil.getInstance();
            MediaType mediaType = MediaType.parse("application/json");
            page.setPage(jobPointLog.getPageIndex());
            RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(root));
            Request request = new Request.Builder()
                    .url(propertiesUtil.getPropertyAsString("STOCK_WMS_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系统库存接口失败", e);
            } finally {
                if (response != null) {
                    response.close();
                }
            }
            if (StringUtils.isNotBlank(resultStr)) {
                JSONObject jsonObject = JSON.parseObject(resultStr);
                if (jsonObject.get("isSuccess") != null && jsonObject.getBooleanValue("isSuccess")) {
                    WmsStockInfo wmsStockInfo = jsonObject.getObject("data", WmsStockInfo.class);
                    List<WmsStockItem> items = wmsStockInfo.getItems();
                    totalPage = wmsStockInfo.getPageItem().getTotal() % wmsStockInfo.getPageItem().getPageSize() == 0 ? wmsStockInfo.getPageItem().getTotal() / wmsStockInfo.getPageItem().getPageSize() : wmsStockInfo.getPageItem().getTotal() / wmsStockInfo.getPageItem().getPageSize() + 1;
                    if (items != null && items.size() > 0) {
                        try {
                            DcBaseStockMapper mapper = SessionUtil.getSession().getMapper(DcBaseStockMapper.class);
                            items.forEach(wmsStockItem -> {
                                DcBaseStock dcBaseStock = new DcBaseStock();
                                try {
                                    BeanUtils.copyProperties(dcBaseStock, wmsStockItem);
                                    dcBaseStock.setUsableSales(wmsStockItem.getUsableStock());
                                    dcBaseStock.setCreateTime(wmsStockItem.getUpdateTime());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    throw new RuntimeException("WMS库存BeanUtils.copyProperties失败");
                                }
                                int i = mapper.updateByExampleSelective(dcBaseStock, DcBaseStockExample.newAndCreateCriteria().andBailunSkuEqualTo(dcBaseStock.getBailunSku()).andWarehouseCodeEqualTo(dcBaseStock.getWarehouseCode()).example());
                                if (i == 0) {
                                    mapper.insertSelective(dcBaseStock);
                                }
                            });
                            if (jobPointLog.getPageIndex() % 5 == 0) {
                                JobPointLogMapper jobPointLogMapper = SessionUtil.getSession().getMapper(JobPointLogMapper.class);
                                jobPointLogMapper.upsertSelective(jobPointLog);
                            }
                        } catch (Exception e) {
                            throw new RuntimeException("MYBATIS操作DB失败", e);
                        } finally {
                            SessionUtil.closeSession();
                        }
                    }
                } else {
                    throw new RuntimeException("调用wms系统库存接口失败");
                }
            } else {
                throw new RuntimeException("调用wms系统库存接口失败");
            }
            jobPointLog.setPageIndex(jobPointLog.getPageIndex() + 1);
        } while (jobPointLog.getPageIndex() <= totalPage);
        jobPointLog.setPageIndex(1);
        jobPointLog.setStartTime(now);
        jobPointLog.setEndTime(LocalDateTime.now());
    }

    private List<String> listWmsStockWarehouse() {
        List<String> listWmsStockWarehouse = null;
        try {
            DcBaseWarehouseMapper mapper = SessionUtil.getSession().getMapper(DcBaseWarehouseMapper.class);
            listWmsStockWarehouse = mapper.listWmsStockWarehouse();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("MYBATIS操作DB失败", e);
        } finally {
            SessionUtil.closeSession();
        }
        return listWmsStockWarehouse;
    }
}
