//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package nc.bs.pub.action;

import com.alibaba.fastjson.JSONObject;
import nc.bs.bd.cust.baseinfo.validator.CustomerVersionValidator;
import nc.bs.bd.pub.util.BaseDocVoConvertUtil;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.json.core.exception.ExceptionUtils;
import nc.bs.pub.compiler.AbstractCompiler2;
import nc.bs.pub.compiler.IWorkFlowRet;
import nc.bs.pub.filesystem.IFileSystemService;
import nc.bs.uapbd.util.BaseOpenApiReq;
import nc.bs.uif2.validation.ValidationException;
import nc.bs.uif2.validation.ValidationFailure;
import nc.itf.bd.bankacc.cust.ICustBankaccQueryService;
import nc.itf.bd.bankacc.cust.ICustBankaccService;
import nc.itf.bd.bankacc.cust.ICustPfBankaccService;
import nc.itf.bd.cust.assign.ICustAssignService;
import nc.itf.bd.cust.baseinfo.ICustBaseInfoQueryService;
import nc.itf.bd.cust.baseinfo.ICustBaseInfoService;
import nc.itf.bd.cust.custaddress.ICustAddressQueryService;
import nc.itf.bd.cust.custaddress.ICustAddressService;
import nc.itf.bd.cust.pf.ICustPfAddressService;
import nc.itf.bd.cust.pf.ICustomerPfQueryService;
import nc.itf.bd.cust.pf.ICustomerPfService;
import nc.uap.utils.ResHelper;
import nc.vo.bd.bankaccount.cust.CustBankaccUnionVO;
import nc.vo.bd.cust.CustCountrytaxesVO;
import nc.vo.bd.cust.CustlinkmanVO;
import nc.vo.bd.cust.CustomerVO;
import nc.vo.bd.cust.custaddress.CustPfaddressVO;
import nc.vo.bd.cust.custaddress.CustaddressVO;
import nc.vo.bd.cust.pf.AggCustomerPfVO;
import nc.vo.bd.cust.pf.CustomerPfBaseVO;
import nc.vo.bd.cust.pf.CustomerPfVO;
import nc.vo.bd.meta.BatchOperateVO;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.org.OrgVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.BusinessRuntimeException;
import nc.vo.pub.compiler.PfParameterVO;
import nc.vo.uap.pf.PFBusinessException;
import nccloud.commons.lang.ArrayUtils;
import nccloud.pubitf.baseapp.apprbac.IDataPermPubService4NCC;
import nccloud.pubitf.platform.attachment.IAttachmentService;
import nccloud.pubitf.uapbd.forrpbill.IUapbd4RPbillSyncService;

import java.util.*;

public class N_10KH_APPROVE extends AbstractCompiler2 {
    public N_10KH_APPROVE() {
    }

