package com.qmth.sop.business.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.sop.business.bean.result.FlowResult;
import com.qmth.sop.business.bean.result.FlowTaskResult;
import com.qmth.sop.business.entity.TFCustomFlow;
import com.qmth.sop.business.mapper.TFCustomFlowMapper;
import com.qmth.sop.business.service.TFCustomFlowService;
import com.qmth.sop.common.enums.TFCustomTypeEnum;
import com.qmth.sop.common.util.GsonUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * <p>
 * 自定义流程表 服务实现类
 * </p>
 *
 * @author wangliang
 * @since 2023-07-17
 */
@Service
public class TFCustomFlowServiceImpl extends ServiceImpl<TFCustomFlowMapper, TFCustomFlow>
        implements TFCustomFlowService {

    /**
     * 查询版本号
     *
     * @param orgId
     * @param flowName
     * @param type
     * @return
     */
    @Override
    public TFCustomFlow findMaxVersion(Long orgId, String flowName, TFCustomTypeEnum type) {
        return this.baseMapper.findMaxVersion(orgId, flowName, Objects.nonNull(type) ? type.name() : null);
    }

    /**
     * 查询流程部署信息
     *
     * @return
     */
    @Override
    public List<TFCustomFlow> findFlowDeploymentList() {
        List<TFCustomFlow> tfCustomFlowList = this.baseMapper.findFlowDeploymentList();
        if (!CollectionUtils.isEmpty(tfCustomFlowList)) {
            for (TFCustomFlow t : tfCustomFlowList) {
                List<String> setupList = new ArrayList<>();
                FlowResult flowResult = JSONObject.parseObject(t.getFlowProcessVar(), FlowResult.class);
                LinkedHashMap<String, FlowTaskResult> setupMap = flowResult.getSetupMap();
                for (Map.Entry<String, FlowTaskResult> entry : setupMap.entrySet()) {
                    FlowTaskResult flowTaskResult = GsonUtil.fromJson(GsonUtil.toJson(entry.getValue()),
                            FlowTaskResult.class);
                    if (flowTaskResult.getSetup().intValue() > 0) {
                        setupList.add(flowTaskResult.getTaskName());
                    }
                }
                setupList.add("已完结");
                t.setSetupList(setupList);
            }
        }
        return tfCustomFlowList;
    }

    /**
     * 获取流程版本信息
     *
     * @param type
     * @return
     */
    @Override
    public List<TFCustomFlow> findFlowVersion(TFCustomTypeEnum type) {
        return this.list(new QueryWrapper<TFCustomFlow>().lambda().eq(TFCustomFlow::getType, type)
                .orderByDesc(TFCustomFlow::getVersion));
    }
}
