package com.jeelowcode.service.bpm.listener;

import com.jeelowcode.core.framework.entity.FormEntity;
import com.jeelowcode.core.framework.mapper.FormMapper;
import com.jeelowcode.core.framework.service.IDbformDataService;
import com.jeelowcode.core.framework.service.IFormService;
import com.jeelowcode.framework.utils.tool.NumberUtil;
import com.jeelowcode.framework.utils.tool.spring.SpringUtils;
import com.jeelowcode.service.bpm.controller.vo.instance.BpmProcessInstanceRespVO;
import com.jeelowcode.service.bpm.service.IBpmProcessInstanceService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Order(value = 999)
@Component
@ComponentScan("com.jeelowcode.module.biz.listener")
public class TestListener implements ExecutionListener{

    @Autowired
    private IBpmProcessInstanceService processInstanceService;

    @Autowired
    private IDbformDataService dbformDataService;

    @Autowired
    private IFormService iFormService;

    private static TestListener AU;

    @PostConstruct
    public void init(){
        AU = this;
    }


    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void notify(DelegateExecution execution) {
//        Map<String,Object> map = new HashMap<>();
//        //流程实例id
//        String processInstanceId = execution.getProcessInstanceId();
//        BpmProcessInstanceRespVO vo = AU.processInstanceService.getProcessInstanceVO(processInstanceId);
//        //获取到的自定义表单数据id
//        String id = vo.getFormVariables().get("id").toString();
//        //数据表id
//        Long formId = vo.getProcessDefinition().getFormId();
        FormEntity formEntity = SpringUtils.getBean(FormMapper.class).getById(NumberUtil.toLong("1962005768360239106"));


        //实例状态 （1:审批中, 2：审批通过, 3:审批不通过, 4:已取消）
       // Integer status = vo.getStatus();
        Map<String,Object> json = new HashMap<>();
//        json.put(ApproveStatusEnum.codeField, ApproveStatusEnum.APPROVED.getCode());
//        json.put(ApproveStatusEnum.nameField, ApproveStatusEnum.APPROVED.getDesc());
//        AU.dbformDataService.editJsonData(formId, new JSONObject(json));
        AU.dbformDataService.update(formEntity.getTableName(),"123",json);

    }

}
