package nc.bs.uapbd.util;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
import com.google.common.collect.Lists;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.pub.pa.PreAlertObject;
import nc.bs.pub.taskcenter.BgWorkingContext;
import nc.bs.pub.taskcenter.IBackgroundWorkPlugin;
import nc.itf.bd.cust.assign.ICustAssignService;
import nc.vo.bd.cust.CustomerVO;
import nc.vo.org.OrgVO;
import nc.vo.pub.BusinessException;

public class CustomerAssginBackgroundPlugin implements IBackgroundWorkPlugin {

	@Override
	public PreAlertObject executeTask(BgWorkingContext context) throws BusinessException {
		// 查询客户
		String whereSql = " ts>'2025-05-01 00:00:00' order by ts desc";

		List<CustomerVO> list = (List<CustomerVO>) new BaseDAO().retrieveByClause(CustomerVO.class, whereSql);
		if (list == null || list.size() == 0) {
			return null;
		}
		// 查询需要分配的业务单元
		OrgVO[] virtulaOrg = getVirtulaOrg();
		String[] orgPks = Arrays.stream(virtulaOrg).map(OrgVO::getPk_org).toArray(String[]::new);
		// 将客户按照100条进行拆分
		List<List<CustomerVO>> batches = Lists.partition(list, 50);
		for (int i = 0; i < batches.size(); i++) {
			List<CustomerVO> custList = batches.get(i);
			// 拿到客户编码
			String[] custPks = toPropertyArray(custList, CustomerVO::getPk_customer, String.class);
			((ICustAssignService) NCLocator.getInstance().lookup(ICustAssignService.class)).assignCustomerByPks(custPks,
					orgPks, (String[]) null);
		}
		// 调用接口进行分配
		return null;
	}

	public static <T, R> R[] toPropertyArray(List<T> list, Function<T, R> propertyExtractor, Class<R> clazz) {
		return list.stream().map(propertyExtractor)
				.toArray(size -> (R[]) java.lang.reflect.Array.newInstance(clazz, size));
	}

	/**
	 * 查询组织信息
	 *
	 * @author mzr
	 * @date 2025/05/29
	 */
	public OrgVO[] getVirtulaOrg() throws BusinessException {
		String groupID = InvocationInfoProxy.getInstance().getGroupId();
		// NCCForUAPLogger.debug("groupID = " + groupID);
		// enablestate 启用状态 isbusinessunit 是否业务单元数据
		String condition = "pk_group = '" + groupID + "' and ENABLESTATE = '2' and isbusinessunit='Y'";
		Collection<OrgVO> collection = (new BaseDAO()).retrieveByClause(OrgVO.class, condition, "code");
		return collection.toArray(new OrgVO[0]);
	}

}
