package com.ankaibei.workFlow.common.flow.online.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.ankaibei.workFlow.common.flow.base.service.BaseFlowOnlineService;
import com.ankaibei.workFlow.common.flow.model.FlowWorkOrder;
import com.ankaibei.workFlow.common.flow.util.FlowCustomExtFactory;
import com.ankaibei.workFlow.common.online.model.OnlineColumn;
import com.ankaibei.workFlow.common.online.model.OnlineTable;
import com.ankaibei.workFlow.common.online.model.constant.FieldKind;
import com.ankaibei.workFlow.common.online.service.OnlineOperationService;
import com.ankaibei.workFlow.common.online.service.OnlineTableService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;

/**
 * 在线表单和流程监听器进行数据对接时的服务实现类。
 *
 * @author Buzhanyi
 * @date 2022-09-25
 */
@Slf4j
@Service("flowOnlineBusinessServiceImpl")
public class FlowOnlineBusinessServiceImpl extends BaseFlowOnlineService {

    @Autowired
    private FlowCustomExtFactory flowCustomExtFactory;
    @Autowired
    private OnlineTableService onlineTableService;
    @Autowired
    private OnlineOperationService onlineOperationService;

    @PostConstruct
    public void doRegister() {
        flowCustomExtFactory.getOnlineBusinessDataExtHelper().setOnlineBusinessService(this);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateFlowStatus(FlowWorkOrder workOrder) {
        OnlineTable onlineTable = onlineTableService.getOnlineTableFromCache(workOrder.getOnlineTableId());
        if (onlineTable == null) {
            log.error("OnlineTableId [{}] doesn't exist while calling FlowOnlineBusinessServiceImpl.updateFlowStatus",
                    workOrder.getOnlineTableId());
            return;
        }
        String dataId = workOrder.getBusinessKey();
        for (OnlineColumn column : onlineTable.getColumnMap().values()) {
            if (ObjectUtil.equals(column.getFieldKind(), FieldKind.FLOW_FINISHED_STATUS)) {
                onlineOperationService.updateColumn(onlineTable, dataId, column, workOrder.getFlowStatus());
            }
            if (ObjectUtil.equals(column.getFieldKind(), FieldKind.FLOW_APPROVAL_STATUS)) {
                onlineOperationService.updateColumn(onlineTable, dataId, column, workOrder.getLatestApprovalStatus());
            }
        }
    }
}