    public Object runComClass(PfParameterVO vo) throws BusinessException {
        try {
            super.m_tmpVo = vo;
            String cuserid = InvocationInfoProxy.getInstance().getUserId();
            String pk_group = InvocationInfoProxy.getInstance().getGroupId();
            IDataPermPubService4NCC dataPerService = (IDataPermPubService4NCC) NCLocator.getInstance().lookup(IDataPermPubService4NCC.class);
            boolean userHasPermission = dataPerService.isUserHasPermission(cuserid, "customerpf", "approve", pk_group, ((AggCustomerPfVO) this.getVo()).getParentVO());
            if (!userHasPermission) {
                ExceptionUtils.wrapBusinessException(ResHelper.getString("nccriauapbd0", "0nccriauapbd00215"));
            }

            IWorkFlowRet woekFlowRet = (IWorkFlowRet) this.procActionFlow(vo);
            ICustomerPfService pfService = (ICustomerPfService) NCLocator.getInstance().lookup(ICustomerPfService.class);
            ICustomerPfQueryService qryPfService = (ICustomerPfQueryService) NCLocator.getInstance().lookup(ICustomerPfQueryService.class);
            if (woekFlowRet == null) {
                CustomerPfVO pfvo = (CustomerPfVO) ((AggCustomerPfVO) this.getVo()).getParentVO();
                CustomerPfBaseVO baseVO = qryPfService.queryCustomerPfBaseVOByPk(pfvo.getPk_customerpf_base());
                CustomerVO customer = BaseDocVoConvertUtil.customerPfBaseVO2CustomerVO(baseVO);
                customer.setPk_customerpf(pfvo.getPrimaryKey());

                try {
                    Integer applyType = pfvo.getApply_type();
                    if (applyType != 2 && applyType != 5) {
                        customer.setIsCreateCust(-1);
                        CustCountrytaxesVO[] curTaxVOs = customer.getCusttaxtypes();
                        if (curTaxVOs != null) {
                            for (CustCountrytaxesVO taxVO : curTaxVOs) {
                                taxVO.setStatus(2);
                            }
                        }

                        CustlinkmanVO[] curLinkmanVOs = customer.getCustcontacts();
                        if (curLinkmanVOs != null) {
                            for (CustlinkmanVO linkVO : curLinkmanVOs) {
                                linkVO.setStatus(2);
                            }
                        }

                        customer = ((ICustBaseInfoService) NCLocator.getInstance().lookup(ICustBaseInfoService.class)).insertCustomerVO(customer, true);
                        // 分配客户的组织
                        String[] customerPks = {customer.getPk_customer()};
                        OrgVO[] virtulaOrg = getVirtulaOrg();
                        String[] assignOrgPks = Arrays.stream(virtulaOrg).map(OrgVO::getPk_org).toArray(String[]::new);
                        NCLocator.getInstance().lookup(ICustAssignService.class).assignCustomerByPks(customerPks, assignOrgPks, null);

                        ICustBankaccService uptBankService = (ICustBankaccService) NCLocator.getInstance().lookup(ICustBankaccService.class);
                        CustBankaccUnionVO[] newUnionVOs = ((ICustPfBankaccService) NCLocator.getInstance().lookup(ICustPfBankaccService.class)).queryCustBankaccUnionVOsByCustAndPfType(customer.getPk_customer(), 1, 1);
                        uptBankService.insertCustBankaccs(newUnionVOs);
                        this.dealCustAddress(customer);
                    } else {
                        customer.setTs(baseVO.getOldts());
                        CustomerVersionValidator custversion = new CustomerVersionValidator(pfvo);
                        ValidationFailure vfail = custversion.validate(customer);
                        if (vfail != null) {
                            List<ValidationFailure> fs = new ArrayList();
                            fs.add(vfail);
                            throw new ValidationException(fs);
                        }

                        ICustBaseInfoService service = (ICustBaseInfoService) NCLocator.getInstance().lookup(ICustBaseInfoService.class);
                        this.dealCustomerBank(customer);
                        this.dealCustAddressOfEditOrVersion(customer, applyType);
                        customer.setStatus(1);
                        ICustBaseInfoQueryService qryService = (ICustBaseInfoQueryService) NCLocator.getInstance().lookup(ICustBaseInfoQueryService.class);
                        CustomerVO originVO = qryService.queryDataByPkSet(new String[]{customer.getPk_customer()})[0];
                        this.dealCountryTaxesVO(customer, originVO);
                        this.dealLinkManVO(customer, originVO);
                        if (applyType == 5) {
                            service.createCustomerVersion(customer);
                        } else {
                            service.updateCustomerVO(customer, false);
                        }
                    }

                    if (applyType == 1 || applyType == 2) {
                        if (applyType == 2) {
                            String applyRootPath = "uapbd/e4f48eaf-5567-4383-a370-a59cb3e8a451/" + customer.getPrimaryKey();
                            IFileSystemService fileMngService = (IFileSystemService) NCLocator.getInstance().lookup(IFileSystemService.class);
                            fileMngService.deleteNCFileNode(applyRootPath);
                        }

                        String rootPath = "uapbd/6d6d4a15-d9bb-4b0c-9da3-80760872bf87/" + pfvo.getPrimaryKey();
                        String destDirPath = "uapbd/e4f48eaf-5567-4383-a370-a59cb3e8a451/" + customer.getPrimaryKey();
                        IAttachmentService aService = (IAttachmentService) NCLocator.getInstance().lookup(IAttachmentService.class);
                        aService.copyTo(rootPath, destDirPath);
                    }
                } catch (BusinessException e) {
                    String msg = NCLangRes4VoTransl.getNCLangRes().getStrByID("10140custsup", "010140custsup0061", (String) null, new String[]{e.getMessage()});
                    throw new BusinessRuntimeException(msg, e);
                }

                CustomerPfBaseVO pfBaseVO = qryPfService.queryCustomerPfBaseVOByPk(pfvo.getPk_customerpf_base());
                pfBaseVO.setCode(customer.getCode());
                pfBaseVO.setPk_customer_v(customer.getPk_customer_v());
                pfvo.setCustomercode(customer.getCode());
                pfvo.setMemo((String) null);
                pfvo = pfService.updateCustomerPfVOByActionWithBaseInfo("approve", pfvo, pfBaseVO);
                // this.assignCustomerToOrg(pfvo, customer);
                this.getVo().setParentVO(pfvo);
                ((IUapbd4RPbillSyncService) NCLocator.getInstance().lookup(IUapbd4RPbillSyncService.class)).syncData("10KH", this.getVo(), "Approve");
                return this.getVo();
            } else {
                CustomerPfVO pfvo = (CustomerPfVO) ((AggCustomerPfVO) woekFlowRet.m_inVo).getParentVO();
                pfvo = pfService.updateCustomerPfVOByAction("unapprove", pfvo);
                ((AggCustomerPfVO) woekFlowRet.m_inVo).setParentVO(pfvo);
                return woekFlowRet;
            }
        } catch (Exception ex) {
            if (ex instanceof BusinessException) {
                throw (BusinessException) ex;
            } else {
                throw new PFBusinessException(ex.getMessage(), ex);
            }
        }
    }

