package com.zfire.mall.manager.logic.k3;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.CommonCountBean;
import com.zfire.mall.manager.bean.ExcelData;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.k3.K3ReceiptBean;
import com.zfire.mall.manager.bean.k3.RequestApiBean;
import com.zfire.mall.manager.bean.listV2.K3ReceiptVO;
import com.zfire.mall.manager.bean.wallet.CustomerWalletAmountBean;
import com.zfire.mall.manager.commonmapper.K3Mapper;
import com.zfire.mall.manager.commonmapper.listV2.CommonCMapper;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.constant.KingDeeCons;
import com.zfire.mall.manager.enums.ExamineStatusEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.helper.ResponseHelper;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.logic.k3.bill.K3ReceiptBillLogic;
import com.zfire.mall.manager.logic.wallet.WalletLogic;
import com.zfire.mall.manager.plus.entity.CustomerWallet;
import com.zfire.mall.manager.plus.entity.KingDeeReceipt;
import com.zfire.mall.manager.plus.entity.KingDeeWallet;
import com.zfire.mall.manager.plus.entity.ReceivableOrder;
import com.zfire.mall.manager.plus.service.KingDeeCustomerService;
import com.zfire.mall.manager.plus.service.KingDeeReceiptService;
import com.zfire.mall.manager.plus.service.KingDeeWalletService;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import com.zfire.mall.manager.zfire.util.FieldUtils;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
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 java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Log4j
public class K3ReceiptLogic {

    @Autowired
    K3Mapper k3Mapper;
    @Autowired
    KingDeeReceiptService kingDeeReceiptService;
    @Autowired
    KingDeeCustomerService kingDeeCustomerService;
    @Autowired
    KingDeeWalletService kingDeeWalletService;
    @Autowired
    CommonCMapper commonCMapper;
    @Autowired
    CommonLogic commonLogic;
    @Autowired
    K3Logic k3Logic;
    @Autowired
    WalletLogic walletLogic;
    @Autowired
    K3ReceiptBillLogic k3ReceiptBillLogic;


    /**
     * 收款单列表-V2
     */
    public IPage<K3ReceiptVO> listV2(ZfireParamBean zfireParamBean){
        zfireParamBean = FieldUtils.supplyParam(zfireParamBean);
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : null;
        IPage<K3ReceiptVO> page = commonCMapper.queryK3Receipt(new Page(zfireParamBean.getPageNum(),
                zfireParamBean.getPageSize()), zfireParamBean, customerId,adminUser.getServiceIds());
        return page;
    }


    /**
     * 收款单列表
     * @param billType
     * @param billNo
     * @param wlCompanyType
     * @param customerName
     * @param settleType
     * @param startTime
     * @param endTime
     * @param websitNumber
     * @param pageNum
     * @param pageSize
     * @return
     */
    public IPage<K3ReceiptBean> list(String billType,String billNo,String wlCompanyType,String customerName,String settleType,
                                      String startTime,String endTime,String websitNumber,Integer pageNum,Integer pageSize){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : null;

        IPage<K3ReceiptBean> k3ReceiptBeanIPage = k3Mapper
                .queryReceiptBill(new Page(pageNum, pageSize), billType, billNo, wlCompanyType, customerName, settleType, startTime, endTime,customerId,websitNumber);
        return k3ReceiptBeanIPage;
    }

    public CommonCountBean listCount(String billType, String billNo, String wlCompanyType, String customerName, String settleType,
                                     String startTime, String endTime,String websitNumber){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : null;
        return k3Mapper.queryReceiptBillCount(billType, billNo, wlCompanyType, customerName, settleType, startTime, endTime,customerId,websitNumber);
    }


    public K3ReceiptBean detail(String id){
        KingDeeReceipt kingDeeReceipt = kingDeeReceiptService.getById(id);
        K3ReceiptBean bean = new K3ReceiptBean();
        BeanUtils.copyProperties(kingDeeReceipt,bean);
        //客户名称
        bean.setCustomerName(kingDeeCustomerService.getById(bean.getCustomerId()).getName());
        //钱包名称
        bean.setWalletName(kingDeeWalletService.getById(bean.getWalletId()).getName());
        return bean;
    }

