package com.reptileclient.jlifeapp.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.reptileclient.jlifeapp.constant.JlifeConstant;
import com.reptileclient.jlifeapp.dao.hm.HmBookTradeOrderMapper;
import com.reptileclient.jlifeapp.dao.hm.HmTokenMapper;
import com.reptileclient.jlifeapp.dto.HmBookTradeOrderDTO;
import com.reptileclient.jlifeapp.entity.hm.HmBookTradeOrder;
import com.reptileclient.jlifeapp.entity.hm.HmToken;
import com.reptileclient.jlifeapp.entity.hm.ServerOrder;
import com.reptileclient.jlifeapp.filter.Filter;
import com.reptileclient.jlifeapp.service.*;
import com.reptileclient.jlifeapp.util.HttpUtil;
import com.reptileclient.jlifeapp.util.JsonUtil;
import com.reptileclient.jlifeapp.util.OkHttpUtil;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static com.reptileclient.jlifeapp.constant.HemaConstant.*;

/**
 * @author fuxubing
 */
@Service
public class HmBookTradeOrderServiceImpl implements HmBookTradeOrderService {
    private static final Logger logger = LoggerFactory.getLogger(HmBookTradeOrderServiceImpl.class);
    @Resource
    private HmBookTradeOrderMapper hmBookTradeOrderMapper;
    @Resource
    private Filter filter;
    @Resource
    private HmTokenMapper hmTokenMapper;
    @Resource
    private HmDownHistoryService hmDownHistoryService;
    @Resource
    private RetryService retryService;

    @Autowired
    private HmRequestService hmRequestService;


    @Autowired
    private HmPhoneDecryptService phoneDecryptService;


//    盒马	
//    1	待履约
//    6	待上门
//    2	服务已提供
//    9	服务已完成
//    4	已取消

