package com.hzs.third.mqcall.listener;

import cn.hutool.core.util.ReflectUtil;
import com.hzs.common.core.constant.RabbitMqConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.ELanguages;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.system.base.ITransactionServiceApi;
import com.hzs.system.base.dto.TransactionDTO;
import com.hzs.third.mq.dto.TransactionMqDTO;
import com.hzs.third.translate.dto.TranslateParam;
import com.hzs.third.translate.service.ITranslateService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 国际化翻译监听
 */
@Slf4j
@Component
public class TransactionListener {

    @Autowired
    private ITranslateService iTranslateService;

    @DubboReference
    ITransactionServiceApi iTransactionServiceApi;

    /**
     * 国际化全量翻译监听处理
     *
     * @param message
     * @param channel
     * @throws Exception
     */
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = RabbitMqConstants.TRANSLATE_EXCHANGE, type = "topic"),
            value = @Queue(value = RabbitMqConstants.TRANSLATE_QUEUE, durable = "true", autoDelete = "false"),
            key = RabbitMqConstants.TRANSLATE_KEY))
    @RabbitHandler
    public void onMessage(Message<TransactionMqDTO> message, Channel channel) throws Exception {
        // 手动应答
        Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
        channel.basicAck(deliveryTag, false);

        // 根据传入的ID获取翻译内容
        TransactionMqDTO transactionMqDto = message.getPayload();

        log.info("异步翻译入参信息：{}", transactionMqDto);

        // 调用服务查询翻译内容
        ELanguages fromLanguage = ELanguages.getLanguagesByColumn(transactionMqDto.getColumn());
        if (null == fromLanguage) {
            log.error("异步翻译来源语言不存在");
            return;
        }

        // 翻译内容
        String content = transactionMqDto.getColumnValue();
        // 翻译来源语言
        String from = fromLanguage.getApiKey();

        // 翻译目标语言列表
        List<String> toList = new ArrayList<>();
        if (StringUtils.isNotEmpty(transactionMqDto.getToApiKey())) {
            toList.add(transactionMqDto.getToApiKey());
        } else {
            for (ELanguages value : ELanguages.values()) {
                if (!value.getApiKey().equals(from)) {
                    toList.add(value.getApiKey());
                }
            }
        }

        if (StringUtils.isNotEmpty(content)) {
            // 调用三方服务处理成功
            Map<String, String> dataMap = iTranslateService.translate(TranslateParam.builder()
                    .from(from)
                    .to(toList)
                    .content(content)
                    .build());

            // 封装调用翻译服务入库内容
            TransactionDTO transactionDTO = new TransactionDTO();
            transactionDTO.setPkId(transactionMqDto.getPkId());
            ReflectUtil.setFieldValue(transactionDTO, fromLanguage.getColumn(), content);

            // 赋值入库并处理是否加入缓存
            for (String apiKey : toList) {
                ELanguages languages = ELanguages.getLanguagesByApiKey(apiKey);
                if (null != languages) {
                    String translateStr = dataMap.get(apiKey);

                    ReflectUtil.setFieldValue(transactionDTO, languages.getColumn(), translateStr);

                    log.info("{}", apiKey + ":" + translateStr);
                }
            }
            log.info("transactionDTO: {}", transactionDTO);

            R<Boolean> updateR = iTransactionServiceApi.updateTransactionSync(transactionDTO);
            if (!updateR.isSuccess()) {
                log.error("异步翻译调用翻译服务入库失败： {}", updateR.getMsg());
            }
        } else {
            log.warn("异步翻译内容为空");
        }
    }

}
