package org.ta.pddserver.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.ta.pddserver.model.pddgd.request.GDTicketListRequest;
import org.ta.pddserver.model.pddgd.response.GDTicketRepsonse;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
public class PddGDUtil {
    private static final String CLIENT_ID = "8f5f3f9c92e847b2894fc9c0afce3d61";
    private static final String CLIENT_SECRET = "281d79ad5117d20a51efb9e7b0d5f7ee336399b0";

    private static final int page_size = 100;

    public static List<GDTicketRepsonse> getTickets() {
        long end = new Date().getTime() / 1000;
        int page = 0;
        int total_count = 1;
        List<GDTicketRepsonse> list = new ArrayList<GDTicketRepsonse>();
        while (page * page_size <= total_count) {
            page++;
            try {
                JSONObject respObject = getTicketsByPage(1, end);
                JSONObject jsonObject = respObject.getJSONObject("logistics_ticket_get_response");
                total_count = jsonObject.getInteger("total_count");
//                log.info("本次数量：{}", total_count);
                List<GDTicketRepsonse> tempList = jsonObject.getJSONArray("logistics_ticket_list").toJavaList(GDTicketRepsonse.class);
                if (tempList != null && !tempList.isEmpty()) {
                    list.addAll(tempList);
                }
            } catch (Exception e) {
                log.error("工单获取失败");
            }

        }
        return list;
    }

    private static JSONObject getTicketsByPage(int page, long end) {
        GDTicketListRequest request = new GDTicketListRequest();
        request.setClient_id(CLIENT_ID);
        request.setEnd_updated_at(end);
        request.setStart_updated_at(end - 1800);
        request.setPage(page);
        request.setPage_size(page_size);
        request.setType("pdd.logistics.ticket.get");
        long time = new Date().getTime() / 1000;
        request.setTimestamp(time);
        request.setSign(PddSignTool.generateSign(request, CLIENT_SECRET));
        String resp = PddHttpTool.sendJsonPostGD2(request);
        return JSON.parseObject(resp);
    }
}
