package com.huigou.topsun.sap.suppliers.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.suppliers.application.SuppliersDataApplication;
import com.huigou.topsun.sap.suppliers.domain.*;
import com.huigou.topsun.sap.suppliers.domain.query.SuppliersBankQueryRequest;
import com.huigou.topsun.sap.suppliers.domain.query.SuppliersBuyerQueryRequest;
import com.huigou.topsun.sap.suppliers.domain.query.SuppliersDataQueryRequest;
import com.huigou.topsun.sap.suppliers.domain.query.SuppliersPayQueryRequest;
import com.huigou.topsun.sap.suppliers.domain.vo.*;
import com.huigou.topsun.sap.suppliers.repository.*;
import com.huigou.uasp.bmp.common.BizBillStatus;
import com.huigou.uasp.bpm.ApprovalParameter;
import com.huigou.uasp.bpm.FlowBroker;
import com.huigou.util.*;
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.util.*;
import java.util.stream.Collectors;

@Service("suppliersDataApplication")
public class SuppliersDataApplicationImpl extends FlowBroker implements SuppliersDataApplication {

    @Autowired
    SuppliersInfoRepository suppliersInfoRepository;
    @Autowired
    SuppliersPayRepository suppliersPayRepository;
    @Autowired
    SuppliersBuyerRepository suppliersBuyerRepository;
    @Autowired
    SuppliersBankRepository suppliersBankRepository;
    @Autowired
    DefaultHttpClient defaultHttpClient;
    @Autowired
    SapMutualEpLogApplication sapMutualEpLogApplication;
    @Autowired
    SuppliersItemPeriodRepository suppliersItemPeriodRepository;

