package com.huigou.topsun.sap.finaCustomer.application.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huigou.cache.DictUtil;
import com.huigou.data.domain.model.CommonDomainConstants;
import com.huigou.data.query.model.QueryDescriptor;
import com.huigou.data.query.model.QueryModel;
import com.huigou.topsun.sap.common.DefaultHttpClient;
import com.huigou.topsun.sap.common.application.SapMutualEpLogApplication;
import com.huigou.topsun.sap.common.domain.SapResult;
import com.huigou.topsun.sap.finaCustomer.application.FinaCustomerApplication;
import com.huigou.topsun.sap.finaCustomer.domain.FinaCustomerBank;
import com.huigou.topsun.sap.finaCustomer.domain.FinaCustomerInfo;
import com.huigou.topsun.sap.finaCustomer.domain.FinaCustomerPay;
import com.huigou.topsun.sap.finaCustomer.domain.query.FinaCustomerQueryRequest;
import com.huigou.topsun.sap.finaCustomer.repository.FinaCustomerBankRepository;
import com.huigou.topsun.sap.finaCustomer.repository.FinaCustomerInfoRepository;
import com.huigou.topsun.sap.finaCustomer.repository.FinaCustomerPayRepository;
import com.huigou.topsun.syncOrg.vo.SapPersonVo.BankVo;
import com.huigou.topsun.syncOrg.vo.SapPersonVo.CompanyCodeVo;
import com.huigou.topsun.syncOrg.vo.SapPersonVo.MdClientSapVo;
import com.huigou.uasp.bmp.common.BizBillStatus;
import com.huigou.uasp.bmp.fn.CodeGenerator;
import com.huigou.uasp.bpm.ApprovalParameter;
import com.huigou.uasp.bpm.FlowBroker;
import com.huigou.util.ClassHelper;
import com.huigou.util.DateUtil;
import com.huigou.util.SDO;
import com.huigou.util.StringUtil;
import lombok.SneakyThrows;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.DelegateTask;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service("finaCustomerApplication")
public class FinaCustomerApplicationImpl extends FlowBroker implements FinaCustomerApplication {

    @Autowired
    FinaCustomerInfoRepository finaCustomerRepository;
    @Autowired
    FinaCustomerPayRepository finaCustomerPayRepository;
    @Autowired
    FinaCustomerBankRepository finaCustomerBankRepository;
    @Autowired
    DefaultHttpClient defaultHttpClient;
    @Autowired
    SapMutualEpLogApplication sapMutualEpLogApplication;
    @Autowired
    private CodeGenerator codeGenerator;
    //finaCustomerNum