    private void dealCustomerBank(CustomerVO customer) throws BusinessException {
        ICustBankaccQueryService bankQryService = (ICustBankaccQueryService) NCLocator.getInstance().lookup(ICustBankaccQueryService.class);
        CustBankaccUnionVO[] originVOs = bankQryService.queryCustBankaccUnionVOsByCust(customer.getPk_customer(), 1, true);
        CustBankaccUnionVO[] applyBankVOs = ((ICustPfBankaccService) NCLocator.getInstance().lookup(ICustPfBankaccService.class)).queryCustBankaccUnionVOsByCustAndPfType(customer.getPk_customer(), 1, 1);
        Map<String, CustBankaccUnionVO> bankMap = new HashMap();
        if (originVOs != null) {
            for (CustBankaccUnionVO bankVO : originVOs) {
                bankMap.put(bankVO.getBankaccbasVO().getPrimaryKey(), bankVO);
            }
        }

        Map<String, CustBankaccUnionVO> newBankMap = new HashMap();
        List<CustBankaccUnionVO> insertBankList = new ArrayList();
        List<CustBankaccUnionVO> updateBankList = new ArrayList();
        List<CustBankaccUnionVO> deleteBankList = new ArrayList();
        if (applyBankVOs != null) {
            for (CustBankaccUnionVO bankVO : applyBankVOs) {
                String key = bankVO.getBankaccbasVO().getPrimaryKey();
                newBankMap.put(key, bankVO);
                if (bankMap.containsKey(key)) {
                    updateBankList.add(bankVO);
                } else {
                    bankVO.getCustbankVO().setPk_cust(customer.getPk_customer());
                    insertBankList.add(bankVO);
                }
            }
        }

        if (originVOs != null) {
            for (CustBankaccUnionVO bankVO : originVOs) {
                if (!newBankMap.containsKey(bankVO.getBankaccbasVO().getPrimaryKey())) {
                    deleteBankList.add(bankVO);
                }
            }
        }

        ICustBankaccService uptBankService = (ICustBankaccService) NCLocator.getInstance().lookup(ICustBankaccService.class);
        if (insertBankList.size() > 0) {
            uptBankService.insertCustBankaccs((CustBankaccUnionVO[]) insertBankList.toArray(new CustBankaccUnionVO[0]));
        }

        if (updateBankList.size() > 0) {
            uptBankService.updateCustBankaccsFromPf((CustBankaccUnionVO[]) updateBankList.toArray(new CustBankaccUnionVO[0]));
        }

    }

    private void dealCustAddress(CustomerVO customer) throws BusinessException {
        CustPfaddressVO[] pfAddressVOs = ((ICustPfAddressService) NCLocator.getInstance().lookup(ICustPfAddressService.class)).queryCustPfaddressVOs(customer.getPk_customer());
        if (!ArrayUtils.isEmpty(pfAddressVOs)) {
            List<CustaddressVO> list = new ArrayList();

            for (CustPfaddressVO pfAddressVO : pfAddressVOs) {
                CustaddressVO addressVO = (CustaddressVO) BaseDocVoConvertUtil.convertVO(pfAddressVO, new CustaddressVO());
                list.add(addressVO);
            }

            BatchOperateVO bovo = new BatchOperateVO();
            bovo.setAddObjs(list.toArray(new CustaddressVO[0]));
            ((ICustAddressService) NCLocator.getInstance().lookup(ICustAddressService.class)).batchSaveCashAccount(bovo);
        }
    }