    @Override
    public Map<String, Object> slicedSuppliersDataQuery(SuppliersDataQueryRequest query) {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "slicedSuppliersInfoQuery");
        QueryModel model = this.sqlExecutorDao.getQueryModel(queryDescriptor, query);
        model.putDictionary("status", DictUtil.getDictionary("bizBillStatus"));
        return this.sqlExecutorDao.executeSlicedQuery(model);
    }

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

        SuppliersInfo suppliersInfo = getBizEntity(SuppliersInfo.class);
        List<SuppliersPay> suppliersPayList = getBizEntities(SuppliersPay.class, "suppliersPayList");
        List<SuppliersBuyer> suppliersBuyerList = getBizEntities(SuppliersBuyer.class, "suppliersBuyerList");
        List<SuppliersItemPeriod> suppliersItemPeriodList = getBizEntities(SuppliersItemPeriod.class, "suppliersItemPeriodList");
        //List<SuppliersBank> suppliersBankList = getBizEntities(SuppliersBank.class, "suppliersBankList");
        List<SuppliersInfo> suppliersInfos = suppliersInfoRepository.findByStenr(suppliersInfo.getStenr());
        if ("0".equals(suppliersInfo.getApplyType()) && suppliersInfos.size()>0) {
            //根据税码验证供应商唯一性
            //排除自身，有ID  无 ID  两种情况
            if (StringUtil.isNotBlank(suppliersInfo.getId())){
                for (SuppliersInfo info : suppliersInfos) {
                    if (!info.getId().equals(suppliersInfo.getId())){
                        throw new RuntimeException("税号已存在！");
                    }
                }
            }
            if (StringUtil.isBlank(suppliersInfo.getId()) && suppliersInfos.size()>0){
                throw new RuntimeException("税号已存在！");
            }
        }else if ("1".equals(suppliersInfo.getApplyType()) && suppliersInfos.size()>0) {
            //根据税码验证供应商唯一性
            //排除自身，有ID  无 ID  两种情况
            if (StringUtil.isNotBlank(suppliersInfo.getId())){
                for (SuppliersInfo info : suppliersInfos) {
                    if (!info.getId().equals(suppliersInfo.getId()) && !info.getPartner().equals(suppliersInfo.getPartner())){
                        throw new RuntimeException("税号已存在！");
                    }
                }
            }
            if (StringUtil.isBlank(suppliersInfo.getId())){
                for (SuppliersInfo info : suppliersInfos) {
                    if (!info.getPartner().equals(suppliersInfo.getPartner())){
                        throw new RuntimeException("税号已存在！");
                    }
                }
            }
        }
        if (suppliersInfo.isNew()) {
            suppliersInfo.setStatusId(BizBillStatus.APPLYING.getId());
        } else {
            suppliersInfo = (SuppliersInfo) commonDomainService.loadAndFillinProperties(suppliersInfo);
        }
        suppliersInfo = suppliersInfoRepository.save(suppliersInfo);

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

            }

        }
        for (SuppliersBuyer buyer : suppliersBuyerList) {

            if (StringUtil.isNotBlank(buyer.getInco1())&&StringUtil.isBlank(buyer.getInco2L())){
                throw new RuntimeException("请输入国际贸易条款位置1！");
            }
            if (StringUtil.isBlank(buyer.getSId())) {
                buyer.setSId(suppliersInfo.getId());
                this.suppliersBuyerRepository.save(buyer);
            } else if (!(suppliersInfo.getId().equals(buyer.getSId()))) { //从新增带过来的
                SuppliersBuyer modifyBuyer = new SuppliersBuyer();
                ClassHelper.copyProperties(buyer, modifyBuyer);
                modifyBuyer.setId(UUID.randomUUID().toString());
                modifyBuyer.setSId(suppliersInfo.getId());
                this.suppliersBuyerRepository.save(modifyBuyer);
            } else {
                buyer.setSId(suppliersInfo.getId());
                if (StringUtil.isBlank(buyer.getId())) {
                    this.suppliersBuyerRepository.save(buyer);
                } else {
                    SuppliersBuyer suppliersBuyer=suppliersBuyerRepository.findOne(buyer.getId());
                    ClassHelper.copyProperties(buyer, suppliersBuyer);
                    this.suppliersBuyerRepository.saveAndFlush(suppliersBuyer);
                }
             }
        }
        for (SuppliersItemPeriod suppliersItemPeriod : suppliersItemPeriodList) {
            if (StringUtil.isNotBlank(suppliersItemPeriod.getInco1())&&StringUtil.isBlank(suppliersItemPeriod.getInco2L())){
                throw new RuntimeException("请输入国际贸易条款位置1！");
            }
            if (StringUtil.isBlank(suppliersItemPeriod.getSId())) {
                suppliersItemPeriod.setSId(suppliersInfo.getId());
                this.suppliersItemPeriodRepository.save(suppliersItemPeriod);
            } else if (!(suppliersInfo.getId().equals(suppliersItemPeriod.getSId()))) { //从新增带过来的
                SuppliersItemPeriod modifyItemPeriod = new SuppliersItemPeriod();
                ClassHelper.copyProperties(suppliersItemPeriod, modifyItemPeriod);
                modifyItemPeriod.setId(UUID.randomUUID().toString());
                modifyItemPeriod.setSId(suppliersInfo.getId());
                this.suppliersItemPeriodRepository.save(modifyItemPeriod);
            } else {
                suppliersItemPeriod.setSId(suppliersInfo.getId());
                if (StringUtil.isBlank(suppliersItemPeriod.getId())) {
                    this.suppliersItemPeriodRepository.save(suppliersItemPeriod);
                } else {
                    SuppliersItemPeriod suppliersItemPeriod1=suppliersItemPeriodRepository.findOne(suppliersItemPeriod.getId());
                    ClassHelper.copyProperties(suppliersItemPeriod, suppliersItemPeriod1);
                    this.suppliersItemPeriodRepository.saveAndFlush(suppliersItemPeriod1);
                }
            }
        }
        return suppliersInfo.getId();
    }

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

    @Override
    protected void onBeforeComplete(DelegateTask delegateTask) {
        super.onBeforeComplete(delegateTask);
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
        SuppliersInfo suppliersInfo = suppliersInfoRepository.findOne(bizId);
        suppliersInfo.setStatusId(BizBillStatus.APPROVING.getId());
        suppliersInfoRepository.save(suppliersInfo);
    }

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

    }

    @Override
    public void onComplete(DelegateTask delegateTask) {
        super.onComplete(delegateTask);
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
        SuppliersInfo suppliersInfo = suppliersInfoRepository.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(SuppliersInfo.class, bizId, status.getId());
    }

    /**
     * 流程实例结束
     *
     * @param delegateExecution
     */
    @Override
    protected void onEnd(DelegateExecution delegateExecution) {
        //super.onEnd(delegateExecution);
        String bizId = delegateExecution.getProcessBusinessKey();
        SuppliersInfo suppliersInfo = suppliersInfoRepository.findOne(bizId);
        List<SuppliersPay> payList = this.suppliersPayRepository.findAllBySId(suppliersInfo.getId());

        List<SuppliersBuyer> buyerList = this.suppliersBuyerRepository.findAllBySId(suppliersInfo.getId());

        List<SuppliersBank> bankList = this.suppliersBankRepository.findAllBySId(suppliersInfo.getId());
        List<SuppliersItemPeriod> periodList = this.suppliersItemPeriodRepository.findAllBySId(suppliersInfo.getId());

        sendSapData(suppliersInfo, payList, buyerList, bankList, periodList);
        BizBillStatus status = approvePassed() ? BizBillStatus.COMPLETED : BizBillStatus.ABORTED;
        suppliersInfo.setStatusId(status.getId());
        suppliersInfoRepository.save(suppliersInfo);

    }

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

    /**
     * @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();
            SuppliersInfo suppliersInfo = suppliersInfoRepository.findOne(bizId);
            suppliersInfo.setStatusId(BizBillStatus.APPLYING.getId());
            suppliersInfoRepository.save(suppliersInfo);
        }
    }


    /**
     * 远程调用sap接口，传递数据
     */
    public void sendSapData(SuppliersInfo suppliersInfo, List<SuppliersPay> payList, List<SuppliersBuyer> buyerList, List<SuppliersBank> bankList, List<SuppliersItemPeriod> periodList) {
        SuppliersInfoVo suppliersInfoVo = new SuppliersInfoVo();
        BeanUtil.copyProperties(suppliersInfo, suppliersInfoVo);
        suppliersInfoVo.setKtokk(suppliersInfoVo.getRltgr());
        suppliersInfoVo.setUpdkz("I");
        if (suppliersInfo.getApplyType().equals("1")) { //更新
            suppliersInfoVo.setUpdkz("U");
        }
        if (suppliersInfo.getApplyType().equals("-1")) { //删除
            suppliersInfoVo.setUpdkz("D");
        }
        if (suppliersInfo.getApplyType().equals("2")) { //扩展
            suppliersInfoVo.setUpdkz("U");
            List<SuppliersPay> otherPayList = this.getOtherPayList(suppliersInfo.getPartner());
            payList.addAll(otherPayList);
            List<SuppliersBank> otherBankList = this.getOtherBankList(suppliersInfo.getPartner());
            bankList.addAll(otherBankList);
            List<SuppliersBuyer> otherBuyerList = this.getOtherBuyerList(suppliersInfo.getPartner());
            buyerList.addAll(otherBuyerList);
            List<SuppliersItemPeriod> otherItemPeriodList = this.getOtherItemPeriodList(suppliersInfo.getPartner());
            periodList.addAll(otherItemPeriodList);
        }
        if ("0".equals(suppliersInfoVo.getSperr())){
            suppliersInfoVo.setSperr("");
        }
        if ("0".equals(suppliersInfoVo.getSperm())){
            suppliersInfoVo.setSperm("");
        }
        List<SuppliersPayVo> payVoList = new ArrayList<>();
        for (SuppliersPay suppliersPay : payList) {
            SuppliersPayVo payVo = new SuppliersPayVo();
            ClassHelper.copyProperties(suppliersPay, payVo);
            if (payVo.getSperr().equals("0")){
                payVo.setSperr("");
            }
            if (payVo.getSperrB().equals("0")){
                payVo.setSperrB("");
            }
            payVoList.add(payVo);
        }
        suppliersInfoVo.setSuppliersPayList(payVoList);
        List<SuppliersBuyerVo> buyerVoList = new ArrayList<>();
        for (SuppliersBuyer suppliersBuyer : buyerList) {
            SuppliersBuyerVo buyerVo = new SuppliersBuyerVo();
            ClassHelper.copyProperties(suppliersBuyer, buyerVo);
            buyerVoList.add(buyerVo);
        }
        suppliersInfoVo.setSuppliersBuyerList(buyerVoList);
        List<SuppliersBankVo> bankVoList = new ArrayList<>();

        SuppliersBankVo bankVo = new SuppliersBankVo();
        ClassHelper.copyProperties(suppliersInfo, 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
        bankVo.setBanka(suppliersInfoVo.getNameOrg1());
        bankVoList.add(bankVo);
        suppliersInfoVo.setSuppliersBankList(bankVoList);


        //供应商子范围
        List<SuppliersItemPeriodVo> itemPeriodVoList = new ArrayList<>();
        periodList.forEach(period -> {
            SuppliersItemPeriodVo itemPeriodVo = new SuppliersItemPeriodVo();
            ClassHelper.copyProperties(period, itemPeriodVo);
            itemPeriodVoList.add(itemPeriodVo);
        });
        suppliersInfoVo.setSuppliersItemPeriodVoList(itemPeriodVoList);
        ObjectMapper objectMapper = new ObjectMapper();
        String url = "CUD_SUPPLY/SUPPLY_DATA";
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("businessType", "供应商主数据");
        resultMap.put("businessId", suppliersInfo.getId());
        List<SuppliersInfoVo> suppliersInfoVos = new ArrayList<>();
        suppliersInfoVos.add(suppliersInfoVo);
        try {
            String parameter=JSON.toJSONString(suppliersInfoVo);
            parameter=parameter.replaceAll("suppliersPayList","LFB1");
            parameter=parameter.replaceAll("suppliersBuyerList","LFM1");
            parameter=parameter.replaceAll("suppliersBankList","BANK");
            parameter=parameter.replaceAll("suppliersItemPeriodVoList","LFM2");
           // parameter=com.huigou.topsun.util.CommonUtil.camelToUnderline(parameter);
            resultMap.put("parameter", parameter);
            String result = defaultHttpClient.execute(suppliersInfoVos, 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(suppliersInfo.getApplyType())){
                    suppliersInfo.setPartner(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());
                suppliersInfoRepository.save(suppliersInfo);

            } 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);
        }


    }

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

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

    @Override
    public SuppliersInfo loadSuppliersDataById(String id) {

        SuppliersInfo suppliersInfo = suppliersInfoRepository.findOne(id);
        return suppliersInfo;
    }

    @Override
    public Map<String, Object> loadSuppliersPayDatas(SuppliersPayQueryRequest queryRequest) {

        //SuppliersInfo suppliersInfo=suppliersInfoRepository.findOne(queryRequest.getSId());
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "slicedSuppliersPayList");
        // SuppliersPayQueryRequest queryRequest=new  SuppliersPayQueryRequest();
        // 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> loadSuppliersBuyerDatas(SuppliersBuyerQueryRequest queryRequest) {
        //return  this.suppliersBuyerRepository.findBysId(sId);
        // Sort sort = new Sort(Sort.Direction.ASC, "sequence");
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "slicedSuppliersBuyerList");

        QueryModel queryModel = this.sqlExecutorDao.getQueryModel(queryDescriptor, queryRequest);
        queryModel.addCriteria(" and t.s_id =:sId");
        queryModel.putParam("sId", queryRequest.getSId());
        return this.sqlExecutorDao.executeSlicedQuery(queryModel);
    }

    @Override
    public Map<String, Object> loadSuppliersBankDatas(SuppliersBankQueryRequest queryRequest) {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "slicedSuppliersBankList");
        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 Map<String, Object> loadSuppliersItemPeriodDatas(SuppliersBankQueryRequest queryRequest) {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "slicedSuppliersItemPeriodList");
        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>> selectSupplierWaers(String partner) {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "selectSupplierWaers");
        return this.sqlExecutorDao.queryToListMap(queryDescriptor.getSql(),partner,partner,partner,partner,partner, partner,partner);
    }

    //删除数据
    @Override
    public void deleteSuppliersDataByIds(List<String> ids) {
        for (String id : ids) {
            List<SuppliersPay> suppliersPayList = this.suppliersPayRepository.findAllBySId(id);
            for (SuppliersPay suppliersPay : suppliersPayList) {
                suppliersPayRepository.delete(suppliersPay);
            }
            List<SuppliersBuyer> suppliersBuyerList = this.suppliersBuyerRepository.findAllBySId(id);
            for (SuppliersBuyer suppliersBuyer : suppliersBuyerList) {
                suppliersBuyerRepository.delete(suppliersBuyer);
            }
            List<SuppliersBank> suppliersBankList = this.suppliersBankRepository.findAllBySId(id);
            for (SuppliersBank suppliersBank : suppliersBankList) {
                suppliersBankRepository.delete(suppliersBank);
            }
            this.suppliersInfoRepository.delete(id);
        }
    }

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

        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "findDeletedByPartner");
        QueryModel queryModel = new QueryModel();
        queryModel.setSql(queryDescriptor.getSql());
        queryModel.setPageIndex(1);
        queryModel.setPageSize(10);
      //  queryModel.setSortFieldName("updateDate");
       // queryModel.setSortOrder("desc");
        queryModel.putParam("partner", params.getString("partner"));

        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 deleteSuppliersPaysByIds( List<String> ids){
      for (String id:ids){
          SuppliersPay suppliersPay=suppliersPayRepository.findOne(id);
          suppliersPayRepository.delete(suppliersPay);
       }
    }

    @Override
    public void deleteSuppliersBuyerByIds( List<String> ids){

        for (String id:ids){
            SuppliersBuyer suppliersBuyer=suppliersBuyerRepository.findOne(id);
            suppliersBuyerRepository.delete(suppliersBuyer);
        }
    }

    @Override
    public void deleteSuppliersItemPeriodByIds(List<String> ids) {
        for (String id : ids) {
            suppliersItemPeriodRepository.delete(id);
        }
    }

    @Override
    public  void deleteSuppliersBankByIds( List<String> ids){
        for (String id:ids){
              SuppliersBank suppliersBank =suppliersBankRepository.findOne(id);
              suppliersBankRepository.delete(suppliersBank);
        }

    }

    public List<Map<String, String>> selectSuppliersDatas(String types)  {
        SuppliersDataQueryRequest queryRequest=new SuppliersDataQueryRequest();
        List<Map<String, String>> list =new ArrayList<>();
        try {
            String sql="select  t.partner,t.name_org1 from sap_suppliers_info t where t.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_suppliers_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<SuppliersInfo> suppliersInfoList = suppliersInfoRepository.findByPartner(partner);

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

    /**
     * 获取供应商编码下有效的采购组织、银行、公司代码
     * @param partner
     * @return
     */
    @Override
    public Map<String, String> getSupplierNowItemList(String partner){


        List<SuppliersBuyer> buyerList = this.getOtherBuyerList(partner);

        List<SuppliersPay> payList = this.getOtherPayList(partner);

        //已维护的采购组织
        Set<String> ekorgSet = buyerList
                .stream()
                .map(SuppliersBuyer::getEkorg)
                .collect(Collectors.toSet());
        String ekorg = StringUtils.join(ekorgSet, ",");

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

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

        return map;

    }

    public Map<String,String> getIdGroup(String partner){
        List<SuppliersInfo> suppliersInfoList = suppliersInfoRepository.findByPartner(partner);
        suppliersInfoList = suppliersInfoList
                .stream()
                .filter(suppliersInfo->BizBillStatus.COMPLETED.getId() == suppliersInfo.getStatusId())
                .sorted(Comparator.comparing(SuppliersInfo::getFillinDate))
                .collect(Collectors.toList());
        String id = "";
        String extendId = "";
        for (SuppliersInfo suppliersInfo : suppliersInfoList) {
            //如果是新增的，那么根据新增的id查询明细
            if ("0".equals(suppliersInfo.getApplyType())){
                id = suppliersInfo.getId();
            }
            //如果有修改的，排序后，取时间最大的供应商id查询明细
            if ("1".equals(suppliersInfo.getApplyType())){
                id = suppliersInfo.getId();
            }

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

    public List<SuppliersBuyer> getOtherBuyerList(String partner){
        Map<String, String> idGroup = this.getIdGroup(partner);
        //采购组织
        List<SuppliersBuyer> buyerList = suppliersBuyerRepository.findAllBySId(idGroup.get("id"));
        List<SuppliersBuyer> extendBuyerList = suppliersBuyerRepository.findAllBySId(idGroup.get("extendId"));
        buyerList.addAll(extendBuyerList);
        return buyerList;
    }

    public List<SuppliersItemPeriod> getOtherItemPeriodList(String partner){
        Map<String, String> idGroup = this.getIdGroup(partner);
        //采购组织
        List<SuppliersItemPeriod> periodList = suppliersItemPeriodRepository.findAllBySId(idGroup.get("id"));
        List<SuppliersItemPeriod> extendperiodList = suppliersItemPeriodRepository.findAllBySId(idGroup.get("extendId"));
        periodList.addAll(extendperiodList);
        return periodList;
    }

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

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