    @Override
    public Map<String, Object> slicedFinaCustomerQuery(FinaCustomerQueryRequest query) {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "slicedFinaCustomerQuery");
        QueryModel model = this.sqlExecutorDao.getQueryModel(queryDescriptor, query);
        model.putDictionary("maintenanceType", DictUtil.getDictionary("maintainType"));
        model.putDictionary("baseUnit", DictUtil.getDictionary("measuringUnit"));
        model.putDictionary("itemAttributes", DictUtil.getDictionary("suppliesType"));
        model.putDictionary("businessUsage", DictUtil.getDictionary("serviceusage"));
        model.putDictionary("status", DictUtil.getDictionary("bizBillStatus"));
        model.addCriteria(" order by bill_code desc ");
        return this.sqlExecutorDao.executeSlicedQuery(model);
    }

    @SneakyThrows
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    protected String saveBizAndApprovalData() {
        super.saveBizAndApprovalData();

        FinaCustomerInfo finaCustomer = getBizEntity(FinaCustomerInfo.class);
        List<FinaCustomerPay> finaCustomerPayList = getBizEntities(FinaCustomerPay.class, "finaCustomerPayList");
        List<FinaCustomerBank> finaCustomerBankList = getBizEntities(FinaCustomerBank.class, "finaCustomerBankList");

        if (finaCustomer.isNew()) {
            finaCustomer.setStatusId(BizBillStatus.APPLYING.getId());
        } else {
            finaCustomer = (FinaCustomerInfo) commonDomainService.loadAndFillinProperties(finaCustomer);
        }
        finaCustomer = finaCustomerRepository.save(finaCustomer);

        for (FinaCustomerPay pay : finaCustomerPayList) {
            if (StringUtil.isBlank(pay.getSId())) {
                pay.setSId(finaCustomer.getId());
                this.finaCustomerPayRepository.save(pay);
            } else if (!(finaCustomer.getId().equals(pay.getSId()))) { //从新增带过来的
                FinaCustomerPay modifyPay = new FinaCustomerPay();
                ClassHelper.copyProperties(pay, modifyPay);
                modifyPay.setId(UUID.randomUUID().toString());
                modifyPay.setSId(finaCustomer.getId());
                this.finaCustomerPayRepository.save(modifyPay);
            } else {
                pay.setSId(finaCustomer.getId());
                if (StringUtil.isBlank(pay.getId())) {
                   this.finaCustomerPayRepository.save(pay);
                } else {
                    FinaCustomerPay finaCustomerPay=finaCustomerPayRepository.findOne(pay.getId());
                    ClassHelper.copyProperties(pay, finaCustomerPay);
                    this.finaCustomerPayRepository.saveAndFlush(finaCustomerPay);
                }

            }

        }

        for (FinaCustomerBank bank : finaCustomerBankList) {

            if (StringUtil.isBlank(bank.getSId())) {
                bank.setSId(finaCustomer.getId());
                this.finaCustomerBankRepository.save(bank);
            } else if (!(finaCustomer.getId().equals(bank.getSId()))) { //从新增带过来的
                FinaCustomerBank modifyBank = new FinaCustomerBank();
                ClassHelper.copyProperties(bank, modifyBank);
                modifyBank.setId(UUID.randomUUID().toString());
                modifyBank.setSId(finaCustomer.getId());
                this.finaCustomerBankRepository.save(modifyBank);
            } else {
               // bank.setSId(finaCustomer.getId());
               // this.finaCustomerBankRepository.save(bank);
                bank.setSId(finaCustomer.getId());
                if (StringUtil.isBlank(bank.getId())) {
                    this.finaCustomerBankRepository.save(bank);
                } else {
                    FinaCustomerBank finaCustomerBank=finaCustomerBankRepository.findOne(bank.getId());
                    ClassHelper.copyProperties(bank, finaCustomerBank);
                    this.finaCustomerBankRepository.saveAndFlush(finaCustomerBank);
                }
            }
        }

        return finaCustomer.getId();
    }

    @Override
    protected Map<String, Object> getProcessBizParams(String bizId) {
        // 返回业务数据给流程实例，
        return ClassHelper.toMap(finaCustomerRepository.getOne(bizId));
    }

    @Override
    protected void onBeforeComplete(DelegateTask delegateTask) {
        super.onBeforeComplete(delegateTask);
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
        if (this.isApplyProcUnit(delegateTask) && this.getApprovalParameter().isAdvanceProcessAction()) {
            FinaCustomerInfo finaCustomer = finaCustomerRepository.findOne(bizId);
            finaCustomer.setStatusId(BizBillStatus.APPROVING.getId());
            finaCustomerRepository.save(finaCustomer);
        }
    }

    //流程已办
    @Override
    public void onAfterComplete(DelegateTask delegateTask) {
        super.onAfterComplete(delegateTask);
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
        //  FinaCustomerInfo finaCustomer = finaCustomerRepository.findOne(bizId);

    }

    @Override
    public void onComplete(DelegateTask delegateTask) {
        super.onComplete(delegateTask);
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
        FinaCustomerInfo finaCustomer = finaCustomerRepository.findOne(bizId);
        //审批不通过
        ApprovalParameter parameter = getApprovalParameter();
        // if (ObjectUtils.equals(parameter.getHandleResult(), HandleResult.DISAGREE.id)) {   //审批不通过 或者退回
        //  }
        if (this.isApplyProcUnit(delegateTask)) {   //申请后直接提交
        }
    }

    /**
     * 流程撤销事件
     **/
    @Override
    protected void onRecallProcessInstance(DelegateExecution delegateExecution) {
        String bizId = delegateExecution.getProcessBusinessKey();
        // 修改单据状态为申请
        updateStatus(bizId, BizBillStatus.APPLYING);
    }


    /**
     * 回收事件
     **/
    @Override
    protected void onWithdraw(DelegateTask delegateTask, String destActivityId) {
        super.onWithdraw(delegateTask, destActivityId);
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
        if (destActivityId.equalsIgnoreCase("apply")) {
            updateStatus(bizId, BizBillStatus.APPLYING);
        }
    }

    @Transactional
    protected void updateStatus(String bizId, BizBillStatus status) {
        Assert.hasText(bizId, CommonDomainConstants.ID_NOT_BLANK);
        this.commonDomainService.updateStatus(FinaCustomerInfo.class, bizId, status.getId());
    }

    /**
     * 流程实例结束
     *
     * @param delegateExecution
     */
    @Override
    protected void onEnd(DelegateExecution delegateExecution) {
        super.onEnd(delegateExecution);
        String bizId = delegateExecution.getProcessBusinessKey();
        FinaCustomerInfo finaCustomer = finaCustomerRepository.findOne(bizId);
        List<FinaCustomerPay> payList = this.finaCustomerPayRepository.findAllBySId(finaCustomer.getId());

        List<FinaCustomerBank> bankList = this.finaCustomerBankRepository.findAllBySId(finaCustomer.getId());
        this.sendSapClientData(finaCustomer, payList, bankList);
        BizBillStatus status = approvePassed() ? BizBillStatus.COMPLETED : BizBillStatus.ABORTED;
        finaCustomer.setStatusId(status.getId());
        finaCustomerRepository.save(finaCustomer);

    }

    @Override
    protected void onAbortProcessInstance(DelegateExecution delegateExecution) {
        super.onAbortProcessInstance(delegateExecution);
        String bizId = delegateExecution.getProcessBusinessKey();
        FinaCustomerInfo finaCustomer = finaCustomerRepository.findOne(bizId);
        finaCustomer.setStatusId(BizBillStatus.ABORTED.getId());
        finaCustomerRepository.save(finaCustomer);
    }

    /**
     * @param delegateTask
     * @param destActivityId 回退到的目标节点id
     */
    @Override
    protected void onBack(DelegateTask delegateTask, String destActivityId) {
        super.onBack(delegateTask, destActivityId);
        if ("Apply".equalsIgnoreCase(destActivityId)) {
            String bizId = delegateTask.getExecution().getProcessBusinessKey();
            FinaCustomerInfo finaCustomer = finaCustomerRepository.findOne(bizId);
            finaCustomer.setStatusId(BizBillStatus.APPLYING.getId());
            finaCustomerRepository.save(finaCustomer);
        }
    }


    /**
     * 远程调用sap接口，传递数据
     */
    @Transactional
    public void sendSapClientData(FinaCustomerInfo finaCustomer, List<FinaCustomerPay> payList, List<FinaCustomerBank> bankList) {
        List<MdClientSapVo> mdClientSapVoList = new ArrayList<>();
        MdClientSapVo mdClientSapVo = new MdClientSapVo();
        BeanUtil.copyProperties(finaCustomer, mdClientSapVo);
        mdClientSapVo.setRltyp("");//BP角色，财务客户
        mdClientSapVo.setBuGroup(finaCustomer.getCreationGroup());//业务伙伴分类，员工客户
        mdClientSapVo.setKunnr(finaCustomer.getBuPartner());//员工编码
        mdClientSapVo.setLand1(finaCustomer.getCountry());//国家
        mdClientSapVo.setTitle(finaCustomer.getTitleMedi());
        mdClientSapVo.setBuSort1(finaCustomer.getBuSort1Txt());//搜索词
        mdClientSapVo.setStras(finaCustomer.getStreet());//街道
        mdClientSapVo.setTaxnumxl(finaCustomer.getStenr());//税号
        mdClientSapVo.setUpdkz("I");
        //mdClientSapVo.setTaxType("CN5");//税类别
        if (finaCustomer.getApplyType().equals("1")) { //更新
            mdClientSapVo.setUpdkz("U");
        }
        if (finaCustomer.getApplyType().equals("-1")) { //删除
            mdClientSapVo.setUpdkz("D");
        }
        if (finaCustomer.getApplyType().equals("2")) { //扩展
            mdClientSapVo.setUpdkz("U");
            List<FinaCustomerPay> otherPayList = this.getOtherPayList(finaCustomer.getBuPartner());
            payList.addAll(otherPayList);
            List<FinaCustomerBank> otherBankList = this.getOtherBankList(finaCustomer.getBuPartner());
            bankList.addAll(otherBankList);
        }
        if ("0".equals(finaCustomer.getSperr())){
            mdClientSapVo.setSperr("");
        }
        //公司代码视图
        List<CompanyCodeVo> payVoList = new ArrayList<>();
        for (int i = 0; i < payList.size(); i++) {
            FinaCustomerPay finaCustomerPay = payList.get(i);
            CompanyCodeVo companyCodeVo = new CompanyCodeVo();
            ClassHelper.copyProperties(finaCustomerPay, companyCodeVo);
            companyCodeVo.setAkont(finaCustomerPay.getAkontCustomer());
            if ("0".equals(companyCodeVo.getSperrB())){
                companyCodeVo.setSperrB("");
            }
            payVoList.add(companyCodeVo);
        }
        mdClientSapVo.setKnb1(payVoList);

        //银行视图
        List<BankVo> bankVoList = new ArrayList<>();
        for (FinaCustomerBank finaCustomerBank : bankList) {
            BankVo bankVo = new BankVo();
            ClassHelper.copyProperties(finaCustomerBank, bankVo);
            //银行账户，BPM不处理，SAP处理
//            if (bankVo.getBankn().length() > 18){
//                String bankn = bankVo.getBankn();
//                bankVo.setBankn(bankn.substring(0,18));
//                //账户明细放18位后的值
//                bankVo.setBkref(bankn.substring(18,bankn.length()));
//            }
            //财务机构名称赋值组织名称1
            bankVoList.add(bankVo);
        }
        mdClientSapVo.setBank(bankVoList);
        String url = "cud_custom/customer";
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("businessType", "财务客户主数据");
        resultMap.put("businessId", finaCustomer.getId());
        try {
//            if (StringUtil.isBlank(finaCustomer.getBuPartner())){
//                String buPartner = this.getBuPartner();
//                finaCustomer.setBuPartner(buPartner);//赋值客户编码
//                mdClientSapVo.setKunnr(buPartner);
//            }
            mdClientSapVoList.add(mdClientSapVo);
            String parameter=JSON.toJSONString(mdClientSapVoList);
            parameter=parameter.replaceAll("finaCustomerPayList","LFB1");
            parameter=parameter.replaceAll("finaCustomerBankList","BANK");
            // parameter=com.huigou.topsun.util.CommonUtil.camelToUnderline(parameter);
            resultMap.put("parameter", parameter);
            String result = defaultHttpClient.execute(mdClientSapVoList, url);
            List<SapResult> sapResultList = JSONObject.parseArray(result, SapResult.class);
            if (sapResultList.size()<1){
                throw new RuntimeException("数据传输失败，没有收到返回结果：" + sapResultList);
            }
            SapResult sapResult = sapResultList.get(0);
            resultMap.put("sequence", resultMap.get("row"));
            if ("S".equals(sapResult.getTYPE())) {
                if ("0".equals(finaCustomer.getApplyType())){
                    finaCustomer.setBuPartner(sapResult.getMESSAGE_V1().substring(4));
                    resultMap.put("MESSAGE", sapResult.getMESSAGE()+sapResult.getMESSAGE_V1().substring(4));
                } else {
                    resultMap.put("MESSAGE", sapResult.getMESSAGE());
                }
                resultMap.put("TYPE", sapResult.getTYPE());
                finaCustomerRepository.save(finaCustomer);

            } else {
                throw new RuntimeException("数据传输失败，请稍后手动重试！" + sapResult.getMESSAGE());
            }
        } catch (Exception e) {
            resultMap.put("TYPE", "E");
            resultMap.put("MESSAGE", e.getMessage());
            throw new RuntimeException("数据传输失败请检查数据后重试！" + e.getMessage());
        } finally {
            sapMutualEpLogApplication.saveSapMutualEpLog(resultMap);
        }
    }

    /**
     * 从数据库统计客户编码，加锁
     * @return
     */
    public synchronized String getBuPartner(){
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "countBuPartner");
        int buPartner = this.sqlExecutorDao.queryToInt(queryDescriptor.getSql());
        return String.valueOf(buPartner+1);
    }

    /**
     * 设置任务名称
     */
    @Override
    protected void setTaskDescription(DelegateTask delegateTask) {
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
        delegateTask.setDescription(this.getApprovalSubjectName(bizId));
    }

    /**
     * 获取任务标题
     *
     * @param bizId
     * @return
     */
    private String getApprovalSubjectName(String bizId) {
        FinaCustomerInfo finaCustomer = this.finaCustomerRepository.findOne(bizId);
        //查询 单据日期
        String fillinDateStr = DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss", finaCustomer.getFillinDate());
        //设置标题
        // String wantGoodsNameText = DictUtil.getDictionaryDetailText("A0051", wantGoods.getCustomerName());
        if (finaCustomer.getApplyType().equals("1")) {
            return String.format("%s-%s(%s)", "财务客户主数据修改", finaCustomer.getBillCode(), fillinDateStr);
        } else if (finaCustomer.getApplyType().equals("-1")) {
            return String.format("%s-%s(%s)", "财务客户主数据删除", finaCustomer.getBillCode(), fillinDateStr);
        }else if (finaCustomer.getApplyType().equals("2")) {
            return String.format("%s-%s(%s)", "财务客户主数据扩展", finaCustomer.getBillCode(), fillinDateStr);
        } else {
            return String.format("%s-%s(%s)", "财务客户主数据申请", finaCustomer.getBillCode(), fillinDateStr);
        }
    }

    @Override
    public FinaCustomerInfo loadFinaCustomerById(String id) {
        return finaCustomerRepository.findOne(id);
    }

    @Override
    public Map<String, Object> loadFinaCustomerPayDatas(FinaCustomerQueryRequest queryRequest) {

        //FinaCustomerInfo finaCustomer=finaCustomerRepository.findOne(queryRequest.getSId());
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "slicedFinaCustomerPayList");
        // FinaCustomerPayQueryRequest queryRequest=new  FinaCustomerPayQueryRequest();
        // queryRequest.setSId(sId);
        QueryModel queryModel = this.sqlExecutorDao.getQueryModel(queryDescriptor, queryRequest);
        // queryModel.putDictionary("konwa", DictUtil.getDictionary("currency"));
        queryModel.addCriteria(" and t.s_id =:sId");
        queryModel.putParam("sId", queryRequest.getSId());
        return this.sqlExecutorDao.executeSlicedQuery(queryModel);
    }

    @Override
    public Map<String, Object> loadFinaCustomerBankDatas(FinaCustomerQueryRequest queryRequest) {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "slicedFinaCustomerBankList");
        QueryModel queryModel = this.sqlExecutorDao.getQueryModel(queryDescriptor, queryRequest);
        queryModel.putDictionary("banks",DictUtil.getDictionary("country"));
        queryModel.addCriteria(" and t.s_id =:sId");
        queryModel.putParam("sId", queryRequest.getSId());
        return this.sqlExecutorDao.executeSlicedQuery(queryModel);
    }

    @Override
    public List<Map<String, Object>> findDeletedFinaCustomerById(SDO params) {

        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "findDeletedByBuPartner");
        QueryModel queryModel = new QueryModel();
        queryModel.setSql(queryDescriptor.getSql());
        queryModel.setPageIndex(1);
        queryModel.setPageSize(10);
        queryModel.putParam("buPartner", params.getString("buPartner"));

        Map<String, Object> map=this.sqlExecutorDao.executeSlicedQuery(queryModel);
        List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("Rows");

        return list;
    }

    @Override
    public  void deleteFinaCustomerPaysByIds( List<String> ids){
      for (String id:ids){
          FinaCustomerPay finaCustomerPay=finaCustomerPayRepository.findOne(id);
          finaCustomerPayRepository.delete(finaCustomerPay);
       }
    }

    @Override
    public  void deleteFinaCustomerBankByIds( List<String> ids){
        for (String id:ids){
              FinaCustomerBank finaCustomerBank =finaCustomerBankRepository.findOne(id);
              finaCustomerBankRepository.delete(finaCustomerBank);
        }
    }

    public List<Map<String, String>> selectFinaCustomers(String types)  {
        FinaCustomerQueryRequest queryRequest=new FinaCustomerQueryRequest();
        List<Map<String, String>> list =new ArrayList<>();
        try {
            String sql="select  t.bu_partner,t.name_org1 from sap_fina_customer_info t where t.bu_partner!='' and t.status=3 ";
            List<Map<String, Object>> list2=this.sqlExecutorDao.queryToListMap(sql);
            for (Map map:list2){
              list.add(map);
           }
        //    QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "sap_finaCustomer_info");
         //   QueryModel queryModel = this.sqlExecutorDao.getQueryModel(queryDescriptor, queryRequest);
       //     queryModel.putDictionary("banks", DictUtil.getDictionary("country"));
       //     queryModel.addCriteria(" and t.status =3");
            // queryModel.putParam("sId", queryRequest.getSId());

           // Map<String, Object> map = this.sqlExecutorDao.executeSlicedQuery(queryModel);
            // list = (List<Map<String, String>>) map.get("Rows");
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return list;
    }

    @Override
    public String checkApprovalStatus(String partner) {
        List<FinaCustomerInfo> finaCustomerList = finaCustomerRepository.findByBuPartner(partner);

        //如果有单据在审批或者申请中，也不能做任何操作
        for (FinaCustomerInfo finaCustomer : finaCustomerList) {
            //先判断是否已删除，如果删除不能做任何操作
            if ("-1".equals(finaCustomer.getApplyType())){
                return "已删除";
            }
        }
        return null;
    }

    /**
     * 获取财务客户编码下有效的银行、公司代码
     * @param buPartner
     * @return
     */
    @Override
    public Map<String, String> getFinaCustomerNowItemList(String buPartner){

        List<FinaCustomerBank> bankList = this.getOtherBankList(buPartner);

        List<FinaCustomerPay> payList = this.getOtherPayList(buPartner);

        //已维护的银行组织
        Set<String> banklSet = bankList
                .stream()
                .map(FinaCustomerBank::getBankl)
                .collect(Collectors.toSet());
        String bankl = StringUtils.join(banklSet, ",");

        //已维护的公司代码
        Set<String> bukrsSet = payList
                .stream()
                .map(FinaCustomerPay::getBukrs)
                .collect(Collectors.toSet());
        String bukrs = StringUtils.join(bukrsSet, ",");

        Map<String,String> map = new HashMap<>();
        map.put("nowBankl",bankl);
        map.put("nowBukrs",bukrs);

        return map;

    }

    public Map<String,String> getIdGroup(String partner){
        List<FinaCustomerInfo> finaCustomerList = finaCustomerRepository.findByBuPartner(partner);
        finaCustomerList = finaCustomerList
                .stream()
                .filter(finaCustomer->BizBillStatus.COMPLETED.getId() == finaCustomer.getStatusId())
                .sorted(Comparator.comparing(FinaCustomerInfo::getFillinDate))
                .collect(Collectors.toList());
        String id = "";
        String extendId = "";
        for (FinaCustomerInfo finaCustomer : finaCustomerList) {
            //如果是新增的，那么根据新增的id查询明细
            if ("0".equals(finaCustomer.getApplyType())){
                id = finaCustomer.getId();
            }
            //如果有修改的，排序后，取时间最大的财务客户id查询明细
            if ("1".equals(finaCustomer.getApplyType())){
                id = finaCustomer.getId();
            }

            //如果是扩展的，排序后，取时间最大的财务客户id查询明细
            if ("2".equals(finaCustomer.getApplyType())){
                extendId = finaCustomer.getId();
            }
        }
        Map<String,String> map = new HashMap<>();
        map.put("id",id);
        map.put("extendId",extendId);
        return map;
    }

    public List<FinaCustomerBank> getOtherBankList(String partner){
        Map<String, String> idGroup = this.getIdGroup(partner);
        //银行信息
        List<FinaCustomerBank> bankList = finaCustomerBankRepository.findAllBySId(idGroup.get("id"));
        List<FinaCustomerBank> extendBankList = finaCustomerBankRepository.findAllBySId(idGroup.get("extendId"));
        bankList.addAll(extendBankList);
        return bankList;
    }

    public List<FinaCustomerPay> getOtherPayList(String partner){
        Map<String, String> idGroup = this.getIdGroup(partner);
        //付款信息
        List<FinaCustomerPay> payList = finaCustomerPayRepository.findAllBySId(idGroup.get("id"));
        List<FinaCustomerPay> extendPayList = finaCustomerPayRepository.findAllBySId(idGroup.get("extendId"));
        payList.addAll(extendPayList);
        return payList;
    }
}