    private void dealCustAddressOfEditOrVersion(CustomerVO customer, Integer applyType) throws Exception {
        String pk_group = InvocationInfoProxy.getInstance().getGroupId();
        String var10000 = customer.getPk_customer();
        String condition = "pk_customer = '" + var10000 + "' and pk_org = '" + pk_group + "'";
        CustaddressVO[] custaddressVOs = ((ICustAddressQueryService) NCLocator.getInstance().lookup(ICustAddressQueryService.class)).queryCustAddressVOsByCondition(condition);
        if (custaddressVOs != null && custaddressVOs.length > 0) {
            BatchOperateVO bovo = new BatchOperateVO();
            bovo.setDelObjs(custaddressVOs);
            ((ICustAddressService) NCLocator.getInstance().lookup(ICustAddressService.class)).batchSaveCashAccount(bovo);
        }

        CustPfaddressVO[] pfAddressVOs = ((ICustPfAddressService) NCLocator.getInstance().lookup(ICustPfAddressService.class)).queryCustPfaddressVOs(customer.getPk_customer());
        if (!ArrayUtils.isEmpty(pfAddressVOs)) {
            List<CustaddressVO> list = new ArrayList();

            for (CustPfaddressVO pfAddressVO : pfAddressVOs) {
                CustaddressVO addressVO = (CustaddressVO) BaseDocVoConvertUtil.convertVO(pfAddressVO, new CustaddressVO());
                list.add(addressVO);
            }

            BatchOperateVO bov = new BatchOperateVO();
            bov.setAddObjs(list.toArray(new CustaddressVO[0]));
            ((ICustAddressService) NCLocator.getInstance().lookup(ICustAddressService.class)).batchSaveCashAccount(bov);
        }
    }

    private void dealCountryTaxesVO(CustomerVO customer, CustomerVO originVO) {
        CustCountrytaxesVO[] originTaxVOs = originVO.getCusttaxtypes();
        Map<String, CustCountrytaxesVO> oldTaxMap = new HashMap();
        if (originTaxVOs != null) {
            for (CustCountrytaxesVO taxVO : originTaxVOs) {
                oldTaxMap.put(taxVO.getPrimaryKey(), taxVO);
            }
        }

        CustCountrytaxesVO[] curTaxVOs = customer.getCusttaxtypes();
        Map<String, CustCountrytaxesVO> taxMap = new HashMap();
        List<CustCountrytaxesVO> taxList = new ArrayList();
        if (curTaxVOs != null) {
            for (CustCountrytaxesVO taxVO : curTaxVOs) {
                if (oldTaxMap.containsKey(taxVO.getPrimaryKey())) {
                    taxVO.setStatus(1);
                } else {
                    taxVO.setStatus(2);
                }

                taxMap.put(taxVO.getPrimaryKey(), taxVO);
                taxList.add(taxVO);
            }
        }

        if (originTaxVOs != null) {
            for (CustCountrytaxesVO taxVO : originTaxVOs) {
                if (!taxMap.containsKey(taxVO.getPrimaryKey())) {
                    taxVO.setStatus(3);
                    taxList.add(taxVO);
                }
            }
        }

        customer.setCusttaxtypes((CustCountrytaxesVO[]) taxList.toArray(new CustCountrytaxesVO[0]));
    }

