package com.yida.data.form.apply.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yida.data.common.core.entity.applyForm.CoreApprovalProcess;
import com.yida.data.common.core.entity.applyForm.CoreApprovalProcessUser;
import com.yida.data.customForm.vo.apply.ApplyFormProcessSelectVO;
import com.yida.data.form.apply.mapper.CoreApplyFormApprovalProcessMapper;
import com.yida.data.form.apply.service.CoreApplyFormApprovalProcessService;
import com.yida.data.common.core.entity.applyForm.CoreApplyFormApprovalProcess;
import com.yida.data.form.apply.service.CoreApprovalProcessUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 申请表单对应的审核流程 Service
 *
 * @author ZYJ
 * @date 2023/11/21
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class CoreApplyFormApprovalProcessServiceImpl extends ServiceImpl<CoreApplyFormApprovalProcessMapper, CoreApplyFormApprovalProcess>
        implements CoreApplyFormApprovalProcessService {

    private final CoreApprovalProcessUserService coreApprovalProcessUserService;

    @Override
    public void saveApplyFormApprovalProcess(Long applyFormId, List<CoreApplyFormApprovalProcess> processList) {
        // 删除已存在的节点数据
        remove(Wrappers.lambdaQuery(new CoreApplyFormApprovalProcess())
                .eq(CoreApplyFormApprovalProcess::getApplyFormId, applyFormId));
        // 保存信息
        for (int i = 0; i < processList.size(); i++) {
            CoreApplyFormApprovalProcess process = processList.get(i);
            // 处理排序
            process.setSort(i);
            save(process);
        }
    }

    @Override
    public List<ApplyFormProcessSelectVO> listFormApprovalProcess(Long formId) {
        List<ApplyFormProcessSelectVO> list = baseMapper.listFormApprovalProcess(formId);
        // 处理审核人员信息
        list.forEach(vo -> {
            List<CoreApprovalProcessUser> processUserList = coreApprovalProcessUserService.list(Wrappers.lambdaQuery(new CoreApprovalProcessUser())
                    .eq(CoreApprovalProcessUser::getProcessId, vo.getApprovalProcessId()));
            if (CollUtil.isNotEmpty(processUserList)) {
                String names = processUserList.stream().map(CoreApprovalProcessUser::getName).collect(Collectors.joining("、"));
                vo.setApprovalUserName(names);
            }
        });
        return list;
    }
}