    /**
     * 取数范围：前2天到下个月
     *
     * @return
     */
    @Override
    public int addHmBookTradeList() throws InterruptedException {
        HmToken hmToken = hmTokenMapper.selectAll();
        String token = hmToken.getToken();
        //20221012从当前时间 改为取上月开始
        //2020206 从上月开始修改为前2天
        String date = DateUtil.formatDate(DateUtil.offsetDay(new DateTime(), -2));
        String end = DateUtil.formatDate(DateUtil.nextMonth());
        //hmBookTradeOrderMapper.deleteByBetWeenTime(date,end);

        int rowCount = 0;
        int totalPage = -1;
        int pageIndex = JlifeConstant.PAGE_INDEX;
        int pageSize = 5000;//JlifeConstant.PAGE_SIZE;

        do {
            //随机等待几秒
            int waitTime = new Random().nextInt(10);
            Thread.sleep((long) waitTime * 1000);

            HmBookTradeOrderDTO hmBookTradeOrderDTO = new HmBookTradeOrderDTO();
            hmBookTradeOrderDTO.setPageSize(pageSize);
            hmBookTradeOrderDTO.setPageIndex(pageIndex);
            hmBookTradeOrderDTO.setStatus(new Integer[]{0, 1, 6});  //0待接单 1待上门 6待履约
            hmBookTradeOrderDTO.setBeginTime(date);
            hmBookTradeOrderDTO.setEndTime(end); //20240206 取当前时间后一个月 by leo

            String jsonString = JSONObject.toJSONString(hmBookTradeOrderDTO);
            //JSONObject jsonObject = HttpUtil.requestPost(token, jsonString, JlifeConstant.BOOK_TRADE_URL);

            try {

                Map<String, Object> request = retryService.requestPost(token, jsonString, JlifeConstant.BOOK_TRADE_URL);

                if ("true".equals(request.get("success").toString())) {
                    JSONObject data = (JSONObject) JSON.toJSON(request.get("data"));
                    double total = Double.parseDouble(String.valueOf(data.get("total")));
                    totalPage = (int) total / pageSize;
                    logger.info("totalPage:{}", totalPage);
                    JSONArray items = data.getJSONArray("list");
                    if (CollectionUtils.isEmpty(items)) {
                        logger.info("数据为空了。。。。。" + JsonUtil.getJson(request));
                        return 0;
                    }

                    String filter = this.filter.filter(items.toJSONString());
                    //String aliases = EmojiParser.parseToAliases(items.toJSONString());
                    List<HmBookTradeOrder> hmBookTradeOrders = JSONObject.parseArray(filter, HmBookTradeOrder.class);
                    List<HmBookTradeOrder> bookTradeNoList = new ArrayList<>();
                    for (HmBookTradeOrder tradeOrder : hmBookTradeOrders) {
                        HmBookTradeOrder _tradeOrder = hmBookTradeOrderMapper.selectByBookTradeNo(tradeOrder.getBookTradeNo());
                        if (_tradeOrder != null) {
                            _tradeOrder.setStatus(tradeOrder.getStatus());
                            _tradeOrder.setServantPhone(tradeOrder.getServantPhone());
                            _tradeOrder.setServantName(tradeOrder.getServantName());
                            hmBookTradeOrderMapper.updateByPrimaryKey(_tradeOrder);
                        } else {
                            bookTradeNoList.add(tradeOrder);
                        }
                    }

                    rowCount += this.insertBatch(bookTradeNoList);

                    //成功
                    hmDownHistoryService.insertDownLog("技师作业单",
                            JlifeConstant.BOOK_TRADE_URL, jsonString, hmBookTradeOrderDTO.getBeginTime(), null, 0);
                    pageIndex++;
                } else {
                    //失败
                    hmDownHistoryService.insertDownLog("技师作业单",
                            JlifeConstant.BOOK_TRADE_URL, jsonString, hmBookTradeOrderDTO.getBeginTime(), null, 1);
                    return 0;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } while (pageIndex <= totalPage + 1);

        return rowCount;
    }

    @Override
    public int syncHmBookTradeOrderByPhone(String phone) {
        HmToken hmToken = hmTokenMapper.selectAll();
        String token = hmToken.getToken();
        hmBookTradeOrderMapper.deleteByUserPhone(phone);
        int row = 0;
        for (int i = 0; i < 2; i++) {
            if (i != 0) {
                token = hmToken.getSubToken();
            }

            int totalPage;
            int pageIndex = JlifeConstant.PAGE_INDEX;
            int pageSize = JlifeConstant.PAGE_SIZE;

            do {
                HmBookTradeOrderDTO hmBookTradeOrderDTO = new HmBookTradeOrderDTO();
                hmBookTradeOrderDTO.setPageSize(pageSize);
                hmBookTradeOrderDTO.setPageIndex(pageIndex);
                hmBookTradeOrderDTO.setUserPhone(phone);
                if (i != 0) {
                    hmBookTradeOrderDTO.setStationCode("147001");
                }

                String jsonString = JSONObject.toJSONString(hmBookTradeOrderDTO);
                //JSONObject jsonObject = HttpUtil.requestPost(token, jsonString, JlifeConstant.BOOK_TRADE_URL);

                Map<String, Object> request = HttpUtil.request(token, jsonString, JlifeConstant.BOOK_TRADE_URL);

                if ("true".equals(request.get("success").toString())) {
                    JSONObject data = (JSONObject) JSON.toJSON(request.get("data"));
                    double total = Double.parseDouble(String.valueOf(data.get("total")));
                    totalPage = (int) total / pageSize;
                    logger.info("totalPage:{}", totalPage);
                    JSONArray items = data.getJSONArray("list");
                    if (CollectionUtils.isEmpty(items)) {
                        logger.info("数据为空了。。。。。" + JsonUtil.getJson(request));
                        return 0;
                    }
                    String filter = this.filter.filter(items.toJSONString());
                    //String aliases = EmojiParser.parseToAliases(items.toJSONString());
                    List<HmBookTradeOrder> hmBookTradeOrders = JSONObject.parseArray(filter, HmBookTradeOrder.class);
                    for (HmBookTradeOrder tradeOrder : hmBookTradeOrders) {
                        tradeOrder.setUserPhone(phone);
                        if (tradeOrder.getUserPhone().contains("**")) {
                            String phones = phoneDecryptService.getPhoneByTradeNo("userPhone", tradeOrder.getBookTradeNo().toString(), "BOOK_TRADE");
                            if (phones != null)
                                tradeOrder.setUserPhone(phones);
                        }
                    }
                    row += hmBookTradeOrderMapper.insertByBatch(hmBookTradeOrders);

                    //成功
                    hmDownHistoryService.insertDownLog("技师作业单",
                            JlifeConstant.BOOK_TRADE_URL, jsonString, hmBookTradeOrderDTO.getBeginTime(), null, 0);
                    pageIndex++;
                } else {
                    //失败
                    hmDownHistoryService.insertDownLog("技师作业单",
                            JlifeConstant.BOOK_TRADE_URL, jsonString, hmBookTradeOrderDTO.getBeginTime(), null, 1);
                    return 0;
                }
            } while (pageIndex <= totalPage + 1);
        }
        return row;
    }

    //更新服务者今天的服务单
    @Override
    public int syncHmBookTradeOrderByServantPhone(String phone) {
        HmToken hmToken = hmTokenMapper.selectAll();
        String token = hmToken.getToken();
        hmBookTradeOrderMapper.deleteByServantPhone(phone);
        int row = 0;
        for (int i = 0; i < 2; i++) {
            if (i != 0) {
                token = hmToken.getSubToken();
            }

            int totalPage;
            int pageIndex = JlifeConstant.PAGE_INDEX;
            int pageSize = JlifeConstant.PAGE_SIZE;

            do {
                HmBookTradeOrderDTO hmBookTradeOrderDTO = new HmBookTradeOrderDTO();
                hmBookTradeOrderDTO.setPageSize(pageSize);
                hmBookTradeOrderDTO.setPageIndex(pageIndex);
                DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd 00:00:00");
                hmBookTradeOrderDTO.setBeginTime(dtf2.format(LocalDateTime.now()));
                hmBookTradeOrderDTO.setEndTime(dtf2.format(LocalDateTime.now().plusDays(1)));

                hmBookTradeOrderDTO.setServantPhone(phone);
                if (i != 0) {
                    hmBookTradeOrderDTO.setStationCode("147001");
                }

                String jsonString = JSONObject.toJSONString(hmBookTradeOrderDTO);
                //JSONObject jsonObject = HttpUtil.requestPost(token, jsonString, JlifeConstant.BOOK_TRADE_URL);

                Map<String, Object> request = HttpUtil.request(token, jsonString, JlifeConstant.BOOK_TRADE_URL);

                if ("true".equals(request.get("success").toString())) {
                    JSONObject data = (JSONObject) JSON.toJSON(request.get("data"));
                    double total = Double.parseDouble(String.valueOf(data.get("total")));
                    totalPage = (int) total / pageSize;
                    logger.info("totalPage:{}", totalPage);
                    JSONArray items = data.getJSONArray("list");
                    if (CollectionUtils.isEmpty(items)) {
                        logger.info("数据为空了。。。。。" + JsonUtil.getJson(request));
                        return 0;
                    }
                    String filter = this.filter.filter(items.toJSONString());
                    //String aliases = EmojiParser.parseToAliases(items.toJSONString());
                    List<HmBookTradeOrder> hmBookTradeOrders = JSONObject.parseArray(filter, HmBookTradeOrder.class);
                    //手机号解密
                    for (HmBookTradeOrder tradeOrder : hmBookTradeOrders) {
                        if (tradeOrder.getUserPhone().contains("**")) {
                            String dPhone = phoneDecryptService.getPhoneByTradeNo("userPhone", tradeOrder.getBookTradeNo().toString(), "BOOK_TRADE");
                            if (dPhone != null)
                                tradeOrder.setUserPhone(dPhone);
                        }
                    }
                    row += hmBookTradeOrderMapper.insertByBatch(hmBookTradeOrders);

                    //成功
                    hmDownHistoryService.insertDownLog("技师当日作业单",
                            JlifeConstant.BOOK_TRADE_URL, jsonString, hmBookTradeOrderDTO.getBeginTime(), null, 0);
                    pageIndex++;
                } else {
                    //失败
                    hmDownHistoryService.insertDownLog("技师当日作业单",
                            JlifeConstant.BOOK_TRADE_URL, jsonString, hmBookTradeOrderDTO.getBeginTime(), null, 1);
                    return 0;
                }
            } while (pageIndex <= totalPage + 1);
        }
        return row;
    }

    @Override
    public int deleteDistinctData(DateTime dateTime) {
        return hmBookTradeOrderMapper.deleteDistinctData(dateTime);
    }


    @Override
    public HmBookTradeOrder selectNewOne() {
        return hmBookTradeOrderMapper.selectNewOne(null);
    }

    @Override
    public HmBookTradeOrder findByNo(Integer bookTradeNo) {
        if (bookTradeNo == null) return null;
        return hmBookTradeOrderMapper.selectByBookTradeNo(bookTradeNo);
    }

    @Override
    public int updateHmBookTradeList(DateTime startTime, DateTime endTime) {
        HmToken hmToken = hmTokenMapper.selectAll();
        String token = hmToken.getToken();

        //hmBookTradeOrderMapper.deleteByBetWeenTime(DateUtil.formatDate(startTime), DateUtil.formatDate(endTime));

        int rowCount = 0;

        int totalPage = -1;
        int pageIndex = JlifeConstant.PAGE_INDEX;
        int pageSize = 5000;

        do {
            HmBookTradeOrderDTO hmBookTradeOrderDTO = new HmBookTradeOrderDTO();
            hmBookTradeOrderDTO.setPageSize(pageSize);
            hmBookTradeOrderDTO.setPageIndex(pageIndex);
            hmBookTradeOrderDTO.setBeginTime(DateUtil.formatDateTime(startTime));
            hmBookTradeOrderDTO.setEndTime(DateUtil.formatDateTime(endTime));
            hmBookTradeOrderDTO.setStatus(new Integer[]{2, 9});//已提供、已完成
            String jsonString = JSONObject.toJSONString(hmBookTradeOrderDTO);

            try {
                Map<String, Object> request = retryService.requestPost(token, jsonString, JlifeConstant.BOOK_TRADE_URL);

                if ("true".equals(request.get("success").toString())) {
                    JSONObject data = (JSONObject) JSON.toJSON(request.get("data"));
                    double total = Double.parseDouble(String.valueOf(data.get("total")));
                    totalPage = (int) total / pageSize;
                    logger.info("totalPage:{}", totalPage);
                    JSONArray items = data.getJSONArray("list");
                    if (CollectionUtils.isEmpty(items)) {
                        return 0;
                    }
                    String filter = this.filter.filter(items.toJSONString());
                    List<HmBookTradeOrder> hmBookTradeOrders = JSONObject.parseArray(filter, HmBookTradeOrder.class);
                    List<HmBookTradeOrder> saveList = new ArrayList<>();
                    for (HmBookTradeOrder tradeOrder : hmBookTradeOrders) {
                        HmBookTradeOrder _tradeOrder = hmBookTradeOrderMapper.selectByBookTradeNo(tradeOrder.getBookTradeNo());
                        if (_tradeOrder != null) {
                            _tradeOrder.setStatus(tradeOrder.getStatus());
                            _tradeOrder.setServantPhone(tradeOrder.getServantPhone());
                            _tradeOrder.setServantName(tradeOrder.getServantName());
                            hmBookTradeOrderMapper.updateByPrimaryKey(_tradeOrder);
                        } else {
                            saveList.add(tradeOrder);
                        }
                    }
                    rowCount +=hmBookTradeOrders.size();
                    if(saveList.size()>0)
                        hmBookTradeOrderMapper.insertByBatch(saveList);
//                    List<Integer> bookTrades = hmBookTradeOrders.stream().filter(a -> a.getStatus() == 6).map(a -> a.getBookTradeNo()).collect(Collectors.toList());
//                    bookTradeNoList.addAll(bookTrades);
//                    rowCount += this.insertBatch(hmBookTradeOrders);

                    //成功
                    hmDownHistoryService.insertDownLog("技师作业单", JlifeConstant.BOOK_TRADE_URL, jsonString, hmBookTradeOrderDTO.getBeginTime(), null, 0);
                    pageIndex++;
                } else {
                    //失败
                    hmDownHistoryService.insertDownLog("技师作业单", JlifeConstant.BOOK_TRADE_URL, jsonString, hmBookTradeOrderDTO.getBeginTime(), null, 1);
                    return 0; //第二个账号数据为空了，正常；返回第一个账号抓取的数据
                }
            } catch (Exception e) {
                e.printStackTrace();
                pageIndex++; //如果出现异常，也要继续往下走，避免死循环
            }

        } while (pageIndex <= totalPage + 1);

        return rowCount;
    }


    public int insertBatch(List<HmBookTradeOrder> hmBookTradeOrders) {
        List<HmBookTradeOrder> list = new ArrayList<HmBookTradeOrder>();
        for (HmBookTradeOrder s : hmBookTradeOrders) {
            list.add(s);
            if (list.size() >= 500) {
                hmBookTradeOrderMapper.insertByBatch(list);
                list.clear();
            }
        }
        if (!list.isEmpty()) {
            hmBookTradeOrderMapper.insertByBatch(list);
        }
        return hmBookTradeOrders.size();
    }

    /**
     * 我已上门接口
     * {
     * "code":200,
     * "fail":true,
     * "message":"暂不能确认服务，请在完成服务后再点击服务已提供。",
     * "success":false
     * }
     *
     * @param bookTradeNo
     * @return
     */
    @Override

    public Map<String, Object> confirmBookTrade(Integer bookTradeNo) {
        JSONObject js = buildParam(bookTradeNo);
        if (null == js) {
            HashMap<String, Object> objectObjectHashMap = new HashMap<>();
            objectObjectHashMap.put("message", "未找到对应的数据");
            return objectObjectHashMap;
        }
        OkHttpClient okHttpClient = OkHttpUtil.getClient();
        HmToken hmToken = hmTokenMapper.selectAll();
        String token = hmToken.getToken();
        MediaType ACCEPT_JSON = MediaType.get("application/json; charset=utf-8");
        Request request = new Request.Builder().url(serverProvidedUrl).header("cookie", "WDKSESSID=" + token).post(RequestBody.create(js.toJSONString(), ACCEPT_JSON)).build();
        return getStringObjectMap(okHttpClient, request);
    }

    @SuppressWarnings("unchecked")
    private Map<String, Object> getStringObjectMap(OkHttpClient okHttpClient, Request request) {
        try (Response response = okHttpClient.newCall(request).execute()) {
            String string = Objects.requireNonNull(response.body()).string();
            if (string.length() < 2000) {
                logger.info("调用盒马接口返回数据:" + string);
            }
            return JSONObject.parseObject(string, Map.class);
        } catch (IOException e) {
            logger.error("调用盒马接口更新技师服务单状态失败，失败原因：" + e.getMessage());
            return new HashMap<>();
        }
    }

    @Override
    public Map<String, Object> arrivedByMerchant(Integer bookTradeNo) {
        OkHttpClient client = OkHttpUtil.getClient();
        String token = hmTokenMapper.selectAll().getToken();
        FormBody formBody = new FormBody.Builder().add("bookTradeNo", bookTradeNo.toString()).build();
        Request request = new Request.Builder().url(serverOpenUrl).header("cookie", "WDKSESSID=" + token).post(formBody).build();
        return getStringObjectMap(client, request);
    }

    @Override
    public int deleteHmBookTradeList(DateTime startTime, DateTime endTime) {
        if (hmRequestService.insert(serverInfoGetUrl) == 0) {
            logger.error("超过当日最大请求数，请求中止");
            return 0;
        }

        OkHttpClient client = OkHttpUtil.getClient();
        String token = hmTokenMapper.selectAll().getToken();
        MediaType ACCEPT_JSON = MediaType.get("application/json; charset=utf-8");
        JSONObject js = new JSONObject();
        js.put("beginTime", DateUtil.formatDateTime(startTime));
        js.put("endTime", DateUtil.formatDateTime(endTime));
        js.put("pageIndex", 1);
        js.put("pageSize", 5000);
        js.put("status", Collections.singletonList(4));
        Request request = new Request.Builder().url(serverInfoGetUrl)
                .header("cookie", "WDKSESSID=" + token).post(RequestBody.create(js.toJSONString(), ACCEPT_JSON)).build();
        Map<String, Object> stringObjectMap = getStringObjectMap(client, request);
        int rowCount = 0;
        Boolean isSuccess = (Boolean) stringObjectMap.get("success");
        if (!isSuccess) {
            logger.warn("查询取消订单数据失败");
            return rowCount;
        }
        //检查是否需要翻页查询
        JSONObject jsonObject = (JSONObject) stringObjectMap.get("data");
        if (null == jsonObject) {
            return rowCount;
        }
        Integer total = jsonObject.getInteger("total");
        List<String> collect = new ArrayList<>();
        if (total > 5000) {
        	//加入第一页数据
        	 List<HmBookTradeOrder> tempTrade = jsonObject.getJSONArray("list").toJavaList(HmBookTradeOrder.class);
             collect.addAll(tempTrade.stream().map(a -> String.valueOf(a.getBookTradeNo())).collect(Collectors.toList()));
             
            //计算需要翻页的次数
            int page = total / 5000;
            for (int i = 0; i < page; i++) {
                js.put("pageIndex", i + 2);
                request = new Request.Builder().url(serverInfoGetUrl)
                        .header("cookie", "WDKSESSID=" + token).post(RequestBody.create(js.toJSONString(), ACCEPT_JSON)).build();
                stringObjectMap = getStringObjectMap(client, request);
                isSuccess = (Boolean) stringObjectMap.get("success");
                if (!isSuccess) {
                    logger.warn("查询取消订单第{}页数据失败", i + 2);
                    return rowCount;
                }
                jsonObject = (JSONObject) stringObjectMap.get("data");
                if (null == jsonObject) {
                    return rowCount;
                }
                List<HmBookTradeOrder> hmBookTradeOrders = jsonObject.getJSONArray("list").toJavaList(HmBookTradeOrder.class);
                collect.addAll(hmBookTradeOrders.stream().map(a -> String.valueOf(a.getBookTradeNo())).collect(Collectors.toList()));
            }
        } else {
            List<HmBookTradeOrder> hmBookTradeOrders = jsonObject.getJSONArray("list").toJavaList(HmBookTradeOrder.class);
            collect.addAll(hmBookTradeOrders.stream().map(a -> String.valueOf(a.getBookTradeNo())).collect(Collectors.toList()));
        }
        if (!collect.isEmpty()) {
//        	logger.info("collect进入开始删除"+collect.size());
//            //如果数据量大于1000，分组删除
//            if (collect.size() > 100) {
//                int size = collect.size();
//                int group = size / 100;
//                for (int i = 0; i < group; i++) {
//                    List<String> subList = collect.subList(i * 100, (i + 1) * 100);
//                    rowCount += hmBookTradeOrderMapper.deleteByBookTradeNoList(subList);
//                   // hmBookTradeOrderMapper.deleteWorkerOrderList(subList);
//                }
//                List<String> subList = collect.subList(group * 100, size);
//                if(subList!=null&&!collect.isEmpty()) {
//                	rowCount += hmBookTradeOrderMapper.deleteByBookTradeNoList(subList);
//                }
//               // hmBookTradeOrderMapper.deleteWorkerOrderList(subList);
//            } else {
//                rowCount += hmBookTradeOrderMapper.deleteByBookTradeNoList(collect);
//               // hmBookTradeOrderMapper.deleteWorkerOrderList(collect);
//            }
            
            try {
            	logger.info("collect再次进入开始删除"+collect.size());
            	List<String> subList =new ArrayList<String>();
            	for(String e:collect) {
            		subList.add(e);
            		if(subList.size()>=100) {
//            			hmBookTradeOrderMapper.deleteWorkerOrderList(subList);
            			logger.info("删除subList:{}",subList);
            			hmBookTradeOrderMapper.deleteByBookTradeNoList(subList);
            			rowCount += hmBookTradeOrderMapper.updateHmBookTradeState(subList);
            			subList.clear();
            		}
            	}
            	if(subList.size()>0) {
//            		hmBookTradeOrderMapper.deleteWorkerOrderList(subList);
            		 hmBookTradeOrderMapper.deleteByBookTradeNoList(subList);
            		 rowCount += hmBookTradeOrderMapper.updateHmBookTradeState(subList);
            	}
			} catch (Exception e2) {
				logger.info("删除worker_worderinfo出错：deleteWorkerOrderList：{}",e2);
			}
        }
        System.out.println("collect = " + collect.size());


        return rowCount;
    }

    /**
     * {"bookTradeNo":"12789696","servantPhone":"","userPhone":"","pageIndex":1,"pageSize":50}
     *
     * @param bookTradeNo
     * @return
     */
    private JSONObject buildParam(Integer bookTradeNo) {
        OkHttpClient client = OkHttpUtil.getClient();
        String token = hmTokenMapper.selectAll().getToken();
        MediaType ACCEPT_JSON = MediaType.get("application/json; charset=utf-8");
        JSONObject js = new JSONObject();
        js.put("bookTradeNo", bookTradeNo);
        js.put("pageIndex", 1);
        js.put("pageSize", 50);
        Request request = new Request.Builder().url(serverInfoGetUrl).header("cookie", "WDKSESSID=" + token).post(RequestBody.create(js.toJSONString(), ACCEPT_JSON)).build();
        Map<String, Object> stringObjectMap = getStringObjectMap(client, request);
        if (!stringObjectMap.isEmpty() && stringObjectMap.containsKey("success") && (boolean) stringObjectMap.get("success")) {
            JSONObject jsonObject = (JSONObject) stringObjectMap.get("data");
            if (jsonObject.getInteger("total") >= 1) {
                List<ServerOrder> list = jsonObject.getJSONArray("list").toJavaList(ServerOrder.class);
                ServerOrder serverOrder = list.get(0);
                String s = JSONObject.toJSONString(serverOrder);
                return JSON.parseObject(s);
            }
        }
        return null;
    }

}
