package com.jeelowcode.module.biz.enhance;

import com.jeelowcode.core.framework.config.aspect.enhance.model.EnhanceContext;
import com.jeelowcode.core.framework.config.aspect.enhance.plugin.AfterAdvicePlugin;
import com.jeelowcode.core.framework.config.aspect.enhance.plugin.BeforeAdvicePlugin;
import com.jeelowcode.core.framework.config.btncommand.ButtonInvoker;
import com.jeelowcode.core.framework.config.btncommand.button.DetailsButtonCommand;
import com.jeelowcode.core.framework.config.btncommand.param.ButtonParamDetail;
import com.jeelowcode.core.framework.config.btncommand.receiver.ButtonReceiverDetail;
import com.jeelowcode.core.framework.config.btncommand.receiver.IButtonCommandReceiver;
import com.jeelowcode.framework.exception.JeeLowCodeException;
import com.jeelowcode.framework.plus.core.toolkit.CollectionUtils;
import com.jeelowcode.framework.plus.core.toolkit.StringUtils;
import com.jeelowcode.framework.utils.model.ResultDataModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 删除前校验
 */
@Slf4j
@Component("beforeDeleteEnhance")
public class BeforeDeleteEnhance implements BeforeAdvicePlugin {
    @Override
    public void execute(EnhanceContext enhanceContext) {

        Map<String, Object> params = enhanceContext.getParam().getParams();
        Long id = ((List<Long>) params.get("dataIdList")).get(0);

        params.put("id", id);//把id放到参数集合里面

        ButtonParamDetail buttonParam = new ButtonParamDetail();
        buttonParam.setDbFormId(enhanceContext.getParam().getDbFormId());
        buttonParam.setDataId(id);
        buttonParam.setParams(params);

        //执行者绑定参数
        IButtonCommandReceiver receiver = new ButtonReceiverDetail(buttonParam);

        //执行者和命令绑定
        DetailsButtonCommand command = new DetailsButtonCommand(receiver);

        //创建调用者
        ButtonInvoker<ResultDataModel> invoker = new ButtonInvoker();
        invoker.setButtonCommand(command);//调用者设置命令
        ResultDataModel resultDataModel = invoker.executeCommand();//调用者下发命令

        if (!CollectionUtils.isEmpty(resultDataModel.getRecords())) {
            if(Objects.isNull(resultDataModel.getRecords().get(0).get("approveStatus"))){
                return;
            }
            String status = resultDataModel.getRecords().get(0).get("approveStatus").toString();
            if (StringUtils.isNotEmpty(status) && !status.equals("0")) {
                throw new JeeLowCodeException("当前单据存在审批流程，不允许删除");
            }
        }

    }
}
