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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.ta.pddserver.config.PddAPIConfig;
import org.ta.pdd.entity.GDAttachmentEntity;
import org.ta.pdd.entity.GDReplyAttachmentEntity;
import org.ta.pdd.entity.GDReplyEntity;
import org.ta.pdd.entity.GDTicketEntity;
import org.ta.pddserver.model.api.request.TicketListRequest;
import org.ta.pddserver.model.api.response.GDReplyListResponse;
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.service.impl.GDAttachmentImpl;
import org.ta.pddserver.service.impl.GDReplyAttachmentImpl;
import org.ta.pddserver.service.impl.GDReplyImpl;
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 org.ta.pddserver.serviceutil.GDOperator;

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

@Slf4j
@RestController
@RequestMapping("/gd")
public class PddGDController {

    @Resource
    GDTicketImpl gdTicketImpl;

    @Resource
    GDAttachmentImpl gdAttachmentImpl;

    @Resource
    GDReplyAttachmentImpl gdReplyAttachmentImpl;

    @Resource
    GDReplyImpl gdReplyImpl;

    @Resource
    GDOperator gdOperator;

    /*工单列表*/
    @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());

        List<GDReplyListResponse> gDReplyList = gdReplyImpl.findListByTicketId(ticketListRequest.getTicket_id());

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

        return JsonResponse.generateLocalCommonSuccessResponse(map, "");
    }

    /*上传图片*/
    @PostMapping("/uploadImage")
    public JSONObject uploadImage(HttpServletRequest request, @RequestBody GDUploadRequest gdUploadRequest) throws IOException {
        gdUploadRequest.setClient_id(PddAPIConfig.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, PddAPIConfig.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, "");
    }


    /*工单回复*/
    @PostMapping("/reply")
    public JSONObject reply(HttpServletRequest request, @RequestBody GDTicketReplyRequest replyRequest) {
        GDTicketEntity gdTicketEntity = gdTicketImpl.getByTicketId(replyRequest.getTicket_id());

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

        replyRequest.setTicket_id(replyRequest.getTicket_id());
        replyRequest.setWaybill_no(gdTicketEntity.getWaybill_no());
        replyRequest.setHandle_result(replyRequest.getHandle_result());
        replyRequest.setSign_state(replyRequest.getSign_state());
        replyRequest.setCompensate_state(replyRequest.getCompensate_state());
        replyRequest.setCompensate_amount(replyRequest.getCompensate_state());
        replyRequest.setDuty(replyRequest.getReply_type());
        replyRequest.setExpress_dealer(replyRequest.getExpress_dealer());
        replyRequest.setExpress_dealer_contact(replyRequest.getExpress_dealer_contact());
        replyRequest.setReply_type(replyRequest.getReply_type());
        List<String> list = replyRequest.getAttach_paths();
        String attach_path_list = JSONArray.toJSONString(replyRequest.getAttach_paths());
        replyRequest.setAttach_path_list(attach_path_list);
        replyRequest.setAttach_paths(null);
        if (replyRequest.getReply_call_result().isEmpty()) {
            replyRequest.setReply_call_result(null);
        }

        replyRequest.setClient_id(PddAPIConfig.CLIENT_ID);

        replyRequest.setType("pdd.logistics.ticket.notify");
        long time = new Date().getTime() / 1000;
        replyRequest.setTimestamp(time);
        replyRequest.setSign(PddSignTool.generateSign(replyRequest, PddAPIConfig.CLIENT_SECRET));
        String resp = PddHttpTool.sendJsonPostGD(replyRequest);
        log.info("resp = {}", resp);

        JSONObject respObj = JSON.parseObject(resp);
        JSONObject respObject = respObj.getJSONObject("logistics_ticket_notify_response");
        if (respObject == null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "未收到回复");
        } else {
            GDTicketReplyRepsonse replyRepsonse = respObject.toJavaObject(GDTicketReplyRepsonse.class);
            log.info("replyRepsonse is_success:{}", replyRepsonse.getIs_success());
            GDReplyEntity gdReply = new GDReplyEntity();
            gdReply.setTicket_id(replyRequest.getTicket_id());
            gdReply.setDuty(replyRequest.getDuty());
            gdReply.setHandle_result(replyRequest.getHandle_result());
            gdReply.setSign_state(replyRequest.getSign_state());
            gdReply.setCompensate_state(replyRequest.getCompensate_state());
            gdReply.setCompensate_amount(replyRequest.getCompensate_state());
            gdReply.setExpress_dealer(replyRequest.getExpress_dealer());
            gdReply.setExpress_dealer_contact(replyRequest.getExpress_dealer_contact());
            gdReply.setReply_type(replyRequest.getReply_type());
            gdReply.setDuty(replyRequest.getDuty());
            gdReply.setHandle_result(replyRequest.getHandle_result());

            gdReplyImpl.save(gdReply);
            if (list != null) {
                for (String lists : list) {
                    GDReplyAttachmentEntity gdReplyAttachmentEntity = new GDReplyAttachmentEntity();
                    gdReplyAttachmentEntity.setTicket_id(replyRequest.getTicket_id());
                    gdReplyAttachmentEntity.setWaybill_no(replyRequest.getWaybill_no());
                    gdReplyAttachmentEntity.setUrl(lists);
                    gdReplyAttachmentEntity.setReplyId(gdReply.getUid());
                    gdReplyAttachmentImpl.save(gdReplyAttachmentEntity);
                }
            }


            return JsonResponse.generateLocalCommonSuccessResponse(replyRepsonse.getIs_success(), "");
        }


    }

    @PostMapping("/ticketFresh")
    public JSONObject freshFromPdd(HttpServletRequest request) {
        gdOperator.getGdTickets();
        return JsonResponse.generateLocalCommonSuccessResponse("", "OK");
    }

}
