package com.ssm.manage.service.impl;

import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.BigDecimalUtils;
import com.ssm.core.utils.ChuangLanBeanSmsUtil;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.core.utils.StoreParaUtils;
import com.ssm.manage.dao.SsmRepayTradeDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.extendEntity.StoreDaily;
import com.ssm.manage.mapper.RepayTradeListMapper;
import com.ssm.manage.query.*;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.service.*;
import com.ssm.manage.utils.Constant;
import com.ssm.manage.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class SsmRepayTradeServiceImpl extends BaseServiceImpl<RepayTradeList> implements SsmRepayTradeService {
    @Autowired
    private SsmDebtService ssmDebtService;

    @Autowired
    private ChuangLanBeanSmsUtil chuangLanBeanSmsUtil;

    @Autowired
    private SsmBaseStaffService ssmBaseStaffService;

    @Autowired
    private SsmCollectionTypeService ssmCollectionTypeService;

    @Autowired
    private SsmSalesmanService ssmSalesmanService;

    @Autowired
    private SsmPayService ssmPayService;

    @Autowired
    private SsmRechargeAccountService ssmRechargeAccountService;
    @Autowired
    private SsmRepayAccountListService ssmRepayAccountListService;

    @Autowired
    private SsmCourseAccountService ssmCourseAccountService;


    @Autowired
    private SsmAccountTradeRecordService ssmAccountTradeRecordService;

    @Autowired
    private SsmMemberCsService ssmMemberCsService;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;
    @Autowired
    private SsmRepayService ssmRepayService;

    @Autowired
    private SsmProjectService ssmProjectService;

    @Autowired
    private SsmRepayTradeDao dao;

    @Autowired
    private RepayTradeListMapper mapper;

    @Override
    public SsmRepayTradeDao getDao() {
        return dao;
    }

    @Override
    public List<RepayTradeList> selectList(RepayTradeList repayTradeList) {
        return dao.select(repayTradeList);
    }

    @Override
    public List<RepayTradeList> selectFKJ(RepayTradeRequest repayTradeList) {
        return dao.selectFKJ(repayTradeList);
    }
    @Override
    public List<RepayTradeList> selectFKJByDate(RepayTradeRequest repayTradeList) {
        return mapper.selectFKJByDate(repayTradeList);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int add(List<RepayTradeRequest> repayTradeLists, RepayList repayList) throws SmsException {
        int i = 0;
        for (RepayTradeRequest repayTradeRequest : repayTradeLists) {
//            if(repayTradeRequest.getDocType().equals("card_recharge")){
//                if(!repayTradeRequest.getStoreId().equals(repayList.getStoreId())){
//                    throw new SmsException(ResponseCode.MSG,"单据【"+repayTradeRequest.getDocNum()+"】是充值欠款，请到【"+repayTradeRequest.getStoreName()+"】进行还款");
//                }
//            }
            List<RepayAccountListRequest> repayAccountListRequests = repayTradeRequest.getRepayAccountListRequests();
            //校验还款金额和欠款金额是否相等
//            if (BigDecimalUtils.compareTo(repayTradeRequest.getPayMoney().add(repayTradeRequest.getPayRechargeMoney()), repayTradeRequest.getDebtMoney()) != 0) {
//                throw new SmsException(ResponseCode.NOT_EQUALS_REQUIREMENTS_S, "支付金额和欠款金额");
//            }
            BigDecimal payRechargeMoney = BigDecimal.valueOf(0);
            //交易卡付金额是否相等
            if(repayAccountListRequests!=null&&repayAccountListRequests.size()>0){

                for (RepayAccountListRequest repayAccountListRequest : repayAccountListRequests) {
                    if(repayAccountListRequest.getAccountType()==1){
                        CourseAccount courseAccount = new CourseAccount();
                        courseAccount.setId(repayAccountListRequest.getAccountId());
                        CourseAccount courseAccount1 = ssmCourseAccountService.selectByPrimaryKey(courseAccount.getId());
                        if(courseAccount1!=null)
                        if(courseAccount1.getCourseRestPrice().compareTo(courseAccount1.getCourseConsumePrice())!=0){
                            throw new SmsException(ResponseCode.MSG, "支付的疗程卡："+courseAccount1.getCourseProjectName()+"存在欠款，不允许支付，请先取消欠款");
                        }
                    }
                    payRechargeMoney=payRechargeMoney.add(repayAccountListRequest.getPayMoney());
                }
//                if(payRechargeMoney.compareTo(repayTradeRequest.getPayRechargeMoney())!=0){
//                    throw new SmsException(ResponseCode.MSG, "卡付金额不等于每张卡的支付金额");
//                }
            }

            RepayTradeList repayTradeList = new RepayTradeList();
            BeanUtils.copyProperties(repayTradeRequest, repayTradeList);



            repayTradeList.setRepayNum(repayList.getRepayNum());

            repayTradeList.setRepayDate(repayList.getRepayDate());
            repayTradeList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            //设置业务人员
            List<StaffRequest> staffRequests = repayTradeRequest.getStaffRequests();
            if(staffRequests!=null&&staffRequests.size()>0){
                StaffRequest staffRequest = staffRequests.get(0);
                if(staffRequest.getId()!=null) {
                    BaseStaff baseStaff = ssmBaseStaffService.selectByPrimaryKey(staffRequest.getId());
                    if (!(baseStaff.getStoreId() == repayTradeList.getStoreId()) && !(baseStaff.getStoreId().equals(repayTradeList.getStoreId()))) {
                        repayTradeList.setStoreId(repayList.getStoreId());
                        repayTradeList.setStoreName(repayList.getStoreName());
                    } else {
                        repayList.setStoreId(baseStaff.getStoreId());
                        repayList.setStoreName(baseStaff.getStoreName());
                    }
                }
            }
            BigDecimal reduce3 = staffRequests.stream().map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
            if(null != reduce3 && reduce3.compareTo(BigDecimal.valueOf(100))!=0 && reduce3.compareTo(BigDecimal.valueOf(0))!=0){
                throw new SmsException(ResponseCode.MSG,"业务员业绩占比和不等于100");
            }
            this.setStaffValue(staffRequests, repayTradeList);

            //计算业绩
            this.setAchiComm(repayTradeList,repayTradeRequest.getCourseMoney());
            //修改欠款单
            DebtList debtList = ssmDebtService.selectByPrimaryKey(repayTradeRequest.getDebtId());

            repayTradeList.setBelongingStoreId(debtList.getStoreId());
            repayTradeList.setBelongingStoreName(debtList.getStoreName());
            if(repayTradeList.getAccountId()==null){
                CourseAccount courseAccount = new CourseAccount();
                courseAccount.setCourseNum(repayTradeRequest.getDocNum());
                courseAccount.setCourseProjectId(repayTradeRequest.getTradeId());
                courseAccount.setMemberId(repayTradeRequest.getMemberId());
                courseAccount = ssmCourseAccountService.selectOne(courseAccount);
                if(courseAccount!=null){
                    repayTradeList.setAccountId(courseAccount.getId());
                    repayTradeRequest.setAccountId(courseAccount.getId());
                }
            }

            //校验还款金额和欠款金额
            if (BigDecimalUtils.compareTo(repayTradeRequest.getPayMoney(), debtList.getDebtMoney()) == 1){
                throw new SmsException(ResponseCode.PRICE_COMPARE_MORE_THAN, "支付金额比欠款金额");
            }
            debtList.setDebtMoney(debtList.getDebtMoney().subtract(repayTradeRequest.getPayMoney()));
            //欠款金额修改
            BigDecimal totalMoney = BigDecimal.valueOf(0);
            try {
                if(null != repayAccountListRequests){
                    //添加每张卡的支付记录和扣除金额
                    for (RepayAccountListRequest repayAccountListRequest : repayAccountListRequests) {
                        totalMoney=totalMoney.add(repayAccountListRequest.getPayMoney());
                        repayAccountListRequest.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                        repayAccountListRequest.setStoreId(repayAccountListRequest.getStoreId());
                        repayAccountListRequest.setStoreName(repayAccountListRequest.getStoreName());
                        repayAccountListRequest.setRepayNum(repayAccountListRequest.getRepayNum());
                        repayAccountListRequest.setRepayTradeId(repayTradeList.getId());
                        RepayAccountList repayAccountList = new RepayAccountList();
                        BeanUtils.copyProperties(repayAccountListRequest,repayAccountList);
                        int save = ssmRepayAccountListService.save(repayAccountList);
                        if(save>0){
                            if(repayAccountListRequest.getAccountType()==0){ //充值支付
                                ssmRechargeAccountService.repayRechargeAccount(repayAccountListRequest,repayTradeRequest,repayList);
                            }else{ //疗程支付
                                ssmCourseAccountService.repayCourseAccount(repayAccountListRequest,repayTradeRequest,repayList);
                            }
                        }else{
                            throw new SmsException(ResponseCode.MSG,"保存卡包支付记录出错");
                        }

                    }
                }

                //欠款等于0 全部还清 修改状态为1
                if (BigDecimalUtils.compareTo(debtList.getDebtMoney(),BigDecimalUtils.bigDecimal("0")) == 0){
                    debtList.setState(1);
                }
//                debtList.setDebtMoney(debtMoneyBd);
//                充值还款
                repayTradeList.setPayRechargeMoney(totalMoney);
//                repayTradeList.setPayMoney(repayTradeList.getPayMoney().add(repayTradeList.getPayRechargeMoney()));
                if (Constant.doc_type_recharge.equals(repayTradeList.getDocType())) {
                    //更新充值账户
                    ssmRechargeAccountService.repayNew(repayTradeList, repayList,debtList);
                } else if (Constant.doc_type_card_use.equals(repayTradeList.getDocType())||Constant.doc_type_card_change.equals(repayTradeList.getDocType())) {//疗程还款
                    //更新疗程账户
                    ssmCourseAccountService.repayNew(repayTradeList, repayList, debtList);
                }else if (Constant.promotion_card_use.equals(repayTradeList.getDocType())) {
                    //促销疗程账户
                    ssmCourseAccountService.repayPromotionNew(repayTradeList, repayList,debtList);
                }
//                repayTradeList.setPayMoney(repayTradeList.getPayMoney().subtract(repayTradeList.getPayRechargeMoney()));
                //添加明细
                repayTradeList.setBelongingStoreId(debtList.getStoreId());
                repayTradeList.setBelongingStoreName(debtList.getStoreName());
                i = dao.saveNotNull(repayTradeList);
//                if(i>0){
//                    ssmDebtService.updateNotNull(debtList);
//                }
                if(null != repayTradeRequest.getSalesmens()){
                    List<Salesman> salesmens = repayTradeRequest.getSalesmens();
                    for (Salesman salesmen : salesmens) {
                        Random r = new Random(3);
                        int i1 = r.nextInt();
                        salesmen.setId(salesmen.getId()+i1);
                        salesmen.setOrderId(String.valueOf(repayTradeList.getId()));
                        salesmen.setOrderNum(repayTradeList.getRepayNum());
                        salesmen.setOrderType(7);
                        salesmen.setOrderDate(new Date());
                        salesmen.setState(0);
                        salesmen.setOperatorBy(repayList.getInputBy());
                        salesmen.setMoney(repayTradeList.getRepayMoney());
                    }
                    ssmSalesmanService.addBatch(salesmens);
                }
            } catch (Exception e) {
                log.error("SsmRepayTradeServiceImpl.add:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }

            //将还款单据信息添加到评价表
            MemberCsRequest memberCsRequest = new MemberCsRequest();
            BeanUtils.copyProperties(repayTradeList, memberCsRequest);
            memberCsRequest.setDocId(repayList.getId());

            memberCsRequest.setDocNum(repayList.getRepayNum());

            memberCsRequest.setDocType(Constant.doc_type_repay);
            memberCsRequest.setDocDate(repayList.getRepayDate());
            StringBuffer staffIds = new StringBuffer();
            StringBuffer staffNames = new StringBuffer();
            if (repayTradeRequest.getStaffRequests().size() > 0) {
                for (StaffRequest staffRequest : repayTradeRequest.getStaffRequests()) {
                    staffIds = staffIds.append(staffRequest.getId());
                    staffNames = staffNames.append(staffRequest.getStaffName());
                }
            }
            ssmMemberCsService.addMemberCs(memberCsRequest);

           if ( repayList.getIsSendSms()==1){
               //发送短信
               BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(repayList.getStoreId());
               //设置短信账户 发送 否则不发送
               if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
                   try {
                       chuangLanBeanSmsUtil.sendRepaySmsNew(baseStore, repayList.getMobilePhone(), repayTradeList.getTradeName(), repayTradeList.getRepayMoney() ,repayTradeList.getDocType());
                   } catch (IOException e) {
                       log.error("SsmRepayTradeServiceImpl.add:", e);
                   } catch (SmsException e) {
                       log.error("SsmRepayTradeServiceImpl.add:", e);
                   }
               }
           }
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int addPromotionRecharge(List<RepayTradeRequest> repayTradeLists, RepayList repayList) throws SmsException {
        int i = 0;
        for (RepayTradeRequest repayTradeRequest : repayTradeLists) {
//            if(repayTradeRequest.getDocType().equals("card_recharge")){
//                if(!repayTradeRequest.getStoreId().equals(repayList.getStoreId())){
//                    throw new SmsException(ResponseCode.MSG,"单据【"+repayTradeRequest.getDocNum()+"】是充值欠款，请到【"+repayTradeRequest.getStoreName()+"】进行还款");
//                }
//            }
            List<RepayAccountListRequest> repayAccountListRequests = repayTradeRequest.getRepayAccountListRequests();
            //校验还款金额和欠款金额是否相等
//            if (BigDecimalUtils.compareTo(repayTradeRequest.getPayMoney().add(repayTradeRequest.getPayRechargeMoney()), repayTradeRequest.getDebtMoney()) != 0) {
//                throw new SmsException(ResponseCode.NOT_EQUALS_REQUIREMENTS_S, "支付金额和欠款金额");
//            }
            BigDecimal payRechargeMoney = BigDecimal.valueOf(0);
            //交易卡付金额是否相等
            if(repayAccountListRequests!=null&&repayAccountListRequests.size()>0){

                for (RepayAccountListRequest repayAccountListRequest : repayAccountListRequests) {
                    if(repayAccountListRequest.getAccountType()==1){
                        CourseAccount courseAccount = new CourseAccount();
                        courseAccount.setId(repayAccountListRequest.getAccountId());
                        CourseAccount courseAccount1 = ssmCourseAccountService.selectByPrimaryKey(courseAccount.getId());
                        if(courseAccount1!=null)
                            if(courseAccount1.getCourseRestPrice().compareTo(courseAccount1.getCourseConsumePrice())!=0){
                                throw new SmsException(ResponseCode.MSG, "支付的疗程卡："+courseAccount1.getCourseProjectName()+"存在欠款，不允许支付，请先取消欠款");
                            }
                    }
                    payRechargeMoney=payRechargeMoney.add(repayAccountListRequest.getPayMoney());
                }
//                if(payRechargeMoney.compareTo(repayTradeRequest.getPayRechargeMoney())!=0){
//                    throw new SmsException(ResponseCode.MSG, "卡付金额不等于每张卡的支付金额");
//                }
            }

            RepayTradeList repayTradeList = new RepayTradeList();
            BeanUtils.copyProperties(repayTradeRequest, repayTradeList);



            repayTradeList.setRepayNum(repayList.getRepayNum());

            repayTradeList.setRepayDate(repayList.getRepayDate());
            repayTradeList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            //设置业务人员
            List<StaffRequest> staffRequests = repayTradeRequest.getStaffRequests();
            if(staffRequests!=null&&staffRequests.size()>0){
                StaffRequest staffRequest = staffRequests.get(0);
                if(staffRequest.getId()!=null) {
                    BaseStaff baseStaff = ssmBaseStaffService.selectByPrimaryKey(staffRequest.getId());
                    if (!(baseStaff.getStoreId() == repayTradeList.getStoreId()) && !(baseStaff.getStoreId().equals(repayTradeList.getStoreId()))) {
                        repayTradeList.setStoreId(repayList.getStoreId());
                        repayTradeList.setStoreName(repayList.getStoreName());
                    } else {
                        repayList.setStoreId(baseStaff.getStoreId());
                        repayList.setStoreName(baseStaff.getStoreName());
                    }
                }
            }
            BigDecimal reduce3 = staffRequests.stream().map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
            if(null != reduce3 && reduce3.compareTo(BigDecimal.valueOf(100))!=0 && reduce3.compareTo(BigDecimal.valueOf(0))!=0){
                throw new SmsException(ResponseCode.MSG,"业务员业绩占比和不等于100");
            }
            this.setStaffValue(staffRequests, repayTradeList);

            //计算业绩
            this.setAchiComm(repayTradeList,repayTradeRequest.getCourseMoney());
            //修改欠款单
            DebtList debtList = ssmDebtService.selectByPrimaryKey(repayTradeRequest.getDebtId());

            repayTradeList.setBelongingStoreId(debtList.getStoreId());
            repayTradeList.setBelongingStoreName(debtList.getStoreName());
            if(repayTradeList.getAccountId()==null){
                CourseAccount courseAccount = new CourseAccount();
                courseAccount.setCourseNum(repayTradeRequest.getDocNum());
                courseAccount.setCourseProjectId(repayTradeRequest.getTradeId());
                courseAccount.setMemberId(repayTradeRequest.getMemberId());
                courseAccount = ssmCourseAccountService.selectOne(courseAccount);
                if(courseAccount!=null){
                    repayTradeList.setAccountId(courseAccount.getId());
                    repayTradeRequest.setAccountId(courseAccount.getId());
                }
            }

            //校验还款金额和欠款金额
            if (BigDecimalUtils.compareTo(repayTradeRequest.getPayMoney(), debtList.getDebtMoney()) == 1){
                throw new SmsException(ResponseCode.PRICE_COMPARE_MORE_THAN, "支付金额比欠款金额");
            }
            debtList.setDebtMoney(debtList.getDebtMoney().subtract(repayTradeRequest.getPayMoney()));
            //欠款金额修改
            BigDecimal totalMoney = BigDecimal.valueOf(0);
            try {
                if(null != repayAccountListRequests){
                    //添加每张卡的支付记录和扣除金额
                    for (RepayAccountListRequest repayAccountListRequest : repayAccountListRequests) {
                        totalMoney=totalMoney.add(repayAccountListRequest.getPayMoney());
                        repayAccountListRequest.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                        repayAccountListRequest.setStoreId(repayAccountListRequest.getStoreId());
                        repayAccountListRequest.setStoreName(repayAccountListRequest.getStoreName());
                        repayAccountListRequest.setRepayNum(repayAccountListRequest.getRepayNum());
                        repayAccountListRequest.setRepayTradeId(repayTradeList.getId());
                        RepayAccountList repayAccountList = new RepayAccountList();
                        BeanUtils.copyProperties(repayAccountListRequest,repayAccountList);
                        int save = ssmRepayAccountListService.save(repayAccountList);
                        if(save>0){
                            if(repayAccountListRequest.getAccountType()==0){ //充值支付
                                ssmRechargeAccountService.repayRechargeAccount(repayAccountListRequest,repayTradeRequest,repayList);
                            }else{ //疗程支付
                                ssmCourseAccountService.repayCourseAccount(repayAccountListRequest,repayTradeRequest,repayList);
                            }
                        }else{
                            throw new SmsException(ResponseCode.MSG,"保存卡包支付记录出错");
                        }

                    }
                }

                //欠款等于0 全部还清 修改状态为1
                if (BigDecimalUtils.compareTo(debtList.getDebtMoney(),BigDecimalUtils.bigDecimal("0")) == 0){
                    debtList.setState(1);
                }
//                debtList.setDebtMoney(debtMoneyBd);
//                充值还款
                repayTradeList.setPayRechargeMoney(totalMoney);
//                repayTradeList.setPayMoney(repayTradeList.getPayMoney().add(repayTradeList.getPayRechargeMoney()));
                if (Constant.doc_type_recharge.equals(repayTradeList.getDocType())) {
                    //更新充值账户
                    ssmRechargeAccountService.repayNewPromotionRecharge(repayTradeList, repayList,debtList);
                } else if (Constant.doc_type_card_use.equals(repayTradeList.getDocType())||Constant.doc_type_card_change.equals(repayTradeList.getDocType())) {//疗程还款
                    //更新疗程账户
                    ssmCourseAccountService.repayNew(repayTradeList, repayList, debtList);
                }else if (Constant.promotion_card_use.equals(repayTradeList.getDocType())) {
                    //促销疗程账户
                    ssmCourseAccountService.repayPromotionNewByRecharge(repayTradeList, repayList,debtList);
                }
//                repayTradeList.setPayMoney(repayTradeList.getPayMoney().subtract(repayTradeList.getPayRechargeMoney()));
                //添加明细
                repayTradeList.setBelongingStoreId(debtList.getStoreId());
                repayTradeList.setBelongingStoreName(debtList.getStoreName());
                i = dao.saveNotNull(repayTradeList);
//                if(i>0){
//                    ssmDebtService.updateNotNull(debtList);
//                }
                if(null != repayTradeRequest.getSalesmens()){
                    List<Salesman> salesmens = repayTradeRequest.getSalesmens();
                    for (Salesman salesmen : salesmens) {
                        Random r = new Random(3);
                        int i1 = r.nextInt();
                        salesmen.setId(salesmen.getId()+i1);
                        salesmen.setOrderId(String.valueOf(repayTradeList.getId()));
                        salesmen.setOrderNum(repayTradeList.getRepayNum());
                        salesmen.setOrderType(7);
                        salesmen.setOrderDate(new Date());
                        salesmen.setState(0);
                        salesmen.setOperatorBy(repayList.getInputBy());
                        salesmen.setMoney(repayTradeList.getRepayMoney());
                    }
                    ssmSalesmanService.addBatch(salesmens);
                }
            } catch (Exception e) {
                log.error("SsmRepayTradeServiceImpl.add:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }

            //将还款单据信息添加到评价表
            MemberCsRequest memberCsRequest = new MemberCsRequest();
            BeanUtils.copyProperties(repayTradeList, memberCsRequest);
            memberCsRequest.setDocId(repayList.getId());

            memberCsRequest.setDocNum(repayList.getRepayNum());

            memberCsRequest.setDocType(Constant.doc_type_repay);
            memberCsRequest.setDocDate(repayList.getRepayDate());
            StringBuffer staffIds = new StringBuffer();
            StringBuffer staffNames = new StringBuffer();
            if (repayTradeRequest.getStaffRequests().size() > 0) {
                for (StaffRequest staffRequest : repayTradeRequest.getStaffRequests()) {
                    staffIds = staffIds.append(staffRequest.getId());
                    staffNames = staffNames.append(staffRequest.getStaffName());
                }
            }
            ssmMemberCsService.addMemberCs(memberCsRequest);

            if ( repayList.getIsSendSms()==1){
                //发送短信
                BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(repayList.getStoreId());
                //设置短信账户 发送 否则不发送
                if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
                    try {
                        chuangLanBeanSmsUtil.sendRepaySmsNew(baseStore, repayList.getMobilePhone(), repayTradeList.getTradeName(), repayTradeList.getRepayMoney() ,repayTradeList.getDocType());
                    } catch (IOException e) {
                        log.error("SsmRepayTradeServiceImpl.add:", e);
                    } catch (SmsException e) {
                        log.error("SsmRepayTradeServiceImpl.add:", e);
                    }
                }
            }
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int cancel(List<RepayTradeRequest> repayTradeLists, RepayList repayList) throws SmsException {
        SimpleDateFormat simpleDateFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int i = 0;
        for (RepayTradeRequest repayTradeRequest : repayTradeLists) {
            RepayTradeList repayTradeList = new RepayTradeList();
            BeanUtils.copyProperties(repayTradeRequest, repayTradeList);
            RepayTradeList repayTradeList2 = dao.selectByPrimaryKey(repayTradeRequest.getId());
            RepayTradeList repayTradeList1 = new RepayTradeList();
            repayTradeList1.setDebtId(repayTradeRequest.getDebtId());
            List<RepayTradeList> select2 = dao.select(repayTradeList1);
            for (RepayTradeList tradeList : select2) {
                String format = simpleDateFormate.format(tradeList.getRepayDate());
                String format1 = simpleDateFormate.format(repayTradeList2.getRepayDate());
                if(tradeList.getRepayDate().after(repayTradeList2.getRepayDate())){
                    RepayList repayList1 = new RepayList();
                    repayList1.setRepayNum(tradeList.getRepayNum());
                    repayList1.setStoreId(tradeList.getStoreId());
                    RepayList repayList2 = ssmRepayService.selectOne(repayList1);
                    if(repayList2.getIsCancel()==0){
                        throw new SmsException(ResponseCode.MSG,"该还款单不能作废，因为该欠款单还存在更新的还款单据");
                    }
                }
            }

            try {
//                RepayAccountList repayAccountList1 = new RepayAccountList();
//                repayAccountList1.setRepayTradeId(repayTradeRequest.getId());
//                List<RepayAccountList> select1 = ssmRepayAccountListService.select(repayAccountList1);
//                BigDecimal totalMoney=BigDecimal.valueOf(0);
//                for (RepayAccountList repayAccountList : select1) {
//                    totalMoney=totalMoney.add(repayAccountList.getPayMoney());
//                }
//                repayTradeList.setPayMoney(repayTradeRequest.getPayMoney().add(totalMoney));
//                欠款单状态修改
                DebtList debtList = ssmDebtService.selectByPrimaryKey(repayTradeRequest.getDebtId());
                //欠款金额添加
                BigDecimal debtMoneyBd = BigDecimalUtils.add(debtList.getDebtMoney(),repayTradeList.getPayMoney());
                debtList.setDebtMoney(debtMoneyBd);
                //状态为1 作废时改为0
                if (debtList.getState() == 1){
                    debtList.setState(0);
                }
                RepayTradeList repayTradeList3 = dao.selectByPrimaryKey(repayTradeList.getId());
                //还款作废
                if (Constant.doc_type_recharge.equals(repayTradeList3.getDocType())) {
                    //更新充值账户

                    ssmRechargeAccountService.repayCancelNew(repayTradeList3, repayList, debtList);

                }
                else if (Constant.doc_type_card_use.equals(repayTradeList3.getDocType())||Constant.doc_type_card_change.equals(repayTradeList3.getDocType())) {//疗程还款
//                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
//                    String[] split = simpleDateFormat.format(debtList.getDocDate()).split("-");
//                    //开始日期
//                    Integer year =Integer.valueOf(split[0]);
//                    Integer month = 4;
//                    String months=split[1];
//                    Date startDate =null;
//                    Date startDates =null;
//
//                    //今天
//                    Date date = new Date();
//
//
//                    startDate= simpleDateFormat.parse(year+"-"+months);
//                    while (startDate.before(date)){
//                        AccountTradeRecordRequest accountTradeRecord = new AccountTradeRecordRequest();
//                        accountTradeRecord.setInputDate(startDate);
//                        accountTradeRecord.setAccountId(debtList.getAccountId());
//                        accountTradeRecord.setOrderStatu(0);
//                        List<AccountTradeRecord> accountTradeRecords = ssmAccountTradeRecordService.selectList(accountTradeRecord);
//                        if(null != accountTradeRecords && accountTradeRecords.size()>0){
//                            Integer years =Integer.valueOf(split[0]);
//                            Integer monthss = 4;
//                            String months1=split[1];
//
//                            startDates= simpleDateFormat.parse(year+"-"+months);
//                            List<AccountTradeRecord> accountTradeRecordRequests = new ArrayList<>();
//                            for (AccountTradeRecord tradeRecord : accountTradeRecords) {
//                                if(startDates.before(date)){
//                                    AccountTradeRecordRequest accountTradeRecord1 = new AccountTradeRecordRequest();
//                                    accountTradeRecord1.setDocId(tradeRecord.getDocId());
//                                    accountTradeRecord1.setInputDate(startDates);
//                                    List<AccountTradeRecord> accountTradeRecords1 = ssmAccountTradeRecordService.selectList(accountTradeRecord1);
//                                    if(accountTradeRecords1.size()>0){
//                                        for (AccountTradeRecord record : accountTradeRecords1) {
//                                            if(repayList.getRepayDate().before(record.getInputDate())){
//                                                accountTradeRecordRequests.add(record);
//                                            }
//
//                                        }
//                                    }
//
//                                }
//                                monthss++;
//                                if(monthss>12){
//                                    months1="01";
//                                    monthss=1;
//                                    years++;
//                                }else{
//                                    if(monthss<10){
//                                        months1="0"+monthss;
//                                    }else{
//                                        months1 =String.valueOf(monthss);
//                                    }
//                                }
//                                startDates= simpleDateFormat.parse(years+"-"+months1);
//                            }
//                            if(accountTradeRecordRequests.size()>0){
//                                if(accountTradeRecordRequests.size()%2!=0){
//                                    throw new SmsException(ResponseCode.MSG,"当前相关卡包在还款之后已经进行过交易，无法作废");
//                                }
//                            }
//
//                        }
//                        month++;
//                        if(month>12){
//                            months="01";
//                            month=1;
//                            year++;
//                        }else{
//                            if(month<10){
//                                months="0"+month;
//                            }else{
//                                months =String.valueOf(month);
//                            }
//                        }
//                        startDate= simpleDateFormat.parse(year+"-"+months);
//                    }

                    //更新疗程账户
                    int i1 = ssmCourseAccountService.repayCancelNew(repayTradeList3, repayList, debtList);
                    if(i1==8){
                        return 8;
                    }
                    if(i1==9){
                        return 9;
                    }
                }
                else if (Constant.promotion_card_use.equals(repayTradeList.getDocType())) {
                    //促销疗程账户
                    try{
                        ssmCourseAccountService.repayCancelPromotionNew(repayTradeList, repayList,debtList);
                    }catch(SmsException e){
                        throw new SmsException(ResponseCode.MSG,e.getMessage());
                    }
                }
                Salesman salesman = new Salesman();
                salesman.setOrderId(String.valueOf(repayTradeRequest.getId()));
                List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
                for (Salesman salesman1 : salesmen) {
                    salesman1.setState(1);
                    ssmSalesmanService.updateNotNull(salesman1);
                }


            }catch(SmsException e){
                throw new SmsException(ResponseCode.MSG,e.getMessage());
            } catch (Exception e) {
                log.error("SsmRepayTradeServiceImpl.cancel:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }

            //返回支付的卡包金额和次数
            RepayAccountList repayAccountList = new RepayAccountList();
            repayAccountList.setRepayTradeId(repayTradeList.getId());
            List<RepayAccountList> select = ssmRepayAccountListService.select(repayAccountList);
            if(null != select){
                for (RepayAccountList accountList : select) {
                    RepayAccountListRequest repayAccountListRequest = new RepayAccountListRequest();
                    BeanUtils.copyProperties(accountList,repayAccountListRequest);
                    int i1 = 0;
                    if(accountList.getAccountType()==0){ //充值支付
                        i1 = ssmRechargeAccountService.cancelRepayRechargeAccount(repayAccountListRequest, repayTradeRequest, repayList);
                    }else{ //疗程支付
                        i1 = ssmCourseAccountService.cancelRepayCourseAccount(repayAccountListRequest, repayTradeRequest, repayList);
                    }
                    if(i1==0){
                        throw new SmsException(ResponseCode.MSG,"返回卡剩余金额异常");
                    }
                }
            }
        }
        //将评价单进行删除操作
        MemberCs memberCs = new MemberCs();
        memberCs.setDocId(repayList.getId());
        ssmMemberCsService.delete(memberCs);
        return i;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int cancelPromotionRecharge(List<RepayTradeRequest> repayTradeLists, RepayList repayList) throws SmsException {
        SimpleDateFormat simpleDateFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int i = 0;
        for (RepayTradeRequest repayTradeRequest : repayTradeLists) {
            RepayTradeList repayTradeList = new RepayTradeList();
            BeanUtils.copyProperties(repayTradeRequest, repayTradeList);
            RepayTradeList repayTradeList2 = dao.selectByPrimaryKey(repayTradeRequest.getId());
            RepayTradeList repayTradeList1 = new RepayTradeList();
            repayTradeList1.setDebtId(repayTradeRequest.getDebtId());
            List<RepayTradeList> select2 = dao.select(repayTradeList1);
            for (RepayTradeList tradeList : select2) {
                String format = simpleDateFormate.format(tradeList.getRepayDate());
                String format1 = simpleDateFormate.format(repayTradeList2.getRepayDate());
                if(tradeList.getRepayDate().after(repayTradeList2.getRepayDate())){
                    RepayList repayList1 = new RepayList();
                    repayList1.setRepayNum(tradeList.getRepayNum());
                    repayList1.setStoreId(tradeList.getStoreId());
                    RepayList repayList2 = ssmRepayService.selectOne(repayList1);
                    if(repayList2.getIsCancel()==0){
                        throw new SmsException(ResponseCode.MSG,"该还款单不能作废，因为该欠款单还存在更新的还款单据");
                    }
                }
            }

            try {
//                RepayAccountList repayAccountList1 = new RepayAccountList();
//                repayAccountList1.setRepayTradeId(repayTradeRequest.getId());
//                List<RepayAccountList> select1 = ssmRepayAccountListService.select(repayAccountList1);
//                BigDecimal totalMoney=BigDecimal.valueOf(0);
//                for (RepayAccountList repayAccountList : select1) {
//                    totalMoney=totalMoney.add(repayAccountList.getPayMoney());
//                }
//                repayTradeList.setPayMoney(repayTradeRequest.getPayMoney().add(totalMoney));
//                欠款单状态修改
                DebtList debtList = ssmDebtService.selectByPrimaryKey(repayTradeRequest.getDebtId());
                //欠款金额添加
                BigDecimal debtMoneyBd = BigDecimalUtils.add(debtList.getDebtMoney(),repayTradeList.getPayMoney());
                debtList.setDebtMoney(debtMoneyBd);
                //状态为1 作废时改为0
                if (debtList.getState() == 1){
                    debtList.setState(0);
                }
                RepayTradeList repayTradeList3 = dao.selectByPrimaryKey(repayTradeList.getId());
                //还款作废
                if (Constant.doc_type_recharge.equals(repayTradeList3.getDocType())) {
                    //更新充值账户

                    ssmRechargeAccountService.repayCancelNewPromotionRecharge(repayTradeList3, repayList, debtList);

                }
                else if (Constant.doc_type_card_use.equals(repayTradeList3.getDocType())||Constant.doc_type_card_change.equals(repayTradeList3.getDocType())) {//疗程还款

                    //更新疗程账户
                    int i1 = ssmCourseAccountService.repayCancelNew(repayTradeList3, repayList, debtList);
                    if(i1==8){
                        return 8;
                    }
                    if(i1==9){
                        return 9;
                    }
                }
                else if (Constant.promotion_card_use.equals(repayTradeList.getDocType())) {
                    //促销疗程账户
                    try{
                        ssmCourseAccountService.cancelPromotionRecharge(repayTradeList, repayList,debtList);
                    }catch(SmsException e){
                        throw new SmsException(ResponseCode.MSG,e.getMessage());
                    }
                }
                Salesman salesman = new Salesman();
                salesman.setOrderId(String.valueOf(repayTradeRequest.getId()));
                List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
                for (Salesman salesman1 : salesmen) {
                    salesman1.setState(1);
                    ssmSalesmanService.updateNotNull(salesman1);
                }


            }catch(SmsException e){
                throw new SmsException(ResponseCode.MSG,e.getMessage());
            } catch (Exception e) {
                log.error("SsmRepayTradeServiceImpl.cancel:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }

            //返回支付的卡包金额和次数
            RepayAccountList repayAccountList = new RepayAccountList();
            repayAccountList.setRepayTradeId(repayTradeList.getId());
            List<RepayAccountList> select = ssmRepayAccountListService.select(repayAccountList);
            if(null != select){
                for (RepayAccountList accountList : select) {
                    RepayAccountListRequest repayAccountListRequest = new RepayAccountListRequest();
                    BeanUtils.copyProperties(accountList,repayAccountListRequest);
                    int i1 = 0;
                    if(accountList.getAccountType()==0){ //充值支付
                        i1 = ssmRechargeAccountService.cancelRepayRechargeAccount(repayAccountListRequest, repayTradeRequest, repayList);
                    }else{ //疗程支付
                        i1 = ssmCourseAccountService.cancelRepayCourseAccount(repayAccountListRequest, repayTradeRequest, repayList);
                    }
                    if(i1==0){
                        throw new SmsException(ResponseCode.MSG,"返回卡剩余金额异常");
                    }
                }
            }
        }
        //将评价单进行删除操作
        MemberCs memberCs = new MemberCs();
        memberCs.setDocId(repayList.getId());
        ssmMemberCsService.delete(memberCs);
        return i;
    }

    @Override
    public List<RepayTradeList> selectList(RepayListRequest repayListRequest) {
        return dao.selectList(repayListRequest);
    }
    @Override
    public List<RepayTradeList> selectLists(RepayListRequest repayListRequest) {
        return dao.selectLists(repayListRequest);
    }

    @Override
    public List<RepayTradeList> selectListBetween(RepayListRequest repayListRequest) {
        return dao.selectListBetween(repayListRequest);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int updateStaff(List<RepayTradeRequest> repayTradeRequests) throws SmsException {
        int i = 0;
        for (RepayTradeRequest repayTradeRequest : repayTradeRequests) {

            List<PayList> payLists = repayTradeRequest.getPayLists();
            for (PayList payList : payLists) {
                    BaseCollectionType baseCollectionType = ssmCollectionTypeService.selectByPrimaryKey(payList.getPayId());
                    payList.setPayName(baseCollectionType.getCollectionTypeName());
                        ssmPayService.updateNotNull(payList);
            }

            RepayTradeList repayTradeList = new RepayTradeList();
            BeanUtils.copyProperties(repayTradeRequest, repayTradeList);
            //设置业务员
            List<StaffRequest> staffLists = repayTradeRequest.getStaffRequests();
            BigDecimal reduce3 = staffLists.stream().map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
            if(null != reduce3 && reduce3.compareTo(BigDecimal.valueOf(100))!=0 && reduce3.compareTo(BigDecimal.valueOf(0))!=0){
                throw new SmsException(ResponseCode.MSG,"业务员业绩占比和不等于100");
            }
            this.setStaffValue(staffLists,repayTradeList);

            try {
                i = dao.updateStaff(repayTradeList);
                Salesman salesman = new Salesman();
                salesman.setOrderId(String.valueOf(repayTradeList.getId()));
                List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
                Date date = repayTradeRequest.getRepayDate();
                for (Salesman salesman1 : salesmen) {
                    date = salesman1.getOrderDate();
                    ssmSalesmanService.delete(salesman1);
                }
                BaseStore baseStore = new BaseStore();
                baseStore.setId(repayTradeRequest.getStoreId());
                BaseStore baseStore1 = ssmBaseStoreService.selectOne(baseStore);
                List<Salesman> salesmens = repayTradeRequest.getSalesmens();
                for (Salesman salesmen2 : salesmens) {
                    Random r = new Random(3);
                    int i1 = r.nextInt();
                    salesmen2.setId(salesmen2.getId()+i1);
                    salesmen2.setOrderId(String.valueOf(repayTradeList.getId()));
                    salesmen2.setOrderNum(repayTradeList.getRepayNum());
                    salesmen2.setOrderType(7);
                    salesmen2.setOrderDate(date);
                    salesmen2.setState(0);
                    salesmen2.setMoney(repayTradeList.getRepayMoney());
                    salesmen2.setStoreNum(baseStore1.getStoreNum());
                    salesmen2.setStoreName(baseStore1.getStoreName());
                    salesmen2.setStoreIdOrder(baseStore1.getId());
                }
                ssmSalesmanService.addBatch(salesmens);
            }catch (Exception e){
                log.error("SsmRepayTradeServiceImpl.updateStaff:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }

        }
        return i;
    }

    @Override
    public int updateStaff(RepayTradeRequest repayTradeRequest) throws SmsException {
        int i = 0;

        RepayTradeList repayTradeList = new RepayTradeList();
        BeanUtils.copyProperties(repayTradeRequest, repayTradeList);

        StoreParament storeParament = StoreParaUtils.getStorePara(repayTradeRequest.getStoreId(), Constant.editOrderNum);
        int days = (int) DateUtils.getDayDiff(repayTradeRequest.getRepayDate(), new Date());
        if(!"0".equals(storeParament.getParamentValue())) {
            if (Integer.parseInt(storeParament.getParamentValue()) < days) {
                throw new SmsException(ResponseCode.CANCEL_NOT_PERMISSIONS, "单据超过允许修改时间");
            }
        }

        //设置业务员
        List<StaffRequest> staffLists = repayTradeRequest.getStaffRequests();
        BigDecimal reduce3 = staffLists.stream().map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
        if(null != reduce3 && reduce3.compareTo(BigDecimal.valueOf(100))!=0 && reduce3.compareTo(BigDecimal.valueOf(0))!=0){
            throw new SmsException(ResponseCode.MSG,"业务员业绩占比和不等于100");
        }
        this.setStaffValue(staffLists,repayTradeList);
        try {
            i = dao.updateStaff(repayTradeList);
            Salesman salesman = new Salesman();
            salesman.setOrderType(7);
            salesman.setOrderId(String.valueOf(repayTradeList.getId()));
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            for (Salesman salesman1 : salesmen) {
                ssmSalesmanService.delete(salesman1);
            }
            BaseStore baseStore = new BaseStore();
            baseStore.setId(repayTradeRequest.getStoreId());
            BaseStore baseStore1 = ssmBaseStoreService.selectOne(baseStore);
            List<Salesman> salesmens = repayTradeRequest.getSalesmens();
            for (Salesman salesmen2 : salesmens) {
                Random r = new Random(3);
                int i1 = r.nextInt();
                salesmen2.setId(salesmen2.getId()+i1);
                salesmen2.setOrderId(String.valueOf(repayTradeList.getId()));
                salesmen2.setOrderNum(repayTradeList.getRepayNum());
                salesmen2.setOrderType(7);
                salesmen2.setOrderDate(new Date());
                salesmen2.setState(0);
                salesmen2.setMoney(repayTradeList.getRepayMoney());
                salesmen2.setStoreNum(baseStore1.getStoreNum());
                salesmen2.setStoreName(baseStore1.getStoreName());
                salesmen2.setStoreIdOrder(baseStore1.getId());
            }
            ssmSalesmanService.addBatch(salesmens);
        }catch (Exception e){
            log.error("SsmRepayTradeServiceImpl.updateStaff:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }


        return i;
    }

    @Override
    public StoreDaily selectrepayCooperate(StoreDailyRequest storeDailyRequest) {

        return dao.selectrepayCooperate(storeDailyRequest);
    }

    @Override
    public List<RepayTradeList> selectListNew(RepayListRequest repayListRequest) {
        return mapper.selectListNew(repayListRequest);
    }

    @Override
    public List<RepayTradeList> selectListByStartTimeAndEndTime(Long id, Date startTime, Date endTime) {
        return mapper.selectListByStartTimeAndEndTime(id,startTime,endTime);
    }

    /*
     * 业务员赋值
     * */
    public void setStaffValue(List<StaffRequest> staffLists, RepayTradeList repayTradeList) {

        for (int i = 0; i < staffLists.size(); i++) {
            StaffRequest staffRequest = staffLists.get(i);
            if (i == 0) {
                repayTradeList.setSaleOneStaffId(staffRequest.getId());
                repayTradeList.setSaleOneStaffName(staffRequest.getStaffName());
                repayTradeList.setSaleOneIdentity(staffRequest.getIdentityCard());
                repayTradeList.setSaleOneRatio(staffRequest.getRatio());
                repayTradeList.setSaleOneNumber(staffRequest.getBrandNumber());
            } else if (i == 1) {
                repayTradeList.setSaleTwoStaffId(staffRequest.getId());
                repayTradeList.setSaleTwoStaffName(staffRequest.getStaffName());
                repayTradeList.setSaleTwoIdentity(staffRequest.getIdentityCard());
                repayTradeList.setSaleTwoRatio(staffRequest.getRatio());
                repayTradeList.setSaleTwoNumber(staffRequest.getBrandNumber());
            } else if (i == 2) {
                repayTradeList.setSaleThreeStaffId(staffRequest.getId());
                repayTradeList.setSaleThreeStaffName(staffRequest.getStaffName());
                repayTradeList.setSaleThreeIdentity(staffRequest.getIdentityCard());
                repayTradeList.setSaleThreeRatio(staffRequest.getRatio());
                repayTradeList.setSaleThreeNumber(staffRequest.getBrandNumber());
            } else if(i==3){
                repayTradeList.setSaleFourStaffId(staffRequest.getId());
                repayTradeList.setSaleFourStaffName(staffRequest.getStaffName());
                repayTradeList.setSaleFourIdentity(staffRequest.getIdentityCard());
                repayTradeList.setSaleFourRatio(staffRequest.getRatio());
                repayTradeList.setSaleFourNumber(staffRequest.getBrandNumber());
            }
            if (i == 4) {
                repayTradeList.setSaleFiveStaffId(staffRequest.getId());
                repayTradeList.setSaleFiveStaffName(staffRequest.getStaffName());
                repayTradeList.setSaleFiveIdentity(staffRequest.getIdentityCard());
                repayTradeList.setSaleFiveRatio(staffRequest.getRatio());
                repayTradeList.setSaleFiveNumber(staffRequest.getBrandNumber());
            } else if (i == 5) {
                repayTradeList.setSaleSixStaffId(staffRequest.getId());
                repayTradeList.setSaleSixStaffName(staffRequest.getStaffName());
                repayTradeList.setSaleSixIdentity(staffRequest.getIdentityCard());
                repayTradeList.setSaleSixRatio(staffRequest.getRatio());
                repayTradeList.setSaleSixNumber(staffRequest.getBrandNumber());
            } else if (i == 6) {
                repayTradeList.setSaleSevenStaffId(staffRequest.getId());
                repayTradeList.setSaleSevenStaffName(staffRequest.getStaffName());
                repayTradeList.setSaleSevenIdentity(staffRequest.getIdentityCard());
                repayTradeList.setSaleSevenRatio(staffRequest.getRatio());
                repayTradeList.setSaleSevenNumber(staffRequest.getBrandNumber());
            } else if(i==7){
                repayTradeList.setSaleEightStaffId(staffRequest.getId());
                repayTradeList.setSaleEightStaffName(staffRequest.getStaffName());
                repayTradeList.setSaleEightIdentity(staffRequest.getIdentityCard());
                repayTradeList.setSaleEightRatio(staffRequest.getRatio());
                repayTradeList.setSaleEightNumber(staffRequest.getBrandNumber());
            }
        }
    }

    public RepayTradeList setAchiComm(RepayTradeList repayTradeList,BigDecimal courseMoney) {
        //疗程还款 业绩提成计算
        if (Constant.doc_type_card_use.equals(repayTradeList.getDocType())||Constant.doc_type_card_change.equals(repayTradeList.getDocType())) {
            BaseProject baseProject=ssmProjectService.selectByPrimaryKey(repayTradeList.getTradeId());

            CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(repayTradeList.getAccountId());
            //现付销售业绩标准  >0 <=1比率   >1固定金额
            BigDecimal achiRatio = baseProject.getSalesAchievement();
            //现付销售提成标准  >0 <=1比率   >1固定金额
            BigDecimal commRatio = baseProject.getSalesCommission();
            //卡付销售业绩标准  >0 <=1比率   >1固定金额
            BigDecimal cardAchiRatio = baseProject.getCardSalesAchievement();
            //卡付销售提成标准  >0 <=1比率   >1固定金额
            BigDecimal cardCommRatio = baseProject.getCardSalesCommission();
            repayTradeList.setAchievementAmount(new BigDecimal("0"));
            repayTradeList.setCardAchievementAmount(new BigDecimal("0"));


            //现付业绩
            if (BigDecimalUtils.compareTo(achiRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
                repayTradeList.setAchievementAmount(BigDecimalUtils.multiply(achiRatio, repayTradeList.getRepayMoney()));
            } else {
                //固定金额 还款金额/(成交金额/成交次数)*业绩标准
                repayTradeList.setAchievementAmount(BigDecimalUtils.multiply(
                        BigDecimalUtils.div(repayTradeList.getRepayMoney(),
                                BigDecimalUtils.div(courseAccount.getCourseProjectMoney(), BigDecimalUtils.bigDecimal(courseAccount.getCourseCount().toString()))), achiRatio));
            }
            //卡付业绩
            if (BigDecimalUtils.compareTo(cardAchiRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
                repayTradeList.setCardAchievementAmount(BigDecimalUtils.multiply(cardAchiRatio, courseMoney));
            } else {
                //固定金额 还款金额/(成交金额/成交次数)*业绩标准
                repayTradeList.setCardAchievementAmount(BigDecimalUtils.multiply(
                        BigDecimalUtils.div(courseMoney,
                                BigDecimalUtils.div(courseAccount.getCourseProjectMoney(), BigDecimalUtils.bigDecimal(courseAccount.getCourseCount().toString()))), cardAchiRatio));
            }

            BigDecimal AchiMoneyAmount=new BigDecimal("0");//现付合作业绩
            BigDecimal CardMoneyAmount=new BigDecimal("0");//卡付合作业绩
            //是否是合作项目,1=合作项目
            if(baseProject.getIsCooperation()==1){
                if(baseProject.getSmokeCommissionWay()==1) {//合作按比例
                    AchiMoneyAmount=repayTradeList.getPayMoney().multiply(baseProject.getBrokerage()).divide(BigDecimal.valueOf(100)
//                            .multiply(.divide(repayTradeList.getTradeMoney(),4,BigDecimal.ROUND_HALF_UP)),4,BigDecimal.ROUND_HALF_UP
                            );
                    CardMoneyAmount=repayTradeList.getCardAchievementAmount().multiply(baseProject.getBrokerage()).divide(BigDecimal.valueOf(100));
                }else{
                    AchiMoneyAmount=baseProject.getBrokerage().multiply(repayTradeList.getRepayMoney().divide(repayTradeList.getTradeMoney(),4,BigDecimal.ROUND_HALF_UP));
                    CardMoneyAmount=BigDecimal.valueOf(0);
                }
            }
            repayTradeList.setAchievementAmount(repayTradeList.getAchievementAmount().subtract(AchiMoneyAmount));
            repayTradeList.setCardAchievementAmount(repayTradeList.getCardAchievementAmount().subtract(CardMoneyAmount));


            //现付提成
            if (BigDecimalUtils.compareTo(commRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
                repayTradeList.setCommissionAmount(BigDecimalUtils.multiply(commRatio, repayTradeList.getAchievementAmount()));
            } else {
                //固定金额 还款金额/(成交金额/成交次数)*提成标准
                repayTradeList.setCommissionAmount(BigDecimalUtils.multiply(
                        BigDecimalUtils.div(repayTradeList.getPayMoney(),
                                BigDecimalUtils.div(courseAccount.getCourseProjectMoney(), BigDecimalUtils.bigDecimal(courseAccount.getCourseCount().toString()))), commRatio));
            }

            //卡付提成
            if (BigDecimalUtils.compareTo(cardCommRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
                repayTradeList.setCardCommissionAmount(BigDecimalUtils.multiply(cardCommRatio, repayTradeList.getCardAchievementAmount()));
            } else {
                //固定金额 还款金额/(成交金额/成交次数)*提成标准
                repayTradeList.setCardCommissionAmount(BigDecimalUtils.multiply(
                        BigDecimalUtils.div(courseMoney,
                                BigDecimalUtils.div(courseAccount.getCourseProjectMoney(), BigDecimalUtils.bigDecimal(courseAccount.getCourseCount().toString()))), cardCommRatio));
            }

        }else if (Constant.doc_type_recharge.equals(repayTradeList.getDocType())){//充值卡还款
            RechargeAccount rechargeAccount = ssmRechargeAccountService.selectByPrimaryKey(repayTradeList.getAccountId());
            //提成标准
            BigDecimal commRatio = repayTradeList.getTypeRatio();
            //业绩
            repayTradeList.setAchievementAmount(repayTradeList.getRepayMoney());
            //提成
            if (BigDecimalUtils.compareTo(commRatio, BigDecimalUtils.bigDecimal("1")) != 1) {

                repayTradeList.setCommissionAmount(BigDecimalUtils.multiply(commRatio, repayTradeList.getPayMoney()));

            } else {
                repayTradeList.setCommissionAmount(BigDecimalUtils.multiply(
                        BigDecimalUtils.div(repayTradeList.getPayMoney(), rechargeAccount.getCardRechargeMoney()), commRatio));
            }
        }
        return repayTradeList;
    }


}
