package cn.axzo.msg.center.message.service.todo;

import cn.axzo.msg.center.domain.entity.Todo;
import cn.axzo.msg.center.message.domain.param.PendingMessagePushParam;
import cn.axzo.msg.center.message.service.card.CardManager;
import cn.axzo.msg.center.service.dto.PeerPerson;
import cn.axzo.msg.center.service.dto.PersonDTO;
import cn.axzo.msg.center.service.enums.CardBizState;
import cn.axzo.msg.center.service.enums.CardState;
import cn.axzo.msg.center.service.pending.request.CardSendRequest;
import cn.axzo.msg.center.service.pending.request.CardStateInfo;
import cn.axzo.msg.center.service.pending.request.CardUpdatePresetButtonRequest;
import cn.axzo.msg.center.service.pending.request.CardUpdateStateRequest;
import cn.axzo.msg.center.service.pending.request.PresetButtonPressedRequest;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Sets;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author xudawei@axzo.cn
 * @date 2024/12/12
 * @desc 待办与卡片关联包装
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TodoWithCardWrapper {

    private final CardManager cardManager;

    private static final String APP_CODE = "msg-center";

    /**
     * 点击预设按钮-同步卡片
     */
    public void fireCardWhenPresetButtonPressedByTodo(PresetButtonPressedRequest request, Todo todo) {
        log.info("TodoWithCardWrapper#fireCardWhenPresetButtonPressedByTodo start,request:{},todo:{}", JSON.toJSONString(request), JSON.toJSONString(todo));
        try {
            //1 构建对象
            CardUpdatePresetButtonRequest cardRequest = this.buildCardUpdatePresetButtonRequest(request, todo);
            //2 同步卡片
            cardManager.firePresetButtonPressed(cardRequest);
        } catch (Exception e) {
            log.warn("TodoWithCardWrapper#fireCardWhenPresetButtonPressedByTodo exception,request:{},todo:{}", JSON.toJSONString(request), JSON.toJSONString(todo),e);
        }
    }

    /**
     * 构建对象
     */
    private CardUpdatePresetButtonRequest buildCardUpdatePresetButtonRequest(PresetButtonPressedRequest request, Todo todo) {
        CardUpdatePresetButtonRequest cardRequest = new CardUpdatePresetButtonRequest();
        cardRequest.setAppCode(APP_CODE);
        cardRequest.setTemplateCode(todo.getTemplateCode());
        cardRequest.setBizCode(todo.getBizCode());
        cardRequest.setSubBizCode(todo.getSubBizCode());
        cardRequest.setReceivers(Sets.newHashSet(
                PeerPerson.newPeerPerson(todo.getExecutorPersonId()
                        , todo.getOuId()
                        , todo.getReceiverWorkspaceId())));

        cardRequest.setPresetButtonType(request.getPresetButtonType());
        cardRequest.setOperatorId(request.getOperatorId());
        return cardRequest;
    }

    /**
     * 发送卡片信息
     */
    public void send(PendingMessagePushParam param) {
        log.info("TodoWithCardWrapper#send start,param:{}", JSON.toJSONString(param));
        try {
            //1 构建对象
            CardSendRequest cardSendRequest = this.buildCardSendRequest(param);
            //2 发送
            cardManager.send(cardSendRequest);
        } catch (Exception e) {
            log.warn("TodoWithCardWrapper#send,param:{}", JSON.toJSONString(param), e);
        }
    }

    /**
     * 卡片更新状态-完成
     */
    public void cardCompleteStateByTodoList(List<Todo> todoList) {
        this.cardUpdateStateByTodoList(todoList,CardBizState.END.getCode(), CardState.COMPLETED);
    }

    /**
     * 卡片更新状态-回滚
     * 暂时不需要
     */
    public void cardRollbackStateByTodoList(List<Todo> todoList) {
        this.cardUpdateStateByTodoList(todoList, CardBizState.ABORTED.getCode(), CardState.CREATED);
    }

    /**
     * 卡片更新状态-撤销
     */
    public void cardRevokeStateByTodoList(List<Todo> todoList) {
        this.cardUpdateStateByTodoList(todoList, CardBizState.REVOKED.getCode(), CardState.CREATED);
    }

    /**
     * 卡片更新状态-执行中
     */
    public void cardProcessingStateByTodoList(List<Todo> todoList) {
        this.cardUpdateStateByTodoList(todoList, CardBizState.PENDING.getCode(), CardState.CREATED);
    }

    /**
     * 卡片更新完成状态
     */
    private void cardUpdateStateByTodoList(List<Todo> todoList, String bizState, CardState cardState) {
        log.info("TodoWithCardWrapper#cardUpdateStateByTodoList start,todoList:{},bizState:{},cardState:{}", JSON.toJSONString(todoList), bizState, cardState);
        try {
            //1 构建对象
            List<CardUpdateStateRequest> list = this.buildCardStateByTodoList(todoList,bizState, cardState);
            for (CardUpdateStateRequest request : list) {
                //2 更新状态
                cardManager.updateState(request);
            }
        } catch (Exception e) {
            log.warn("TodoWithCardWrapper#cardCompleteState,todoList:{}", JSON.toJSONString(todoList), e);
        }
    }

    /**
     * 构建卡片完成状态
     */
    private List<CardUpdateStateRequest> buildCardStateByTodoList(List<Todo> todoList, String bizState, CardState cardState) {
        if (CollectionUtils.isNotEmpty(todoList)) {
            return Lists.newArrayList();
        }
        List<CardUpdateStateRequest> list = Lists.newArrayList();
        for (Todo todo : todoList) {
            CardUpdateStateRequest updateStateRequest = new CardUpdateStateRequest();

            CardStateInfo cardStateInfo
                    = CardStateInfo.buildCardStateInfo(bizState, cardState);
            updateStateRequest.setStateInfo(cardStateInfo);

            updateStateRequest.setAppCode(APP_CODE);
            updateStateRequest.setTemplateCode(todo.getTemplateCode());
            updateStateRequest.setBizCode(todo.getBizCode());
            updateStateRequest.setSubBizCode(todo.getSubBizCode());
            updateStateRequest.setReceivers(Sets.newHashSet(PeerPerson.newPeerPerson(todo.getExecutorPersonId(), todo.getOuId(), todo.getReceiverWorkspaceId())));//TODO

            list.add(updateStateRequest);
        }
        return list;
    }

    /**
     * 构建对象
     */
    private CardSendRequest buildCardSendRequest(PendingMessagePushParam param) {
        CardSendRequest sendRequest = new CardSendRequest();
        sendRequest.setAppCode(APP_CODE);
        sendRequest.setTemplateCode(param.getTemplateCode());
        sendRequest.setBizCode(param.getBizCode());
        sendRequest.setSubBizCode(param.getSubBizCode());
        sendRequest.setSender(PeerPerson.newPeerPerson(param.getPromoter().getId()
                , param.getPromoterOuId()
                , param.getPromoterWorkspaceId()));
        sendRequest.setReceivers(this.buildReceivers(param.getExecutor(), param.getOuId(), param.getWorkspaceId()));
        if (StringUtils.isNotBlank(param.getBizExtParams())) {
            sendRequest.setBizParam(JSON.parseObject(param.getBizExtParams()));
        }
        if (StringUtils.isNotBlank(param.getRouterParams())) {
            sendRequest.setRouterParam(JSON.parseObject(param.getRouterParams()));
        }
        sendRequest.setStateInfo(CardStateInfo.buildCardStateInfo(CardBizState.PENDING.getCode(), CardState.CREATED));

        return sendRequest;
    }

    private Set<PeerPerson> buildReceivers(List<PersonDTO> personDTOS, Long ouId, Long workspaceId) {
        if (CollectionUtils.isNotEmpty(personDTOS)) {
            return Sets.newHashSet();
        }
        return personDTOS.stream().map(item -> PeerPerson.newPeerPerson(item.getId(), ouId, workspaceId)).collect(Collectors.toSet());
    }


}
