package org.ta.pddserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.ta.pddserver.entity.GDAttachmentEntity;
import org.ta.pddserver.entity.GDTicketEntity;
import org.ta.pddserver.model.api.request.LogOrderListRequest;
import org.ta.pddserver.model.api.request.TicketListRequest;
import org.ta.pddserver.model.pddgd.request.GDTicketReplyRequest;
import org.ta.pddserver.model.pddgd.request.GDUploadRequest;
import org.ta.pddserver.model.pddgd.response.GDTicketReplyRepsonse;
import org.ta.pddserver.model.pddgd.response.GDTicketRepsonse;
import org.ta.pddserver.model.pddjy.request.JYBaseRequestModel;
import org.ta.pddserver.service.impl.GDAttachmentImpl;
import org.ta.pddserver.service.impl.GDTicketImpl;
import org.ta.pddserver.utils.ImageUtils;
import org.ta.pddserver.utils.JsonResponse;
import org.ta.pddserver.utils.PddHttpTool;
import org.ta.pddserver.utils.PddSignTool;

import java.io.IOException;
import java.util.*;

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

    public JSONObject getTicketList() {
        JSONObject jsonObject = new JSONObject();
        long end = new Date().getTime() / 1000;
        jsonObject.put("end_updated_at", end);
        jsonObject.put("start_updated_at", end - 1800);
        jsonObject.put("page", 1);
        jsonObject.put("page_size", 100);
        jsonObject.put("client_id", CLIENT_ID);

        JYBaseRequestModel requestModel = new JYBaseRequestModel();
        requestModel.setRequest(JSON.toJSONString(jsonObject));
        requestModel.setRequest_id("" + new Date().getTime());
        requestModel.setType("pdd.logistics.ticket.get");
        requestModel.setTarget_client_id(CLIENT_ID);
        requestModel.setClient_id(CLIENT_ID);
        long time = new Date().getTime() / 1000;
        requestModel.setTimestamp(time);
        requestModel.setSign(PddSignTool.generateSign(requestModel, CLIENT_SECRET));
        log.info("requestModel:{}", JSON.toJSONString(requestModel));
//        String resp = PddHttpTool.postRequest(requestModel);
        String resp = PddHttpTool.sendJsonPostGD(requestModel);
        log.info("resp = {}", resp);
        JSONObject respObj = JSON.parseObject(resp);
        int count = respObj.getInteger("total_count");
        JSONArray list = respObj.getJSONArray("logistics_ticket_list");
        if (!list.isEmpty()) {
            for (int i = 0; i < list.size(); i++) {
                JSONObject ticket = list.getJSONObject(i);
                GDTicketRepsonse gdTicketRepsonse = ticket.toJavaObject(GDTicketRepsonse.class);
                // todo 保存数据
            }
        }
        return respObj;
    }

    public JSONObject replyTicket() {

        Long ticketId = 1L;
        String waybill_no = "waybill_no";

        GDTicketReplyRequest replyRequest = new GDTicketReplyRequest();
        replyRequest.setTicket_id(ticketId);
        replyRequest.setWaybill_no(waybill_no);
        replyRequest.setHandle_result("无");
        replyRequest.setSign_state(1);
        replyRequest.setCompensate_state(1);
        replyRequest.setDuty(0);
        replyRequest.setExpress_dealer("XXX");
        replyRequest.setExpress_dealer_contact("18599877823");
        replyRequest.setReply_type(1);

        JYBaseRequestModel requestModel = new JYBaseRequestModel();
        requestModel.setRequest(JSON.toJSONString(replyRequest));
        requestModel.setRequest_id("" + new Date().getTime());
        requestModel.setType("pdd.logistics.ticket.get");
        requestModel.setTarget_client_id(CLIENT_ID);
        requestModel.setClient_id(CLIENT_ID);
        long time = new Date().getTime() / 1000;
        requestModel.setTimestamp(time);
        requestModel.setSign(PddSignTool.generateSign(requestModel, CLIENT_SECRET));
        log.info("requestModel:{}", JSON.toJSONString(requestModel));
//        String resp = PddHttpTool.postRequest(requestModel);
        String resp = PddHttpTool.sendJsonPostGD(requestModel);
        log.info("resp = {}", resp);
        JSONObject respObj = JSON.parseObject(resp);
        JSONObject respObject = respObj.getJSONObject("logistics_ticket_notify_response");
        GDTicketReplyRepsonse replyRepsonse = respObject.toJavaObject(GDTicketReplyRepsonse.class);
        log.info("replyRepsonse is_success:{}", replyRepsonse.getIs_success());
        return respObj;
    }


    @Resource
    GDTicketImpl gdTicketImpl;

    @Resource
    GDAttachmentImpl gdAttachmentImpl;

    /*工单列表*/
    @PostMapping("/ticketList")
    public JSONObject ticketList(HttpServletRequest request, @RequestBody TicketListRequest ticketListRequest) {
        return JsonResponse.generateLocalCommonSuccessResponse(gdTicketImpl.getListByRequest(ticketListRequest));
    }

    /*工单详情*/
    @PostMapping("/ticketInfo")
    public JSONObject ticketInfo(HttpServletRequest request, @RequestBody TicketListRequest ticketListRequest) {
        Map<String, Object> map = new HashMap<>();

        GDTicketEntity gdTicketEntity = gdTicketImpl.getByTicketId((long) ticketListRequest.getTicket_id());
        if(gdTicketEntity == null){
            return JsonResponse.generateLocalCommonFailedResponse("-1", "信息获取失败，请检查上传信息");
        }

        List<GDAttachmentEntity> list = gdAttachmentImpl.getListByTicketId(ticketListRequest.getTicket_id());

        map.put("ticket", gdTicketEntity);
        map.put("attachment", list);

        return JsonResponse.generateLocalCommonSuccessResponse(map);
    }

    /*工单列表*/
    @PostMapping("/uploadImage")
    public JSONObject uploadImage(HttpServletRequest request, @RequestBody GDUploadRequest gdUploadRequest) throws IOException {
        gdUploadRequest.setClient_id(CLIENT_ID);

        gdUploadRequest.setType("pdd.logistics.ticket.image.upload");
        long time = new Date().getTime() / 1000;
        gdUploadRequest.setTimestamp(time);
        gdUploadRequest.setImage(new ImageUtils().downloadCompressToBase64(gdUploadRequest.getImage()));
        gdUploadRequest.setSign(PddSignTool.generateSign(gdUploadRequest, CLIENT_SECRET));
        String resp = PddHttpTool.sendJsonPostGD(gdUploadRequest);
        JSONObject jsonObject = JSONObject.parseObject(resp);

        String image = jsonObject.getJSONObject("logistics_ticket_image_upload_response")
                .getString("image_url");

        Map<String, Object> map = new HashMap<>();
        map.put("image", image);

        return JsonResponse.generateLocalCommonSuccessResponse(map);
    }


}
