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().minusHours(1));
        search.setLastModificationTime_end(jobPointLog.getEndTime());
        do {
            OkHttpClient client = OkHttpUtil.getInstance();
            MediaType mediaType = MediaType.parse("application/json");
            page.setPage(jobPointLog.getPageIndex() > 0? jobPointLog.getPageIndex() : 1);
            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();
                    if (jobPointLog.getPageIndex().equals(0)) {
                        int totalPage = wmsStockInfo.getPageItem().getTotal() % jobPointLog.getPageSize() == 0 ? wmsStockInfo.getPageItem().getTotal() / jobPointLog.getPageSize() : wmsStockInfo.getPageItem().getTotal() / jobPointLog.getPageSize() + 1;
                        jobPointLog.setPageIndex(totalPage + 1);
                    }
                    if (items != null && items.size() > 0) {
                        try {
                            DcBaseStockMapper mapper = SessionUtil.getSession().getMapper(DcBaseStockMapper.class);
                            DcBaseStock dcBaseStock = new DcBaseStock();
                            items.forEach(wmsStockItem -> {
                                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() > 0);
        jobPointLog.setPageIndex(0);
        jobPointLog.setStartTime(jobPointLog.getEndTime());
        jobPointLog.setEndTime(jobPointLog.getStartTime().plusDays(jobPointLog.getIntervalTime()).isAfter(LocalDateTime.now()) ? LocalDateTime.now() : jobPointLog.getEndTime().plusDays(jobPointLog.getIntervalTime()));
    }

    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;
    }
}
