package com.sifang.modules.taskdispatch.util;

import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.Service.CustomerEntryService;
import com.sifang.modules.flowable.service.ItemManageService;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sys.util.SpringUtils;
import org.apache.commons.lang.StringUtils;

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

public class BatchItem {

    private final List<Record> items;
    private final String formKey;
    private final String partnerId;

    public BatchItem(List<String> itemIds) {
        List<Record> itemManages = SpringUtils.getBean(ItemManageService.class).findByIds(itemIds);
        this.items = itemManages;
        Set<String> formKeys = itemManages.stream().map(e -> e.getStr("form_key")).collect(Collectors.toSet());
        if (formKeys.size() > 1) {
            throw new BusinessException("待办事项必须为同一审核类型！");
        }
        this.formKey = formKeys.iterator().next();

        Set<String> entryIds = itemManages.stream().map(e -> e.getStr("application_id")).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        List<Record> partnerInfoList = SpringUtils.getBean(CustomerEntryService.class).findPartnerInfoByIds(entryIds);
        Set<String> partnerIds = partnerInfoList.stream().map(e -> e.getStr("partner_id")).collect(Collectors.toSet());
        if (partnerIds.size() > 1) {
            throw new BusinessException("待办事项必须为同一资方！");
        }
        this.partnerId = partnerIds.iterator().next();
    }

    public List<Record> getItems() {
        return items;
    }

    public String getFormKey() {
        return formKey;
    }

    public String getPartnerId() {
        return partnerId;
    }
}
