package jnpf.attendance.event;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import jnpf.attendance.service.AttendanceDailyRuleService;
import jnpf.attendance.service.AttendanceGroupService;
import jnpf.constants.MessageTopicConstants;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.exception.ApproveException;
import jnpf.exception.HandleException;
import jnpf.model.attendance.dto.AttendanceSecondedDto;
import jnpf.model.personnels.dto.secondment.msg.SecondmentMsgUserInfo;
import jnpf.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 借调申请消息
 */
@Component
@RocketMQMessageListener(
        topic = MessageTopicConstants.PERSONNEL_SECONDMENT_TOPIC,
        consumerGroup = MessageTopicConstants.SECONDMENT_GROUP,
        replyTimeout = 600000,
        nameServer = "${spring.cloud.stream.rocketmq.binder.name-server}"
)
@Slf4j
public class SecondmentConsumerMQListener implements RocketMQListener<String> {
    @Resource
    private AttendanceDailyRuleService attendanceDailyRuleService;
    @Autowired
    private AttendanceGroupService attendanceGroupService;

    @Override
    public void onMessage(String message) {
        if (StringUtil.isEmpty(message)) {
            return;
        }
        log.error("接受借调申请信息{}", message);
        try {
            SecondmentMsgUserInfo messageList = JSONUtil.toBean(message, SecondmentMsgUserInfo.class);
            if (Objects.isNull(messageList)) {
                return;
            }
            if (StringUtil.equals(messageList.getOriginalOrganizationId(), messageList.getSecondedOrganizationId())) {
                return;
            }
            AttendanceSecondedDto bean = new AttendanceSecondedDto();
            bean.setBackTime(messageList.getSecondmentEndTime());
            bean.setDepartureTime(messageList.getSecondmentStartTime());
            bean.setStartTime(messageList.getSecondmentStartTime());
            bean.setEndTime(messageList.getSecondmentEndTime());
            bean.setUserIds(List.of(messageList.getUserId()));
            TenantDataSourceUtil.switchTenant(messageList.getTenantId());
            Map<String, String> org2grouopMap = attendanceGroupService.batchSaveGroupByOrgIds(messageList.getTenantId(), CollUtil.newArrayList(messageList.getOriginalOrganizationId(), messageList.getSecondedOrganizationId()));
            if (!org2grouopMap.containsKey(messageList.getOriginalOrganizationId()) || !org2grouopMap.containsKey(messageList.getSecondedOrganizationId())) {
                throw new ApproveException("组织不存在");
            }
            bean.setSelfGroupId(org2grouopMap.get(messageList.getOriginalOrganizationId()));
            bean.setGroupId(org2grouopMap.get(messageList.getSecondedOrganizationId()));
            try {
                attendanceGroupService.secondedStart(bean);
            } catch (HandleException e) {
                throw new ApproveException(e.getMessage());
            }
            //修改用户排班
            try {
                attendanceDailyRuleService.secondmentDailyRuleHandle(bean.getUserIds(), bean.getSelfGroupId(), bean.getGroupId(), bean.getStartTime(), bean.getEndTime(), bean.getDepartureTime(), bean.getBackTime(), messageList.getTenantId());
            } catch (HandleException e) {
                throw new ApproveException(e.getMessage());
            }
        } catch (Exception e) {
            log.error("消息解析异常: message={}", message, e);
        }

    }

}