    private void dealLinkManVO(CustomerVO customer, CustomerVO originVO) {
        CustlinkmanVO[] originLinkmanVOs = originVO.getCustcontacts();
        Map<String, CustlinkmanVO> oldLinkmanMap = new HashMap();
        if (originLinkmanVOs != null) {
            for (CustlinkmanVO linkmanVO : originLinkmanVOs) {
                oldLinkmanMap.put(linkmanVO.getPrimaryKey(), linkmanVO);
            }
        }

        CustlinkmanVO[] curLinkmanVOs = customer.getCustcontacts();
        Map<String, CustlinkmanVO> linkmanMap = new HashMap();
        List<CustlinkmanVO> linkmanList = new ArrayList();
        if (curLinkmanVOs != null) {
            for (CustlinkmanVO linkmanVO : curLinkmanVOs) {
                if (oldLinkmanMap.containsKey(linkmanVO.getPrimaryKey())) {
                    linkmanVO.setStatus(1);
                } else {
                    linkmanVO.setStatus(2);
                }

                linkmanMap.put(linkmanVO.getPrimaryKey(), linkmanVO);
                linkmanList.add(linkmanVO);
            }
        }

        if (originLinkmanVOs != null) {
            for (CustlinkmanVO linkmanVO : originLinkmanVOs) {
                if (!linkmanMap.containsKey(linkmanVO.getPrimaryKey())) {
                    linkmanVO.setStatus(3);
                    linkmanList.add(linkmanVO);
                }
            }
        }

        customer.setCustcontacts((CustlinkmanVO[]) linkmanList.toArray(new CustlinkmanVO[0]));
    }

    private void assignCustomerToOrg(CustomerPfVO pfvo, CustomerVO vo) throws BusinessException {
        if (this.isOrgData(vo)) {
            this.getAssignService().assignCustomerToSelfOrg(vo);
        } else {
            this.getAssignService().assignCustomerForPf(vo.getPk_customer(), pfvo.getPk_org(), (String[]) null);
        }

    }

    private boolean isOrgData(CustomerVO vo) {
        return !vo.getPk_group().equals(vo.getPk_org()) && !"GLOBLE00000000000000".equals(vo.getPk_org());
    }

    public void assignOrgApi(CustomerVO customerVO) throws BusinessException {
        String[] customerPks = {customerVO.getCode()};
        OrgVO[] virtulaOrg = getVirtulaOrg();
        String[] assignOrgPks = Arrays.stream(virtulaOrg).map(OrgVO::getCode).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/assign", 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]);
    }

    private ICustAssignService getAssignService() {
        return (ICustAssignService) NCLocator.getInstance().lookup(ICustAssignService.class);
    }

    public String getCodeRemark() {
        return "\tIWorkFlowRet woekFlowRet = (IWorkFlowRet) procActionFlow(vo);\n\t\t\tICustomerPfService pfService = NCLocator.getInstance().lookup(\n\t\t\t\t\tICustomerPfService.class);\n\t\t\tif (woekFlowRet == null) {\n\t\t\t\tCustomerPfVO pfvo = (CustomerPfVO) ((AggCustomerPfVO) getVo())\n\t\t\t\t\t\t.getParentVO();\n\t\t\t\tCustomerVO customer = (CustomerVO) pfvo.getCustomerinfo();\n\t\t\t\tcustomer.setPk_customerpf(pfvo.getPrimaryKey());\n\t\t\t\ttry {\n\t\t\t\t\tcustomer = NCLocator.getInstance().lookup(\n\t\t\t\t\t\t\tICustBaseInfoService.class).insertCustomerVO(\n\t\t\t\t\t\t\tcustomer, true);\n\t\t\t\t} catch (BusinessException e) {\n\t\t\t\t\tString msg = NCLangRes4VoTransl.getNCLangRes().getStrByID(\n\t\t\t\t\t\t\t\"10140custsup\", \"010140custsup0061\", null,\n\t\t\t\t\t\t\tnew String[] { e.getMessage() })/*@res 客户基本信息校验失败，详细信息如下：\n{0}*/;\n\t\t\t\t\tpfService.writeErrMsgToMemo_RequiresNew(pfvo\n\t\t\t\t\t\t\t.getPrimaryKey(), msg);\n\t\t\t\t\tthrow e;\n\t\t\t\t}\n\t\t\t\tpfvo.setCustomerinfo(customer);\n\t\t\t\tpfvo.setMemo(null);\n\t\t\t\tpfvo = pfService.updateCustomerPfVO(pfvo);\n\t\t\t\tgetVo().setParentVO(pfvo);\n\t\t\t\treturn getVo();\n\t\t\t} else {\n\t\t\t\tCustomerPfVO pfvo = (CustomerPfVO) ((AggCustomerPfVO) woekFlowRet.m_inVo)\n\t\t\t\t\t\t.getParentVO();\n\t\t\t\tpfvo = pfService.updateCustomerPfVO(pfvo);\n\t\t\t\t((AggCustomerPfVO) woekFlowRet.m_inVo).setParentVO(pfvo);\n\t\t\t\treturn woekFlowRet;\n\t\t\t}\n";
    }
}
