package com.tofly.scada.util;

import com.tofly.api.UserTaskClient;
import com.tofly.api.message.MessageClient;
import com.tofly.api.message.MessageStateClient;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.pojo.message.Messagepush;
import com.tofly.pojo.message.Messagerecipient;
import com.tofly.pojo.message.Usertask;
import com.tofly.scada.common.FlowConstant;
import com.tofly.scada.entity.MessagepushW;
import com.tofly.scada.entity.MessagerecipientW;
import com.tofly.scada.entity.UsertaskW;
import com.tofly.scada.mapper.MessagerecipientWMapper;
import com.tofly.scada.service.MessagepushWService;
import com.tofly.scada.service.UsertaskWService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class SendTidingsUtil {
    @Autowired
    private MessageClient messageClient;
    @Autowired
    private MessageStateClient messageStateClient;
    @Autowired
    private UserTaskClient userTaskClient;

    @Autowired
    private MessagepushWService messagepushWService;

    @Autowired
    private MessagerecipientWMapper messagerecipientWMapper;

    @Autowired
    private UsertaskWService usertaskWService;


    /**
     * 自定义发送消息及待办信息
     *
     * @param messagepush 消息信息
     * @param userId      处理人
     */
    public void sendMsg(MessagepushW messagepush, Long userId) {
        this.sendMsg(messagepush, userId, null, false);
    }


    /**
     * 自定义发送消息及待办信息
     *
     * @param messagepush 消息信息
     * @param userId      处理人
     * @param endDate     处理结束时间
     * @param isTask      是否送待办信息
     */
    public void sendMsg(MessagepushW messagepush, Long userId, Date endDate, boolean isTask) {
        log.info("输出路由地址:" + messagepush.getRouteIp());
        try {
            messagepushWService.save(messagepush);
            Long messagePushId = messagepush.getId();
            MessagerecipientW messagerecipient = new MessagerecipientW();
            messagerecipient.setMessageId(messagePushId);
            messagerecipient.setRecipient(userId);
            messagerecipient.setFlag(FlowConstant.FLAG);
            int resultState = messagerecipientWMapper.insertSelective(messagerecipient);
            if (isTask) {
                UsertaskW usertask = new UsertaskW();
                if (endDate != null) {
                    usertask.setEndTime(endDate);
                    usertask.setStartTime(new Date());
                }
                usertask.setTknm(messagepush.getTopic());
                usertask.setTkty(messagepush.getType());
                usertask.setTableName(messagepush.getTableName());
                usertask.setTableId(messagepush.getTableId());
                usertask.setIshandle("0");
                usertask.setRouteIp(messagepush.getRouteIp());
                usertask.setRouteAppIp(messagepush.getRouteIpApp());
                usertask.setHandleUser(userId);
                usertaskWService.save(usertask);
                log.info("输出未处理任务路由地址：" + usertask.getRouteIp());
            }
            if (Objects.isNull(messagepush) || resultState == 0) {
                throw new RuntimeException(FlowConstant.TIDINGS_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }

    /**
     * 发送消息
     *
     * @param messagepush 消息信息
     * @param userId      处理人
     */
    public void setMessageRecipient(Messagepush messagepush, Long userId) {
        this.setMessageRecipient(messagepush, userId, null, false);
    }

    /**
     * 发送消息及待办信息
     *
     * @param messagepush 消息信息
     * @param userId      处理人
     * @param endDate     处理结束时间
     */
    public void setMessageRecipient(Messagepush messagepush, Long userId, Date endDate) {
        this.setMessageRecipient(messagepush, userId, endDate, true);
    }

    /**
     * 发送消息及待办信息
     *
     * @param messagepush 消息信息
     * @param userId      处理人
     * @param endDate     处理结束时间
     * @param isTask      是否送待办信息
     */
    public void setMessageRecipient(Messagepush messagepush, Long userId, Date endDate, boolean isTask) {
        log.info("输出路由地址:" + messagepush.getRouteIp());
        try {
            Long messagePushId = messageClient.save(messagepush).getResult();
            Messagerecipient messagerecipient = new Messagerecipient();
            messagerecipient.setMessageId(messagePushId);
            messagerecipient.setRecipient(userId);
            messagerecipient.setFlag(FlowConstant.FLAG);
            Boolean resultState = messageStateClient.save(messagerecipient).getResult();
            if (isTask) {
                Usertask usertask = new Usertask();
                if (endDate != null) {
                    usertask.setEndTime(endDate);
                    usertask.setStartTime(new Date());
                }
                usertask.setTknm(messagepush.getTopic());
                usertask.setTkty(messagepush.getType());
                usertask.setTableName(messagepush.getTableName());
                usertask.setTableId(messagepush.getTableId());
                usertask.setIshandle("0");
                usertask.setRouteIp(messagepush.getRouteIp());
                usertask.setRouteAppIp(messagepush.getRouteIpApp());
                usertask.setHandleUser(userId);
                userTaskClient.save(usertask);
                log.info("输出未处理任务路由地址：" + usertask.getRouteIp());
            }
            if (Objects.isNull(messagepush) || !resultState) {
                throw new RuntimeException(FlowConstant.TIDINGS_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
           log.error(e.getMessage());
        }
    }


    public Messagepush getMessage(Long id, String message, String topic) {
        Messagepush messagepush = new Messagepush();
        messagepush.setTableId(id);
        messagepush.setMessage(message);
        messagepush.setTopic(topic);
        messagepush.setTableName(FlowConstant.PROCESS_TABLE_NAMEU);
        messagepush.setType(FlowConstant.STRING_ELEVEN);
        return messagepush;
    }


    /**
     * 消除待办
     *
     * @param gdglinfoId 工单id
     * @param topic      业务——处理环节
     */
    public void removeDB(Long gdglinfoId, String topic) {
        // 待办事项处理状态置为完成
        // 待办事项处理
        Usertask usertask = new Usertask();
        usertask.setTableName(FlowConstant.PROCESS_TABLE_NAMEU);
        usertask.setTknm(topic);
        usertask.setTableId(gdglinfoId);
        usertask.setIshandle("0");

        List<Usertask> result = userTaskClient.getUserTaskInfo(usertask).getResult();
        if (null != result && result.size() > 0) {
            for (Usertask task : result) {
                task.setHandleTime(new Date());
                task.setHandleUser(SecurityUtils.getUserId());
                task.setIshandle("1");
                userTaskClient.updateById(task);
            }
        }
    }

    /**
     * 消除待办
     *
     * @param gdglinfoId 工单id
     */
    public void removeDB(Long gdglinfoId) {
        // 待办事项处理状态置为完成
        // 待办事项处理
        this.removeDB(gdglinfoId, null);
    }

}
