package com.tofly.xrtygis.custom.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.tofly.api.message.MessageClient;
import com.tofly.api.message.MessageStateClient;
import com.tofly.pojo.message.Messagepush;
import com.tofly.pojo.message.Messagerecipient;
import com.tofly.xrtygis.custom.mq.em.MessageQueEnum;
import com.tofly.xrtygis.custom.mq.em.MessageSateEnum;
import com.tofly.xrtygis.custom.mq.exception.FeignException;
import com.tofly.xrtygis.custom.service.QuestionMsgService;
import com.tofly.xrtygis.em.Constant;
import com.tofly.xrtygis.entity.Questionmark;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * @author 20126
 */
@Service
public class QuestionMsgServiceImpl implements QuestionMsgService {

    @Autowired
    private MessageClient messageClient;
    @Autowired
    private MessageStateClient messageStateClient;

    @Value("${gis.dispatching.web.inspection}")
    private String dispatchingWebInspectionRouteIp;

    @Value("${gis.dispatching.app.inspection}")
    private String dispatchingAppInspectionRouteIp;

    /**
     * 疑问标识推送到消息表
     *
     * @param data json数据
     */
    @Override
    public boolean queMsgPush(String data) {
        Questionmark mark = JSONObject.parseObject(data, Questionmark.class);
        Long markId = mark.getId();
        Messagepush messagepush = new Messagepush();
        // 消息主题/消息类型/消息表名/消息表中id/路由地址跳转
        messagepush.setTopic(MessageQueEnum.REPORT_QUESTION.getTopic());
        messagepush.setType("0101");
        messagepush.setTableName(MessageQueEnum.REPORT_QUESTION.getTableName());
        messagepush.setTableId(markId);
        // 地址跳转
        messagepush.setRouteIp(dispatchingWebInspectionRouteIp);
        messagepush.setRouteIpApp(dispatchingAppInspectionRouteIp);
        // 消息与接收人信息处理
        return setMessageRecipient(messagepush,mark.getHandleUser());
    }

    private boolean setMessageRecipient(Messagepush push,Long userId){
        try {
            Long  messagePushId = messageClient.save(push).getResult();
            Messagerecipient messagerecipient = new Messagerecipient();
            messagerecipient.setMessageId(messagePushId);
            messagerecipient.setRecipient(userId);
            messagerecipient.setFlag(MessageSateEnum.MESSAGE_SATE_NO.getCode());
            Boolean resultState = messageStateClient.save(messagerecipient).getResult();
            if (null == push || !resultState) {
                throw new FeignException(Constant.FEIGN_MESSAGE_CLIENT_ERROR_CODE, Constant.FEIGN_MESSAGE_CLIENT_ERROR);
            }
        } catch (FeignException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return true;
    }
}
