package com.reptileclient.jlifeapp.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.reptileclient.jlifeapp.constant.HemaConstant;
import com.reptileclient.jlifeapp.constant.QinGeConstant;
import com.reptileclient.jlifeapp.dao.hm.HmBookOrderMapper;
import com.reptileclient.jlifeapp.dao.hm.HmBookTradeOrderMapper;
import com.reptileclient.jlifeapp.dao.hm.HmTokenMapper;
import com.reptileclient.jlifeapp.dto.HmCreateRightRequestDTO;
import com.reptileclient.jlifeapp.dto.HmrightDetailDTO;
import com.reptileclient.jlifeapp.dto.HmrightDetailRespDTO;
import com.reptileclient.jlifeapp.dto.HmrightRelationOrderDetailDTO;
import com.reptileclient.jlifeapp.entity.hm.HmBookOrder;
import com.reptileclient.jlifeapp.entity.hm.HmBookTradeOrder;
import com.reptileclient.jlifeapp.entity.qg.WorkerInfo;
import okhttp3.EventListener;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class OkHttpUtil extends EventListener {
    public static final MediaType ACCEPT_JSON = MediaType.get("application/json; charset=utf-8");

    private static OkHttpClient client;

    public static String hmToken;

    @Autowired
    private HmTokenMapper tokenMapper;


    private static HmBookOrderMapper bookOrderMapper;

    public static Object getOnJobByHmStationCodes(String queryDay, List<String> hmStationCodes) {
        JSONObject js = new JSONObject();
        js.put("beginTime", queryDay + " 00:00:00");
        js.put("endTime", queryDay + " 23:59:59");
        js.put("stationCode", String.join(",", hmStationCodes).replaceAll("\\[|\\]", ""));
        js.put("pageIndex", 1);
        js.put("pageSize", 1000);
        js.put("status", Collections.singletonList(6));
//        js.put("itemName", "保洁");
        try {
            return post(HemaConstant.serverInfoGetUrl, js.toJSONString());
        } catch (IOException e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("success", false);
            jsonObject.put("message", e.getMessage());
            return jsonObject.toJSONString();
        }
    }

    public static String post2Dy(String requestUrl, Map<String, Object> requestMap, String token) {
        RequestBody requestBody = RequestBody.create(JSONObject.toJSONString(requestMap), ACCEPT_JSON);
        Request request = new Request.Builder().url(requestUrl).post(requestBody)
                .addHeader("cookie", token)
                .addHeader("referer", "https://life.douyin.com/p/merchantpoi/comment_management?groupid=1754694907787275")
                .addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36")
                .build();
        try (Response response = client.newCall(request).execute()) {
            return Objects.requireNonNull(response.body()).string();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String get2Dy(String requestUrl, String token) {
        Request request = new Request.Builder().url(requestUrl)
                .addHeader("cookie", token)
                .addHeader("referer", "https://life.douyin.com/p/merchantpoi/comment_management")
                .addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36")
                .build();
        try (Response response = client.newCall(request).execute()) {
            return Objects.requireNonNull(response.body()).string();
        } catch (IOException e) {
            System.out.println("请求失败，失败原因:" + e.getMessage());
            return e.getMessage();
        }
    }

    public static String post2Dy(String relationUrl, String json, String token) {
        RequestBody requestBody = RequestBody.create(json, ACCEPT_JSON);
        Request request = new Request.Builder().url(relationUrl).post(requestBody)
                .addHeader("cookie", token)
                .addHeader("referer", "https://life.douyin.com/p/merchantpoi/comment_management?groupid=1754694907787275")
                .addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36")
                .build();
        try (Response response = client.newCall(request).execute()) {
            return Objects.requireNonNull(response.body()).string();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @Autowired
    private void setBookOrderMapper(HmBookOrderMapper bookOrderMapper) {
        OkHttpUtil.bookOrderMapper = bookOrderMapper;
    }

    private static HmBookTradeOrderMapper tradeOrderMapper;

    @Autowired
    private void setTradeOrderMapper(HmBookTradeOrderMapper tradeOrderMapper) {
        OkHttpUtil.tradeOrderMapper = tradeOrderMapper;
    }



    private static final String[] queryTypes = new String[]{"1", "2", "3"};

    private static final Map<String, String> shopIdNameMap = new HashMap<>();


    static {
        if (null == client) {
            client = new OkHttpClient().newBuilder().connectTimeout(30, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS).build();
        }
        shopIdNameMap.put("10000257", "上海门店");
//        shopIdNameMap.put("10000276", "北京门店");
//        shopIdNameMap.put("10000277", "深圳门店");
//        shopIdNameMap.put("10002854", "南京门店");
//        shopIdNameMap.put("10002870", "苏州门店");
//        shopIdNameMap.put("10002871", "无锡门店"); //已关闭
//        shopIdNameMap.put("10006927", "杭州门店");
    }

    @PostConstruct
    public void init() {
        hmToken = tokenMapper.selectAll().getToken();
    }

    public static OkHttpClient getClient() {
        return client;
    }

    public static String get(Request request) {
        if (null == request.header("cookie") || !Objects.requireNonNull(request.header("cookie")).contains("WDKSESSID=")) {
            request = request.newBuilder().addHeader("cookie", "WDKSESSID=" + hmToken).build();
        }
        try (Response response = client.newCall(request).execute()) {
            return Objects.requireNonNull(response.body()).string();
        } catch (IOException e) {
            System.out.println("请求失败，失败原因:" + e.getMessage());
            return e.getMessage();
        }
    }


    /**
     * 用于增量同步时补充订单缺失的用户三要素->勤鸽抓数据
     *
     * @param validToken
     * @param buyerId
     * @param outId
     * @return
     */
    public static Map<String, String> getUserMissInfo(String validToken, String buyerId, String outId) {
        Map<String, String> result = new HashMap<>();
        String nameUrl = QinGeConstant.QG_CUSTOMER_INFO_URL + "buyerId=" + buyerId +
                "&workCardId=" + outId + "&queryType=" + queryTypes[0];
        String phoneUrl = QinGeConstant.QG_CUSTOMER_INFO_URL + "buyerId=" + buyerId +
                "&workCardId=" + outId + "&queryType=" + queryTypes[1];
        String addressUrl = QinGeConstant.QG_CUSTOMER_INFO_URL + "buyerId=" + buyerId +
                "&workCardId=" + outId + "&queryType=" + queryTypes[2];
        Request nameRequest = new Request.Builder().url(nameUrl).addHeader("cookie", "SCMSESSID=" + validToken).build();
        String name = get(nameRequest);
        JSONObject parseObject = null;
        try {
            parseObject = JSON.parseObject(name);
        } catch (Exception e) {
            System.out.println("查询用户信息结果失败，返回结果：" + name);
            return new HashMap<>();
        }
        if (parseObject.getBoolean("success")) {
            result.put("name", parseObject.getString("data"));
        } else {
            System.out.println(parseObject);
            System.out.println("查询buyerId=" + buyerId + "的用户的queryID=" + queryTypes[0] + "workerId=【" + outId + "】" + "的信息失败,失败原因=" + parseObject.getString("msg"));
            String s = retryCompensation(buyerId, outId, queryTypes[0], validToken);
            result.put("name", s);
        }
        Request phoneRequest = new Request.Builder().url(phoneUrl).addHeader("cookie", "SCMSESSID=" + validToken).build();
        String phone = get(phoneRequest);
        JSONObject parseObject1 = JSON.parseObject(phone);
        if (parseObject1.getBoolean("success")) {
            result.put("phone", parseObject1.getString("data"));
        } else {
            System.out.println(parseObject1);
            System.out.println("查询buyerId=" + buyerId + "的用户的queryID=" + queryTypes[1] + "workerId=【" + outId + "】" + "的信息失败,失败原因=" + parseObject1.getString("msg"));
            String s = retryCompensation(buyerId, outId, queryTypes[1], validToken);
            result.put("phone", s);
        }
        Request addressRequest = new Request.Builder().url(addressUrl).addHeader("cookie", "SCMSESSID=" + validToken).build();
        String address = get(addressRequest);
        JSONObject parseObject2 = JSON.parseObject(address);
        if (parseObject2.getBoolean("success")) {
            result.put("address", parseObject2.getString("data"));
        } else {
            System.out.println(parseObject2);
            System.out.println("查询buyerId=" + buyerId + "的用户的queryID=" + queryTypes[2] + "workerId=【" + outId + "】" +
                    "的信息失败,失败原因=" + parseObject2.getString("msg"));
            String s = retryCompensation(buyerId, outId, queryTypes[2], validToken);
            result.put("address", s);
        }
        return result;

    }

    /**
     * 重试请求->勤鸽抓数据
     *
     * @param buyerId
     * @param outId
     * @param queryType
     * @param validToken
     * @return
     */
    private static String retryCompensation(String buyerId, String outId, String queryType, String validToken) {
        String url = QinGeConstant.QG_CUSTOMER_INFO_URL + "buyerId=" + buyerId +
                "&workCardId=" + outId + "&queryType=" + queryTypes[Integer.parseInt(queryType) - 1];

        Request request = new Request.Builder().url(url).addHeader("cookie", "SCMSESSID=" + validToken).build();
        String name = get(request);
        JSONObject parseObject = JSON.parseObject(name);
        if (parseObject.getBoolean("success")) {
            return parseObject.getString("data");
        }
        System.out.println("重试查询buyerId=" + buyerId + "的用户的queryID=" + queryTypes[2] + "workerId=【" + outId + "】"
                + "的信息失败,失败原因=" + parseObject.getString("msg"));
        return null;
    }


    /**
     * 获取用户三要素->调用上述 getUserMissInfo
     *
     * @param hash
     * @return
     */
    private static Map<String, Object> getUserInfo(Map<String, Object> hash) {
        if (hash.isEmpty() || !hash.containsKey("resStatus")) {
            return hash;
        }
        List<WorkerInfo> workersInfos = (List<WorkerInfo>) hash.get("workerInfo");
        if (workersInfos.isEmpty()) {
            return new HashMap<>();
        }
        String validToken = (String) hash.get("validToken");
        Map<String, Object> workerInfoMap = new HashMap<>();
        List<WorkerInfo> workerInfosList = new ArrayList<>();
        for (WorkerInfo workerInfo : workersInfos) {
            String workerInfoId = workerInfo.getId();
            String buyerId = workerInfo.getBuyerId();
            Map<String, String> userMissInfo = getUserMissInfo(validToken, buyerId, workerInfoId);
            workerInfo.setBuyerName(userMissInfo.get("name"));
            workerInfo.setBuyerMobile(userMissInfo.get("phone"));
            workerInfo.setBuyerAddress(userMissInfo.get("address"));
            workerInfosList.add(workerInfo);
        }
        workerInfoMap.put("workerInfo", workerInfosList);
        workerInfoMap.put("validToken", validToken);
        workerInfoMap.put("resStatus", true);
        return workerInfoMap;
    }


    /**
     * 分页抓取勤鸽订单数据
     *
     * @param startTime
     * @param endTime
     * @param serviceStoreId
     * @param scmsessId
     * @param getUserInfoFlag
     * @return
     */
    public static Map<String, Object> get(long startTime, long endTime, String serviceStoreId, String scmsessId, boolean getUserInfoFlag) {
        Map<String, Object> hash = new HashMap<>();
        String returnJson = getSubResult(startTime, endTime, serviceStoreId, scmsessId, 1);
        JSONObject jsonObject = JSON.parseObject(returnJson);
        if ((boolean) jsonObject.get("success")) {
            JSONObject data = jsonObject.getJSONObject("data");
            if (!data.containsKey("dataSource")) {
                System.out.println("warn:" + shopIdNameMap.get(serviceStoreId) + "在" +
                        Instant.ofEpochMilli(startTime).atZone(ZoneId.systemDefault()).toLocalDate() + "至" +
                        Instant.ofEpochMilli(endTime).atZone(ZoneId.systemDefault()).toLocalDate() + "之间的订单数据为空");
                return new HashMap<>();
            }
            JSONArray datasource = data.getJSONArray("dataSource");
            if (datasource.size() == 0) {
                return new HashMap<>();
            }
            float total = data.getFloat("total");
            int queryCount = (int) Math.ceil(total / 100);
            List<WorkerInfo> workerInfos = datasource.toJavaList(WorkerInfo.class);
            for (int i = 2; i <= queryCount; i++) {
                try {
                    String subResult = getSubResult(startTime, endTime, serviceStoreId, scmsessId, i);
                    JSONObject parseObject = JSON.parseObject(subResult);
                    JSONArray jsonArray = parseObject.getJSONObject("data").getJSONArray("dataSource");
                    List<WorkerInfo> infoList = jsonArray.toJavaList(WorkerInfo.class);
                    workerInfos.addAll(infoList);
                } catch (Exception e) {
                    System.out.println("获取开始时间为：" + LocalDateTime.now() + "服务门店为=" + shopIdNameMap.get(serviceStoreId)
                            + "分页为" + i + "页的数据失败，失败原因" + e.getMessage());
                    System.out.println("服务门店：" + shopIdNameMap.get(serviceStoreId) + "第" + i + "页数据抓取失败，需要手动补偿");
                }
            }
            hash.put("workerInfo", workerInfos);
            hash.put("resStatus", true);
        } else {
//            return get(startTime, endTime, serviceStoreId, getQLoginToken(), getUserInfoFlag);
            System.out.println("抓取数据失败，失败原因：" + jsonObject.getString("msg"));
            hash.put("resStatus", false);
        }
        hash.put("validToken", scmsessId);
        if (getUserInfoFlag && (boolean) hash.get("resStatus")) {
            return getUserInfo(hash);
        }
        return hash;
    }

    /**
     * 真正去勤鸽抓取数据的逻辑
     *
     * @param startTime
     * @param endTime
     * @param serviceStoreId
     * @param scmsessId
     * @param pageIndex
     * @return
     */
    @NotNull
    private static String getSubResult(long startTime, long endTime, String serviceStoreId, String scmsessId, int pageIndex) {
        Request request = new Request.Builder().
                url(QinGeConstant.QG_ORDER_URL + "&pageIndex=" + pageIndex + "&serviceStoreId="
                        + serviceStoreId + "&gmtCreateStart=" + startTime + "&gmtCreateEnd=" + endTime).
                addHeader("cookie", "SCMSESSID=" + scmsessId).
                build();
        return get(request);
    }


    //{"pageIndex":1,"pageSize":20,"createTimeStart":"2021-11-18 00:00:00","createTimeEnd":"2021-11-19 23:59:59","queryType":1}

    /**
     * 盒马公共线索池
     *
     * @param startTime
     * @param endTime
     * @param token
     * @return
     * @throws IOException
     */
    public static String getOpenClueInfo(String startTime, String endTime, String token) throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pageIndex", 1);
        jsonObject.put("pageSize", "10000");
        jsonObject.put("createTimeStart", startTime);
        jsonObject.put("createTimeEnd", endTime);
        jsonObject.put("queryType", "1");
        RequestBody body = RequestBody.create(jsonObject.toJSONString(), ACCEPT_JSON);
        Request request = new Request.Builder()
                .url(HemaConstant.openCluePoolUrl)
                .post(body)
                .header("cookie", "WDKSESSID=" + token)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return Objects.requireNonNull(response.body()).string();
        }

    }

    /**
     * 盒马0.01元 的体验单
     *
     * @param token
     * @param startTime
     * @param endTime
     * @return
     * @throws IOException
     */
    public static String getServeOrderClueInfo(String token, String startTime, String endTime,Integer pageIndex) throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pageIndex", pageIndex);
        jsonObject.put("pageSize", "3000");
        jsonObject.put("beginTime", startTime);
        jsonObject.put("endTime", endTime);
        RequestBody body = RequestBody.create(jsonObject.toJSONString(), ACCEPT_JSON);
        Request request = new Request.Builder()
                .url(HemaConstant.serverOrderClueUrl)
                .post(body)
                .header("cookie", "WDKSESSID=" + token)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return Objects.requireNonNull(response.body()).string();
        }
    }

    /**
     * 抓取勤鸽数据-根据cancel状态
     *
     * @param shopId
     * @param sessionId
     * @return
     */
    public static Map<String, Object> queryStatus(String shopId, String sessionId) {
        //获取总行数 判断设置分页参数
        String queryResult = realQuery(shopId, sessionId, 1);
        return processOriginResult(null, null, queryResult, shopId, sessionId);
    }

    private static String realQuery(String shopId, String sessionId, int pageIndex) {
        Request cancelOrderQuery = new Request.Builder().url(QinGeConstant.QG_ORDER_URL + "&pageIndex=" + pageIndex + "&statusCode=cancel&serviceStoreId=" + shopId)
                .addHeader("cookie", "SCMSESSID=" + sessionId).build();
        return get(cancelOrderQuery);
    }

    /**
     * 抓取所有已完成（核销的）订单数据
     *
     * @param sevenDayBefore
     * @param now
     * @param shopId
     * @param sessionId
     * @return
     */
    public static Map<String, Object> getFinshTime(long sevenDayBefore, long now, String shopId, String sessionId) {
        String queryResult = realGetFinishTime(sevenDayBefore, now, shopId, sessionId, 1);
        return processOriginResult(sevenDayBefore, now, queryResult, shopId, sessionId);
    }

    @NotNull
    private static Map<String, Object> processOriginResult(Long sevenDayBefore, Long now, String queryResult, String shopId, String sessionId) {
        Map<String, Object> hash = new HashMap<>();
        JSONObject jsonObject = JSON.parseObject(queryResult);
        if ((boolean) jsonObject.get("success")) {
            JSONObject data = jsonObject.getJSONObject("data");
            if (!data.containsKey("dataSource")) {
                System.out.println("查询shop:" + shopIdNameMap.get(shopId) + "失败，失败原因，没有查询到数据信息");
                return new HashMap<>();
            }
            JSONArray datasource = data.getJSONArray("dataSource");
            if (datasource.size() == 0) {
                return new HashMap<>();
            }
            float total = data.getFloat("total");
            int queryCount = (int) Math.ceil(total / 100);
            List<WorkerInfo> workerInfos = datasource.toJavaList(WorkerInfo.class);
            for (int i = 2; i <= queryCount; i++) {
                try {
                    String subResult;
                    if (null != sevenDayBefore) {
                        subResult = realGetFinishTime(sevenDayBefore, now, shopId, sessionId, i);
                    } else {
                        subResult = realQuery(shopId, sessionId, i);
                    }
                    JSONObject parseObject = JSON.parseObject(subResult);
                    JSONArray jsonArray = parseObject.getJSONObject("data").getJSONArray("dataSource");
                    List<WorkerInfo> infoList = jsonArray.toJavaList(WorkerInfo.class);
                    workerInfos.addAll(infoList);
                } catch (Exception e) {
                    System.out.println("获取门店为" + shopIdNameMap.get(shopId) + "分页为" + i + "页的数据失败，失败原因" + e.getMessage());
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException ignored) {
                    }
                    String subResult = realQuery(shopId, sessionId, i);
                    JSONObject parseObject = JSON.parseObject(subResult);
                    if (parseObject.getBoolean("success")) {
                        JSONArray jsonArray = parseObject.getJSONObject("data").getJSONArray("dataSource");
                        List<WorkerInfo> infoList = jsonArray.toJavaList(WorkerInfo.class);
                        workerInfos.addAll(infoList);
                    } else {
                        throw new RuntimeException("获取数据失败，失败原因：" + e.getMessage());
                    }
                }
            }
            hash.put("workerInfo", workerInfos);
            hash.put("resStatus", true);
        } else {
            hash.put("resStatus", false);
        }
        return hash;
    }

    private static String realGetFinishTime(long sevenDayBefore, long now, String shopId, String sessionId, int pageIndex) {
        Request finshQuery = new Request.Builder().url(QinGeConstant.QG_ORDER_URL + "&pageIndex=" + pageIndex + "&serviceStoreId="
                        + shopId + "&gmtIdentifyStart=" + sevenDayBefore + "&gmtIdentifyEnd=" + now)
                .addHeader("cookie", "SCMSESSID=" + sessionId).build();
        return get(finshQuery);
    }

    /**
     * 手动补偿用
     *
     * @param startTime
     * @param endTime
     * @param shopId
     * @param sessionId
     * @param b
     * @param pageIndexs
     * @return
     */
    public static Map<String, Object> recoupQgData(long startTime, long endTime, String shopId, String sessionId, boolean b, List<Integer> pageIndexs) {
        Map<String, Object> hash = new HashMap<>();
        List<WorkerInfo> workerInfos = new ArrayList<>();
        for (Integer pageIndex : pageIndexs) {
            try {
                String subResult = getSubResult(startTime, endTime, shopId, sessionId, pageIndex);
                JSONObject parseObject = JSON.parseObject(subResult);
                JSONArray jsonArray = parseObject.getJSONObject("data").getJSONArray("dataSource");
                List<WorkerInfo> infoList = jsonArray.toJavaList(WorkerInfo.class);
                workerInfos.addAll(infoList);
            } catch (Exception e) {
                System.out.println("获取开始时间为：" + LocalDateTime.now() + "服务门店为=" + shopIdNameMap.get(shopId)
                        + "分页为" + pageIndex + "页的数据失败，失败原因" + e.getMessage());
                System.out.println("服务门店：" + shopIdNameMap.get(shopId) + "第" + pageIndex + "页数据抓取失败，需要手动补偿");
            }
            hash.put("workerInfo", workerInfos);
            hash.put("resStatus", true);
        }
        hash.put("validToken", sessionId);
        if (b && (boolean) hash.get("resStatus")) {
            return getUserInfo(hash);
        }
        return hash;
    }

    /**
     * 根据盒马权益单号查询盒马订单信息
     *
     * @param rightOrderNo
     * @return
     */
    public static String getHmRightOrderInfo(String rightOrderNo) {
        JSONObject js = new JSONObject();
        js.put("serviceContractNo", rightOrderNo);
        js.put("currentPage", 1);
        js.put("pageSize", 1);
        try {
            return post(HemaConstant.hmRightQueryUrl, js.toJSONString());
        } catch (IOException e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", -1);
            jsonObject.put("message", e.getMessage());
            return jsonObject.toJSONString();
        }
    }

    public static String getHMOrderByWorkerTel(String workerTel) {
        System.out.println("workerTel = " + workerTel);
        JSONObject js = new JSONObject();
        LocalDateTime start = LocalDateTime.now();
        LocalDateTime end = start.plusDays(14);
        js.put("beginTime", start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        js.put("endTime", end.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        js.put("pageIndex", 1);
        js.put("pageSize", 200);
        js.put("status", Arrays.asList(1, 6));
        js.put("servantPhone", workerTel);
        try {
            return post(HemaConstant.serverInfoGetUrl, js.toJSONString());
        } catch (IOException e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("success", false);
            jsonObject.put("message", e.getMessage());
            return jsonObject.toJSONString();
        }
    }

    /**
     * 获取预约详情
     * 从权益单详情& 工单详情中获取汇总信息
     *
     * @param rightOrderNo 权益卡号
     * @return 权益信息和预约情况
     */
    public static String getHmRightDetail(String rightOrderNo) {
        JSONObject js = new JSONObject();
        js.put("serviceContractNo", rightOrderNo);
        js.put("pageIndex", 1);
        js.put("pageSize", 50);
        try {
            String hmResult = post(HemaConstant.serverOrderClueUrl, js.toJSONString());
            // 获取权益单详情 通过 服务单管理接口
            JSONObject jsonObject = JSONObject.parseObject(hmResult);
            if (jsonObject.getBoolean("success")) {
                //解析详情信息
                String data = jsonObject.getString("data");
                JSONObject parseObject = JSONObject.parseObject(data);
                String list = parseObject.getString("list");
                List<HmrightDetailDTO> detailDTOList = JSONArray.parseArray(list, HmrightDetailDTO.class);
                if (null != detailDTOList && !detailDTOList.isEmpty()) {
                    List<HmrightDetailRespDTO> respDTOS = new ArrayList<>();
                    List<HmrightRelationOrderDetailDTO> waitUpdate = new ArrayList<>();
                    updateBookOrder(rightOrderNo, detailDTOList);
                    for (HmrightDetailDTO detailDTO : detailDTOList) {
                        HmrightDetailRespDTO respDTO = new HmrightDetailRespDTO();
                        BeanUtils.copyProperties(detailDTO, respDTO);
                        //补充 服务者信息 和 服务站信息
                        js.remove("serviceContractNo");
                        js.put("bookTradeNo", detailDTO.getBookTradeNo());
                        js.put("currentPage", 1);
                        js.put("pageSize", 1);
                        String bookInfoResult = post(HemaConstant.serverInfoGetUrl, js.toJSONString());
                        JSONObject object = JSONObject.parseObject(bookInfoResult);
                        if (object.getBoolean("success")) {
                            JSONObject objectJSONObject = object.getJSONObject("data");
                            String objectString = objectJSONObject.getString("list");
                            List<HmrightRelationOrderDetailDTO> hmrightRelationOrderDetailDTOS =
                                    JSONArray.parseArray(objectString, HmrightRelationOrderDetailDTO.class);
                            if (null != hmrightRelationOrderDetailDTOS && !hmrightRelationOrderDetailDTOS.isEmpty()) {
                                HmrightRelationOrderDetailDTO orderDetailDTO = hmrightRelationOrderDetailDTOS.get(0);
                                waitUpdate.add(orderDetailDTO);
                                respDTO.setServantName(orderDetailDTO.getServantName());
                                respDTO.setServantPhone(orderDetailDTO.getServantPhone());
                                respDTO.setStationCode(orderDetailDTO.getStationCode());
                                respDTO.setStationName(orderDetailDTO.getStationName());
                            } else {
                                JSONObject jsonObject1 = new JSONObject();
                                jsonObject1.put("success", false);
                                jsonObject1.put("message", "获取服务者信息失败");
                                return jsonObject1.toJSONString();
                            }
                            respDTOS.add(respDTO);
                        }
                    }
                    updateBookTradeOrder(waitUpdate, rightOrderNo);
                    JSONObject object1 = new JSONObject();
                    object1.put("success", true);
                    object1.put("message", "调用成功");
                    object1.put("data", respDTOS);
                    return object1.toJSONString();
                } else {
                    JSONObject ss = new JSONObject();
                    ss.put("success", false);
                    ss.put("message", "获取权益卡服务详情失败");
                    return ss.toJSONString();
                }
            } else {
                return jsonObject.toJSONString();
            }
        } catch (IOException e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("success", false);
            jsonObject.put("message", e.getMessage());
            return jsonObject.toJSONString();
        }


    }

    private static void updateBookTradeOrder(List<HmrightRelationOrderDetailDTO> waitUpdate, String rightOrderNo) {
        tradeOrderMapper.deleteByServiceContraceNo(rightOrderNo);
        List<HmBookTradeOrder> orders = waitUpdate.stream().map(a -> {
            HmBookTradeOrder hmBookTradeOrder = new HmBookTradeOrder();
            BeanUtils.copyProperties(a, hmBookTradeOrder);
            return hmBookTradeOrder;
        }).collect(Collectors.toList());
        tradeOrderMapper.insertByBatch(orders);
    }

    private static void updateBookOrder(String rightOrderNo, List<HmrightDetailDTO> detailDTOList) {
        bookOrderMapper.deleteByServiceContractNo(rightOrderNo);
        List<HmBookOrder> list = detailDTOList.stream().map(a -> {
            HmBookOrder bookOrder = new HmBookOrder();
            BeanUtils.copyProperties(a, bookOrder);
            return bookOrder;
        }).collect(Collectors.toList());
        bookOrderMapper.insertByBatch(list);
    }

    public static String cancelHmRight(String rightOrderNo) {
        Request query = new Request.Builder().url(HemaConstant.cancelHmRightUrl + rightOrderNo)
                .addHeader("cookie", "WDKSESSID=" + hmToken).build();
        return get(query);
    }


    @Override
    public void callStart(@NotNull Call call) {
        System.out.println("callStart");
    }

    @Override
    public void callEnd(@NotNull Call call) {
        System.out.println("callEnd");
    }


    public static String getHmRightShop() {
        Request request = new Request.Builder().url(HemaConstant.hmAllShopUrl).addHeader("cookie", "WDKSESSID=" + hmToken).build();
        return get(request);
    }

    public static String getHmRightServiceItem(String supplierCode, String shopCode) {
        String url = HemaConstant.hmItemUrl.replace("{$1}", supplierCode)
                .replace("{$2}", shopCode);
        System.out.println("url=" + url);
        Request cookie = new Request.Builder().url(url).addHeader("cookie", "WDKSESSID=" + hmToken).build();
        return get(cookie);
    }

    /**
     * {"supplierCode":"282160323","shopCode":"8090","itemId":"668562452648","userName":"卢克","userPhone":"18555065889","useTimes":"3","refHmOrderNo":"123435667","useCode":"05","useRemark":"test"}
     *
     * @return
     */
    public static String createHmRightOrder(HmCreateRightRequestDTO rightRequestDTO) {
        try {
            return post(HemaConstant.hmRightCreateUrl, JSONObject.toJSONString(rightRequestDTO));
        } catch (IOException e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("success", false);
            jsonObject.put("message", e.getMessage());
            return jsonObject.toJSONString();
        }
    }

    public static String post(String url, String json) throws IOException {
        RequestBody requestBody = RequestBody.create(json, ACCEPT_JSON);
        Request request = new Request.Builder().url(url).post(requestBody)
                .addHeader("cookie", "WDKSESSID=" + hmToken)
                .addHeader("referer", "https://portalpro.hemaos.com/pages/mall/order.html")
                .addHeader("origin", "https://portalpro.hemaos.com")
                .addHeader("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36")
                .build();
        try (Response response = client.newCall(request).execute()) {
            return Objects.requireNonNull(response.body()).string();
        }

    }

}
