package com.clx.performance.listener.settle;

import com.alibaba.fastjson.JSON;
import com.clx.open.sdk.callback.OpenCallBackClient;
import com.clx.open.sdk.callback.message.SettlementOwnerDetailMessage;
import com.clx.order.enums.SyncPlatformEnum;
import com.clx.performance.config.ThirdAppConfig;
import com.clx.performance.constant.RabbitKeyConstants;
import com.clx.performance.dto.dts.DataTransportDTO;
import com.clx.performance.enums.DtsOperationTypeEnum;
import com.msl.common.result.Result;
import com.msl.common.utils.DtsMapConvertUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
@AllArgsConstructor
public class SettlementOwnerDetailDtsListener {

    private final ThirdAppConfig thirdAppConfig;



    @RabbitListener(queues = RabbitKeyConstants.CLX_PERFORMANCE_SETTLEMENT_OWNER_DETAIL_QUEUE)
    public void onMessage(Message message) {
        try {
            String msg = new String(message.getBody());
            log.info("DTS消息同步开始, database:clx_performance.settlement_owner_detail, msg:{}", msg);
            DataTransportDTO dataTransportDTO = JSON.parseObject(msg, DataTransportDTO.class);
            log.info("DTS消息同步开始, database:clx_performance.settlement_owner_detail, 实体:{}", dataTransportDTO);
            log.info("操作类型：{}",dataTransportDTO.getOperationType().getCode());
            SettlementOwnerDetailMessage before = DtsMapConvertUtil.convert(dataTransportDTO.getBeforeMap(), new SettlementOwnerDetailMessage());
            SettlementOwnerDetailMessage after = DtsMapConvertUtil.convert(dataTransportDTO.getAfterMap(), new SettlementOwnerDetailMessage());

            if(Objects.equals(DtsOperationTypeEnum.DELETE.getCode(),dataTransportDTO.getOperationType().getCode())){
                //数据删除
                log.info("删除:{}",before);
                return;
            }
            //违约结算单数据同步
            thirdpartySync(after);
        } catch (Exception e) {
            log.info("DTS消息同步失败, database:clx_performance.settlement_owner_detail, error:{}", e.getMessage());
        }
    }


    /**
     * 第三方同步
     */
    public void thirdpartySync(SettlementOwnerDetailMessage message){

        try{
            OpenCallBackClient openCallBackClient = thirdAppConfig.getOpenCallBackClient(SyncPlatformEnum.Source.NEW_OWNER_CLIENT.getCode().toString());
            log.info("货主运单计费同步:{}", message.getId());
            Result<?> result = openCallBackClient.encryptPost(JSON.toJSONString(message), message.topic());
            if (result.succeed()) {
                log.info("货主运单计费同步成功:{}", message.getId());


            }else{
                log.info("货主运单计费同步失败:{}", message.getId());
            }

        }catch (Exception e){

        }

    }

}
