package nccloud.api.uapbd.customer.tms.listener.kejian;

import com.alibaba.fastjson.JSONObject;
import nc.bs.bd.baseservice.ArrayClassConvertUtil;
import nc.bs.businessevent.IBusinessEvent;
import nc.bs.businessevent.IBusinessListener;
import nc.bs.businessevent.bd.BDCommonEvent;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.uapbd.util.BaseOpenApiReq;
import nc.jdbc.framework.processor.ColumnListProcessor;
import nc.vo.bd.cust.CustomerVO;
import nc.vo.org.OrgVO;
import nc.vo.pub.BusinessException;
import nccloud.baseapp.core.log.NCCForUAPLogger;
import nccloud.vo.sql.util.InSqlUtil;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * 创建客户后，自动分配组织
 *
 * @author mzr
 * @date 2025/06/16
 */
public class AssignCustomerListener implements IBusinessListener {
    @Override
    public void doAction(IBusinessEvent event) throws BusinessException {
        BDCommonEvent e = (BDCommonEvent) event;
        Object[] objs = e.getObjs();
        CustomerVO[] useVOs = ArrayClassConvertUtil.convert(objs, CustomerVO.class);
        for (CustomerVO customerVO : useVOs) {
            assignOrgApi(customerVO);
        }
    }

    public void assignOrgApi(CustomerVO customerVO) throws BusinessException {
        String[] customerPks = {customerVO.getPk_customer()};
        String sql = "select code from bd_customer where pk_customer = '[pk_customer]'";
        sql = sql.replace("[pk_customer]", customerVO.getPk_customer());
        List<String> pks = (List) (new BaseDAO()).executeQuery(sql, new ColumnListProcessor());
        NCCForUAPLogger.debug("pks = " + pks);
        OrgVO[] virtulaOrg = getVirtulaOrg();
        String[] assignOrgPks = Arrays.stream(virtulaOrg).map(OrgVO::getPk_org).toArray(String[]::new);
        JSONObject param = new JSONObject();
        JSONObject ufinterfaceJson = new JSONObject();
        JSONObject dataJson = new JSONObject();
        dataJson.put("customer", customerPks);
        dataJson.put("org", assignOrgPks);

        ufinterfaceJson.put("sender", "default");
        ufinterfaceJson.put("data", dataJson);
        param.put("ufinterface", ufinterfaceJson);
        BaseOpenApiReq req = new BaseOpenApiReq();
        req.assignOrgApi("/nccloud/api/uapbd/customermanageext/customer/assignByPk", param);
    }

    /**
     * 查询组织信息
     *
     * @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]);
    }
}