    /**
     * 收款单-列表(导出)
     */
    public ExcelData export(List<K3ReceiptBean> k3ReceiptBeanList){
        String[] titles = new String[]{"单据类型","单据编码","业务日期","单据状态","钱包","表头.应收金额", "往来单位",
                "表头.实收金额","收款金额","付款单位","表体.实收金额","勾对","备注"};
        List<List<Object>> rows = new ArrayList<>();
        for (K3ReceiptBean k3ReceiptBean : k3ReceiptBeanList) {

            String status = k3ReceiptBean.getStatus();
            String statusName = "";
            if(status != null){
                if(status.equals("C")){
                    statusName = "已审核";
                }else{
                    statusName = "重新审核";
                }
            }

            BigDecimal amount = k3ReceiptBean.getAmount();
            String billTypeName = "";
            if(k3ReceiptBean.getBillType().equals("1")){
                billTypeName = "收款单";
            }else if(k3ReceiptBean.getBillType().equals("2")){
                billTypeName = "付款单";
                amount = BigDecimal.valueOf(0).subtract(amount);
            }else{
                billTypeName = "退款单";
                amount = BigDecimal.valueOf(0).subtract(amount);
            }

            List<Object> row = new ArrayList<>();
            row.add(billTypeName);
            row.add(k3ReceiptBean.getBillNo());
            row.add(DateUtil.formatDate(k3ReceiptBean.getTheTime()));
            row.add(statusName);
            row.add(k3ReceiptBean.getWalletName());
            row.add("");
            row.add(k3ReceiptBean.getWlCompanyName());
            row.add(amount);
            row.add("");
            row.add(k3ReceiptBean.getCustomerName());
            row.add(amount);
            row.add("");
            row.add(k3ReceiptBean.getRemark());
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }











    /**
     * 同步收款单-用来计算钱包余额
     * @param startTime
     * @param endTime
     */
//    @Transactional(propagation = Propagation.REQUIRES_NEW)
//    public void allSyncSkd(String orgId,String orgNum,String startTime,String endTime) throws Exception {
//        String formId =  KingDeeCons.WALLET_SKD;
//        //同步 反审的 收款单  formId永远查询所有
//        RequestApiBean request = k3Logic.getInstance(orgId, orgNum, null, startTime, endTime);
//        request.setFormId(formId);
//        request.setNotTime(true);
//        String filterStr = "FDocumentStatus ='D'";
//        this.allSyncSkd1(request,filterStr);
//
//        //同步已审核的收款单
//        RequestApiBean request2 = k3Logic.getInstance(orgId, orgNum, formId, startTime, endTime);
//        String filterStr2 = "FDocumentStatus ='C' "+k3Logic.supplySql("FApproveDate", request2.getStartTime(), request2.getEndTime());
//        this.allSyncSkd1(request2,filterStr2);
//    }


//    private void allSyncSkd1(RequestApiBean request,String filterStr) throws Exception {
//
//        // 同步钱包接口
//        //String filterStr = "FDocumentStatus ='C' "+k3Logic.supplySql("FModifyDate", request.getStartTime(), request.getEndTime());
//        request.setFieldKeys("FRECEIVEBILLENTRY_FEntryID,FBillNo,FDOCUMENTSTATUS,FRECAMOUNTFOR_E,F_kls_Assistant1,FPAYUNIT,FREALRECAMOUNTFOR_D,FDATE," +
//                "FCONTACTUNIT,FSETTLEDISTAMOUNTFOR,FSALEDEPTID,FSALEERID,FREMARK,FACCOUNTID," +
//                "FSALEGROUPID,FSETTLETYPEID,FSETTLEORGID,FPAYORGID,FCURRENCYID,FPAYUNITTYPE");
//        request.setFilterString(String.format(filterStr));
//        request.setOrderString("FID ASC");
//        String[] fields = new String[]{"id","billNo","status","amount","walletId","customerId","hAmount","theTime",
//                "wlCompanyType","discount","saleDepartment","salePerson","remark","bankAccount",
//                "saleGroup","settleType","settleOrg","skzz","bibie","customerType"};
//
//        List<KingDeeReceipt> objects = k3Logic.allSync(request, fields, KingDeeReceipt.class);
//
//        if (CollectionUtils.isEmpty(objects)) {
//            return;
//        }
//
//        objects.forEach(v -> v.setBillType("1").setId(v.getBillType() + v.getId()));
//        this.initAmount(objects);
//        //处理金额充值-----------------结束
//        kingDeeReceiptService.saveOrUpdateBatch(objects);
//    }



    //AR_REFUNDBILL 退款单

    /**
     * 同步退款单-用来计算钱包余额
     * @param startTime
     * @param endTime
     */
//    @Transactional(propagation = Propagation.REQUIRES_NEW)
//    public void allSyncTkd(String orgId,String orgNum,String startTime,String endTime) throws Exception {
//        String formId =  KingDeeCons.WALLET_TKD;
//        //同步 反审的 退款单
//        RequestApiBean request = k3Logic.getInstance(orgId, orgNum, null, startTime, endTime);
//        request.setFormId(formId);
//        request.setNotTime(true);
//        String filterStr = "FDocumentStatus ='D'";
//        this.allSyncTkd1(request,filterStr);
//
//        //同步已审核的退款单
//        RequestApiBean request2 = k3Logic.getInstance(orgId, orgNum, formId, startTime, endTime);
//        String filterStr2 = "FDocumentStatus ='C' "+k3Logic.supplySql("FApproveDate", request2.getStartTime(), request2.getEndTime());
//        this.allSyncTkd1(request2,filterStr2);
//    }


//    private void allSyncTkd1(RequestApiBean request,String filterStr) throws Exception {
//        // 同步钱包接口
//        request.setFieldKeys("FREFUNDBILLENTRY_FEntryID,FBillNo,FDOCUMENTSTATUS,FREALREFUNDAMOUNTFOR_D,F_kls_Assistant1, " +
//                "FRECTUNIT,FREFUNDAMOUNTFOR_E,FDATE,FCONTACTUNIT, " +
//                "FSALEDEPTID,FSALEERID,FREMARK,FACCOUNTID,FSALEGROUPID, " +
//                "FSETTLETYPEID,FSETTLEORGID,FPAYORGID,FCURRENCYID,FRECTUNITTYPE");
//        request.setFilterString(String.format(filterStr));
//        request.setOrderString("FID ASC");
//        String[] fields = new String[]{"id","billNo","status","amount","walletId",
//                "customerId","hAmount","theTime", "wlCompanyType","saleDepartment",
//                "salePerson","remark","bankAccount", "saleGroup","settleType",
//                "settleOrg","skzz","bibie","customerType"};
//
//        List<KingDeeReceipt> objects = k3Logic.allSync(request, fields, KingDeeReceipt.class);
//        if (CollectionUtils.isEmpty(objects)) {
//            return;
//        }
//        objects.forEach(v -> v.setBillType("2").setId(v.getBillType() + v.getId()));
//        this.initAmount(objects);
//        //处理金额充值-----------------结束
//        kingDeeReceiptService.saveOrUpdateBatch(objects);
//    }



    /**
     * 同步付款单-用来计算钱包余额
     * @param startTime
     * @param endTime
     */
//    @Transactional(propagation = Propagation.REQUIRES_NEW)
//    public void allSyncFkd(String orgId,String orgNum,String startTime,String endTime) throws Exception {
//        String formId =  KingDeeCons.WALLET_FKD;
//        //同步 反审的 付款单
//        RequestApiBean request = k3Logic.getInstance(orgId, orgNum, null, startTime, endTime);
//        request.setFormId(formId);
//        request.setNotTime(true);
//        String filterStr = "FDocumentStatus ='D'";
//        this.allSyncFkd1(request,filterStr);
//
//        //同步已审核的付款单
//        RequestApiBean request2 = k3Logic.getInstance(orgId, orgNum, formId, startTime, endTime);
//        String filterStr2 = "FDocumentStatus ='C' "+k3Logic.supplySql("FApproveDate", request2.getStartTime(), request2.getEndTime());
//        this.allSyncFkd1(request2,filterStr2);
//    }

//    private void allSyncFkd1(RequestApiBean request,String filterStr) throws Exception {
//        // 同步钱包接口
//        request.setFieldKeys("FPAYBILLENTRY_FEntryID,FBillNo,FDOCUMENTSTATUS,FREALPAYAMOUNTFOR_D,F_kls_Assistant1," +
//                " FCONTACTUNIT,FREALPAYAMOUNTFOR_D,FDATE,FSETTLEDISTAMOUNTFOR," +
//                " FSETTLETYPEID,FREMARK,FACCOUNTID, " +
//                "FSETTLEORGID,FPAYORGID,FCURRENCYID,FOUTCONTACTTYPE");
//        request.setFilterString(String.format(filterStr));
//        request.setOrderString("FID ASC");
//        String[] fields = new String[]{"id","billNo","status","amount","walletId",
//                "customerId","hAmount","theTime","discount",
//                "settleType","remark","bankAccount",
//                "settleOrg","skzz","bibie","customerType"};
//
//        List<KingDeeReceipt> objects = k3Logic.allSync(request, fields, KingDeeReceipt.class);
//        if (CollectionUtils.isEmpty(objects)) {
//            return;
//        }
//        objects.forEach(v -> v.setBillType("3").setId(v.getBillType() + v.getId()));
//        this.initAmount(objects);
//        //处理金额充值-----------------结束
//        kingDeeReceiptService.saveOrUpdateBatch(objects);
//    }





    /**
     * 现金钱包金额充值/反审
     * @param objects
     * @throws InterruptedException
     */
//    public void initAmount(List<KingDeeReceipt> objects) throws InterruptedException {
//        //一键生成经销商钱包
//        List<String> customerIds = objects.stream().filter(v -> v != null && StringUtils.isNotEmpty(v.getWalletId()))
//                .map(KingDeeReceipt::getCustomerId).distinct().collect(Collectors.toList());
//        for (String customerId : customerIds) {
//            walletLogic.initByK3Customer(customerId);
//        }
//
//        List<CustomerWalletAmountBean> customerWalletAmountBeans = new ArrayList<>();
//        //处理收款单/返利单逻辑/付款单
//        for(KingDeeReceipt kingDeeReceipt : objects){
//            if(kingDeeReceipt == null || (!kingDeeReceipt.getStatus().equals("C") && !kingDeeReceipt.getStatus().equals("D"))){
//                continue;
//            }
//            if(StringUtils.isEmpty(kingDeeReceipt.getWalletId().trim()) || StringUtils.isEmpty(kingDeeReceipt.getCustomerId().trim())){
//                continue;
//            }
//
//            //本次同步过来的钱
//            BigDecimal amount = kingDeeReceipt.getAmount();
//            if(kingDeeReceipt.getStatus().equals("D")) {
//                amount = BigDecimal.valueOf(0);
//            }
//
//            //检查是否存在反审过来的单,如果之前存在审核通过的单，又有相同的单过来，代表该单这次被反审了，需要减掉它
//            KingDeeReceipt oldBill = kingDeeReceiptService.getById(kingDeeReceipt.getId());
//            if(oldBill != null && oldBill.getStatus().equals("C")){
//                BigDecimal subAmount = BigDecimal.valueOf(0).subtract(oldBill.getAmount());
//                customerWalletAmountBeans.add(this.doAmount(oldBill,subAmount,oldBill.getRemark()));
//            }
//
//            customerWalletAmountBeans.add(this.doAmount(kingDeeReceipt,amount,kingDeeReceipt.getRemark()));
//        }
//        walletLogic.doWalletAmount(customerWalletAmountBeans);
//
//    }


//    private CustomerWalletAmountBean doAmount(KingDeeReceipt kingDeeReceipt,BigDecimal amountParam,String remark) throws InterruptedException {
//        String customerId = kingDeeReceipt.getCustomerId();
//        String walletId = kingDeeReceipt.getWalletId();
//        String billType = kingDeeReceipt.getBillType();//1=收款单  2=退款单   3=付款单
//        String id = kingDeeReceipt.getId();
//
//        //退款单 和 付款单 要反着来
//        if("3".equals(billType) || "2".equals(billType)){
//            amountParam = BigDecimal.valueOf(0).subtract(amountParam);
//        }
//
//        double amount = amountParam.stripTrailingZeros().doubleValue();
//        if(amount == 0){
//            return null;
//        }
//        if(StringUtils.isEmpty(customerId) || StringUtils.isEmpty(walletId)){
//            return null;
//        }
//        CustomerWallet customerWallet = walletLogic.queryCustomerWallet(customerId, walletId);
//        if(customerWallet == null){
//            return null;
//        }
//
//        if(amount > 0) {
//            String billName = "";
//            if(billType.equals("1")){
//                billName = Constant.BILL_TYPE_SKD;
//            }else if(billType.equals("2")){
//                billName = Constant.BILL_TYPE_TKD;
//            }else{
//                billName = Constant.BILL_TYPE_FKD;
//            }
//            if(customerWallet != null){
//                return new CustomerWalletAmountBean(customerWallet.getCustomerWalletId(), amountParam, remark, billName, new Date(), id, 1, "add");
//            }
//        } else{
//            String billName = "";
//            if(billType.equals("1")){
//                billName = Constant.BILL_TYPE_SKD;
//            }else if(billType.equals("2")){
//                billName = Constant.BILL_TYPE_TKD;
//            }else{
//                billName = Constant.BILL_TYPE_FKD;
//            }
//            BigDecimal a = BigDecimal.valueOf(0).subtract(amountParam);
//            return new CustomerWalletAmountBean(customerWallet.getCustomerWalletId(), a, remark, billName, new Date(), id, 1,"sub");
//        }
//        return null;
//    }




    /**
     * 弃审
     */
    @Transactional
    public void abandon(String id) throws InterruptedException {
        KingDeeReceipt kingDeeReceipt = kingDeeReceiptService.getById(id);
        BigDecimal amount = kingDeeReceipt.getAmount();
        String walletId = kingDeeReceipt.getWalletId();
        String customerId = kingDeeReceipt.getCustomerId();
        String billType = kingDeeReceipt.getBillType();

        if(kingDeeReceipt.getStatus().equals("D")){
            throw new RemoteServiceException("请勿重复弃审");
        }

        kingDeeReceipt.setStatus("D");//状态 A=保存 B=审核中 C=已审核 D=重新审核
        kingDeeReceipt.updateById();

        CustomerWallet customerWallet = walletLogic.queryCustomerWallet(customerId, walletId);
        if(customerWallet == null){
            return ;
        }

        if(billType.equals("1")){
            //收款单弃审，把钱减掉
            CustomerWalletAmountBean customerWalletAmountBean = new CustomerWalletAmountBean(customerWallet.getCustomerWalletId(), amount, "收款单弃审", Constant.BILL_TYPE_SKDFS,
                    kingDeeReceipt.getTheTime(), kingDeeReceipt.getBillNo(), 1, "sub");
            walletLogic.doWalletAmount(customerWalletAmountBean);
        }else if(billType.equals("2")){
            //退款单弃审，把钱减掉
            CustomerWalletAmountBean customerWalletAmountBean = new CustomerWalletAmountBean(customerWallet.getCustomerWalletId(),amount,"退款单弃审",Constant.BILL_TYPE_TKDFS,
                    kingDeeReceipt.getTheTime(),kingDeeReceipt.getBillNo(),1,"add");
            walletLogic.doWalletAmount(customerWalletAmountBean);
        }else{
            //付款单弃审，把钱还原
            CustomerWalletAmountBean customerWalletAmountBean = new CustomerWalletAmountBean(customerWallet.getCustomerWalletId(),amount,"付款单弃审",Constant.BILL_TYPE_FKDFS,
                    kingDeeReceipt.getTheTime(),kingDeeReceipt.getBillNo(),1,"add");
            walletLogic.doWalletAmount(customerWalletAmountBean);
        }
    }

    public void add(KingDeeReceipt kingDeeWallet) {
        kingDeeWallet.setTheTime(new Date());
        kingDeeWallet.insert();
    }

    public void update(KingDeeReceipt kingDeeWallet) {
        kingDeeWallet.updateById();
    }


    @Transactional(rollbackFor = Exception.class)
    public void examine(String billNo, String cancelStatus) throws InterruptedException {

        KingDeeReceipt kingDeeReceipt = kingDeeReceiptService.getById(billNo);
        kingDeeReceipt.setStatus(cancelStatus);
        kingDeeReceipt.updateById();

        if (kingDeeReceipt.getStatus().equals(ExamineStatusEnum.OK.getKey())) {
            List<KingDeeReceipt> kingDeeReceipts = new ArrayList<>();
            kingDeeReceipts.add(kingDeeReceipt);
            this.initAmount(kingDeeReceipts);
        }
    }



    /**
     * 现金钱包金额充值/反审
     * @param objects
     * @throws InterruptedException
     */
    public void initAmount(List<KingDeeReceipt> objects) throws InterruptedException {
        //一键生成经销商钱包
//        List<String> customerIds = objects.stream().filter(v -> v != null && StringUtils.isNotEmpty(v.getWalletId()))
//                .map(KingDeeReceipt::getCustomerId).distinct().collect(Collectors.toList());
//        for (String customerId : customerIds) {
//            walletLogic.initByK3Customer(customerId);
//        }
        walletLogic.initByK3Customer(null);
        log.info("收款单/退款单/付款单："+ JSONObject.toJSONString(objects));

        List<CustomerWalletAmountBean> customerWalletAmountBeans = new ArrayList<>();
        //处理收款单/返利单逻辑/付款单
        for(KingDeeReceipt kingDeeReceipt : objects){
            if(kingDeeReceipt == null || (!kingDeeReceipt.getStatus().equals("C") && !kingDeeReceipt.getStatus().equals("D"))){
                continue;
            }
            if(org.apache.commons.lang3.StringUtils.isEmpty(kingDeeReceipt.getWalletId().trim()) || org.apache.commons.lang3.StringUtils.isEmpty(kingDeeReceipt.getCustomerId().trim())){
                continue;
            }

            //本次同步过来的钱
            BigDecimal amount = kingDeeReceipt.getAmount();
            if(kingDeeReceipt.getStatus().equals("D")) {
                amount = BigDecimal.valueOf(0);
            }

            //检查是否存在反审过来的单,如果之前存在审核通过的单，又有相同的单过来，代表该单这次被反审了，需要减掉它
            KingDeeReceipt oldBill = kingDeeReceiptService.getById(kingDeeReceipt.getId());
            if(oldBill != null && oldBill.getExamineTime() != null && kingDeeReceipt.getExamineTime() != null
                    && oldBill.getExamineTime().getTime() == kingDeeReceipt.getExamineTime().getTime()){
                log.info("【重复同步的收款单/付款单】id:"+kingDeeReceipt.getId());
                continue;
            }
            if(oldBill != null && oldBill.getStatus().equals("C")){
                BigDecimal subAmount = BigDecimal.valueOf(0).subtract(oldBill.getAmount());
                customerWalletAmountBeans.add(this.doAmount(oldBill,subAmount,oldBill.getRemark()));
            }

            customerWalletAmountBeans.add(this.doAmount(kingDeeReceipt,amount,kingDeeReceipt.getRemark()));
        }
        walletLogic.doWalletAmount(customerWalletAmountBeans);
    }



    private CustomerWalletAmountBean doAmount(KingDeeReceipt kingDeeReceipt,BigDecimal amountParam,String remark) throws InterruptedException {
        String customerId = kingDeeReceipt.getCustomerId();
        String walletId = kingDeeReceipt.getWalletId();
        String billType = kingDeeReceipt.getBillType();//1=收款单  2=退款单   3=付款单
        String billNo = kingDeeReceipt.getBillNo();

        //退款单 和 付款单 要反着来
        if("3".equals(billType) || "2".equals(billType)){
            amountParam = BigDecimal.valueOf(0).subtract(amountParam);
        }

        double amount = amountParam.stripTrailingZeros().doubleValue();
        if(amount == 0){
            return null;
        }
        if(StringUtils.isEmpty(customerId) || StringUtils.isEmpty(walletId)){
            return null;
        }
        CustomerWallet customerWallet = walletLogic.queryCustomerWallet(customerId, walletId);
        if(customerWallet == null){
            return null;
        }
        if(amount > 0) {
            String billName = "";
            if(billType.equals("1")){
                billName = Constant.BILL_TYPE_SKD;
            }else if(billType.equals("2")){
                billName = Constant.BILL_TYPE_TKD;
            }else{
                billName = Constant.BILL_TYPE_FKD;
            }
            return new CustomerWalletAmountBean(customerWallet.getCustomerWalletId(), amountParam, remark, billName, new Date(), billNo, 1, "add");
        } else{
            String billName = "";
            if(billType.equals("1")){
                billName = Constant.BILL_TYPE_SKD;
            }else if(billType.equals("2")){
                billName = Constant.BILL_TYPE_TKD;
            }else{
                billName = Constant.BILL_TYPE_FKD;
            }
            BigDecimal a = BigDecimal.valueOf(0).subtract(amountParam);
            return new CustomerWalletAmountBean(customerWallet.getCustomerWalletId(), a, remark, billName, new Date(),billNo , 1,"sub");
        }
    }



}
