package com.sf.XWFS.task;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sf.XWFS.domain.OrderDO;
import com.sf.XWFS.service.OrderService;
import com.sf.XWFS.service.YHOrderService;
import com.sf.XWFS.util.CSIMUtil;
import com.sf.erui.util.StringUtil;
import io.jsonwebtoken.lang.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* author:80003756-蔡俊华
* date:2019-5-13
* desc:订单路由定时任务
*/
@Component
public class OrderSendStateTask {
private Logger logger = LoggerFactory.getLogger(OrderSendStateTask.class);
//redis缓存注入
//@Autowired
//private RedisTemplate redisTemplate;
//@Autowired
private OrderService orderService;
private YHOrderService yhOrderService;
/**
* 从丰桥拉取路由状态
* 每隔12小时执行一次
*/
@Scheduled(cron="0 0 0/12 * * ?")
public void pullSendState() {
logger.info("start -----> 开始从丰桥拉取路由状态 ");
orderService = (OrderService)ApplicationContextUtil.getBean("orderServiceImpl");
yhOrderService = (YHOrderService)ApplicationContextUtil.getBean("YHOrderServiceImpl");
long start = System.currentTimeMillis();
int pageSize = 100;//条数
int pageStart = 0;//偏移量
int maxTimes = 50;//最多查询次数 50*100为5000条数据
int queryTimes = 0;
boolean isStop = false;
HashMap<String,Object> param = new HashMap<String,Object>();
try {
//查询50次,一共5000条
param.put("pageSize", pageSize);
param.put("orderBy", "create_tm asc");//排序
param.put("is_cancel", "0");//未作废
param.put("mailnoNotNull","1");//运单号不为空
param.put("send_state_nq","已收件");//未收件
param.put("submit_state","1");//已提交
while( queryTimes ++ <= maxTimes){
param.put("pageStart", pageStart);
try{
List<Map<String, Object>> orderList =orderService.selectOrder(param);
if(Collections.isEmpty(orderList)){
logger.info("第"+queryTimes+"次查询到数据为空");
break;
}
logger.info("第"+queryTimes+"次查询到记录:"+orderList.size());
if(orderList.size()<100){
isStop = true;
}
//获取路由状态
queryState(filter(orderList));
}catch(Exception ex){
isStop = true;
logger.error("", ex);
}
//已经没有需要更新路由的数据
if(isStop){
break;
}
//翻页
pageStart +=pageSize;
}
} catch (Exception ex) {
logger.error("从丰桥拉取路由异常", ex);
} finally {
logger.info("end -----> 从丰桥拉取路由状态结束,耗时:" + (System.currentTimeMillis() - start) + "ms");
}
}
private void queryState(List<Map<String, Object>> orderList){
try{
int start =0;
boolean isStop = false;
String trackingType = "1";//用运单号查询
JSONArray result = new JSONArray();
while(!isStop){
try{
//运单号多个逗号隔开
StringBuilder tracking_number = new StringBuilder();
//每次取十条
for(int i=0;i <10; i++){
if(start >= orderList.size()){
isStop = true;
break;
}
Map<String,Object> order = orderList.get(start ++);
tracking_number.append(order.get("mailno")+",");
}
JSONArray route = CSIMUtil.RouteServiceBySys(trackingType,tracking_number.substring(0,tracking_number.length()-1));
//----
/* JSONObject jsonb = new JSONObject();
jsonb.put("mailno", "873YUADSFH11197773DL0982");
jsonb.put("opcode", "8000");
route.add(jsonb);
JSONObject jsonb2 = new JSONObject();
jsonb2.put("mailno", "873YUADSFH11197773DL098");
jsonb2.put("opcode", "70");
route.add(jsonb2);*/
//--
logger.info("丰桥返回:"+route.toString());
result.addAll(route);
}catch(Exception ex){
logger.error("查询丰桥路由异常",ex );
}
if(result.size()>=30){//30条更新一次数据库
//更新数据状态
updateDatabase(result);
result.clear();
}
}
if(result.size()>0){//更新一次数据库
//更新数据状态
updateDatabase(result);
}
}catch(Exception ex){
logger.error("查询丰桥路由异常",ex );
}
}
/**
* 更新到数据库
* @param route
*/
private void updateDatabase(JSONArray route){
try{
if(route == null ||route.size()==0){
return;
}
Map<String, List<OrderDO>> map = new HashMap<String, List<OrderDO>>() ;
List<OrderDO> list = new ArrayList<OrderDO>();
route.forEach(jsonObj ->{
JSONObject json = (JSONObject)jsonObj;
if(json.get("error") != null){
return;
}
String sendState = "";
String mailno = json.getString("mailno");
String opcode = json.getString("opcode");
switch (opcode) {
case "50":
sendState = "已收件";
break;
case "80":
sendState = "派送成功";
break;
case "8000":
sendState = "派送成功";
break;
case "33":
sendState = "派送失败";
break;
case "70":
sendState = "派送失败";
break;
default:
sendState = "运输中";
break;
}
OrderDO order = new OrderDO();
order.setMailno(mailno);
order.setSendState(sendState);
list.add(order);
});
map.put("list",list);
Integer rest = orderService.batchUpdateRoute(map);
logger.info("成功更新路由到数据库:"+rest);
//更新数据到远航
new Thread(()->updateRoutToYH(list)).start();
}catch(Exception ex){
logger.error("更新路由异常",ex );
}
}
//更新数据到远航
private void updateRoutToYH(List<OrderDO> list){
try{
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sf.format(new Date());
List<Map<String,Object>> param = new ArrayList<Map<String,Object>>();
list.forEach(orderDO -> {
Map<String,Object> map = new HashMap<String,Object>();
map.put("mailno",orderDO.getMailno());
map.put("send_state",orderDO.getSendState());
map.put("hcsj",dateStr);
param.add(map);
});
//推送路由
Integer rest = yhOrderService.updateYHOrderRoute(param);
logger.info("路由推送成功:"+rest);
//更新数据库
Map<String, List<OrderDO>> map = new HashMap<String, List<OrderDO>>();
map.put("list", list);
rest = orderService.batchUpdateBack(map,dateStr);
logger.info("更新回传时间成功:"+rest);
}catch(Exception ex){
logger.error("更新路由到远航异常", ex);
}
}
/**
* 派送失败超过10天不再查询路由
* @param datalist
* @return
*/
public List<Map<String, Object>> filter(List<Map<String, Object>> datalist){
for(Iterator<Map<String,Object>> it = datalist.iterator(); it.hasNext();){
Map<String, Object> map = it.next();
if(map.get("send_state")!=null && map.get("send_state").equals("派送失败")){
if(map.get("first_time_route") == null){
continue;
}
Date first_time_route = (Date)map.get("first_time_route");
Date now = new Date();
long ms = now.getTime()-first_time_route.getTime();
int days = (int) (ms/(1000*60*60*24));
if(days >=10){
it.remove();;
}
}
}
return datalist;
}
}