package com.ssm.manage.service.impl;

import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.BigDecimalUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.SsmCardChangeInProjectDao;
import com.ssm.manage.entity.*;


import com.ssm.manage.extendEntity.AchiCommEntity;
import com.ssm.manage.mapper.CardChangeInProjectMapper;
import com.ssm.manage.query.CardChangeInProjectRequest;
import com.ssm.manage.query.CardChangeListRequest;
import com.ssm.manage.query.RechargeAccountRequest;
import com.ssm.manage.query.StaffRequest;
import com.ssm.manage.response.CardChangeInProjectResponse;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.service.*;
import com.ssm.manage.utils.Constant;
import lombok.extern.slf4j.Slf4j;
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 tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class SsmCardChangeInProjectServiceImpl extends BaseServiceImpl<CardChangeInProject> implements SsmCardChangeInProjectService {
    @Autowired
    private SsmCourseAccountService ssmCourseAccountService;

    @Autowired
    private SsmPayService ssmPayService;
    @Autowired
    private SsmProjectService ssmProjectService;

    @Autowired
    private SsmCardChangeService ssmCardChangeService;


    @Autowired
    private SsmSalesmanService ssmSalesmanService;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmAccountTradeRecordService ssmAccountTradeRecordService;

    @Autowired
    private SsmCardChangeInProjectDao dao;

    @Autowired
    private CardChangeInProjectMapper mapper;

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

    @Override
    public List<CardChangeInProjectResponse> selectList(CardChangeListRequest cardChangeListRequest) {
        CardChangeInProject cardChangeInProject = new CardChangeInProject();
//        BeanUtils.copyProperties(cardChangeListRequest, cardChangeInProject);
        cardChangeInProject.setDocNum(cardChangeListRequest.getDocNum());
        List<CardChangeInProject> list = dao.select(cardChangeInProject);
        List<CardChangeInProjectResponse> responses = new ArrayList<>();
        for (CardChangeInProject changeInProject : list) {
            CardChangeInProjectResponse cardChangeInProjectResponse = new CardChangeInProjectResponse();
            BeanUtils.copyProperties(changeInProject, cardChangeInProjectResponse);
            //设置业务员
            List<AchiCommEntity> entities = this.getAchiCommList(changeInProject);
            cardChangeInProjectResponse.setEntities(entities);
            //查询现付列表
            PayList payList = new PayList();
            payList.setDocId(changeInProject.getDocNum());
            List<PayList> payLists = ssmPayService.select(payList);
            cardChangeInProjectResponse.setPayLists(payLists);
            BaseProject baseProject = new BaseProject();
            baseProject.setId(changeInProject.getProjectId());
            BaseProject select = ssmProjectService.selectOne(baseProject);
            cardChangeInProjectResponse.setProjectNum(select.getProjectNum());
            responses.add(cardChangeInProjectResponse);
        }
        return responses;
    }

    public List<AchiCommEntity> getAchiCommList(CardChangeInProject changeInProject){
        List<AchiCommEntity> entities = new ArrayList<>();
        BigDecimal hundredBD = com.ssm.manage.utils.BigDecimalUtils.bigDecimal("100");

        if (null != changeInProject.getSaleOneStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setDocNum(changeInProject.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_card_change);
            achiCommEntity.setDocDate(changeInProject.getDocDate());
            achiCommEntity.setTradeName(changeInProject.getProjectName());
            achiCommEntity.setBrandNumber(changeInProject.getSaleOneNumber());
            achiCommEntity.setSaleStaffId(changeInProject.getSaleOneStaffId());
            achiCommEntity.setSaleStaffName(changeInProject.getSaleOneStaffName());
            achiCommEntity.setSaleIdentityCard(changeInProject.getSaleOneIdentity());
            achiCommEntity.setSaleRatio(changeInProject.getSaleOneRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(changeInProject.getAchievementAmount(), BigDecimalUtils.div(changeInProject.getSaleOneRatio(), hundredBD)));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(changeInProject.getCommissionAmount(), BigDecimalUtils.div(changeInProject.getSaleOneRatio(), hundredBD)));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(changeInProject.getAchievementAmount(), BigDecimalUtils.div(changeInProject.getSaleOneRatio(), hundredBD)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(changeInProject.getCommissionAmount(), BigDecimalUtils.div(changeInProject.getSaleOneRatio(), hundredBD)));
            entities.add(achiCommEntity);
        }
        if (null != changeInProject.getSaleTwoStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setDocNum(changeInProject.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_card_change);
            achiCommEntity.setDocDate(changeInProject.getDocDate());
            achiCommEntity.setTradeName(changeInProject.getProjectName());
            achiCommEntity.setBrandNumber(changeInProject.getSaleTwoNumber());
            achiCommEntity.setSaleStaffId(changeInProject.getSaleTwoStaffId());
            achiCommEntity.setSaleStaffName(changeInProject.getSaleTwoStaffName());
            achiCommEntity.setSaleIdentityCard(changeInProject.getSaleTwoIdentity());
            achiCommEntity.setSaleRatio(changeInProject.getSaleTwoRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(changeInProject.getAchievementAmount(), BigDecimalUtils.div(changeInProject.getSaleTwoRatio(), hundredBD)));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(changeInProject.getCommissionAmount(), BigDecimalUtils.div(changeInProject.getSaleTwoRatio(), hundredBD)));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(changeInProject.getAchievementAmount(), BigDecimalUtils.div(changeInProject.getSaleTwoRatio(), hundredBD)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(changeInProject.getCommissionAmount(), BigDecimalUtils.div(changeInProject.getSaleTwoRatio(), hundredBD)));
            entities.add(achiCommEntity);
        }
        if (null != changeInProject.getSaleThreeStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setDocNum(changeInProject.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_card_change);
            achiCommEntity.setDocDate(changeInProject.getDocDate());
            achiCommEntity.setTradeName(changeInProject.getProjectName());
            achiCommEntity.setBrandNumber(changeInProject.getSaleThreeNumber());
            achiCommEntity.setSaleStaffId(changeInProject.getSaleThreeStaffId());
            achiCommEntity.setSaleStaffName(changeInProject.getSaleThreeStaffName());
            achiCommEntity.setSaleIdentityCard(changeInProject.getSaleThreeIdentity());
            achiCommEntity.setSaleRatio(changeInProject.getSaleThreeRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(changeInProject.getAchievementAmount(), BigDecimalUtils.div(changeInProject.getSaleThreeRatio(), hundredBD)));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(changeInProject.getCommissionAmount(), BigDecimalUtils.div(changeInProject.getSaleThreeRatio(), hundredBD)));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(changeInProject.getAchievementAmount(), BigDecimalUtils.div(changeInProject.getSaleThreeRatio(), hundredBD)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(changeInProject.getCommissionAmount(), BigDecimalUtils.div(changeInProject.getSaleThreeRatio(), hundredBD)));
            entities.add(achiCommEntity);
        }
        if (null != changeInProject.getSaleFourStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setDocNum(changeInProject.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_card_change);
            achiCommEntity.setDocDate(changeInProject.getDocDate());
            achiCommEntity.setTradeName(changeInProject.getProjectName());
            achiCommEntity.setBrandNumber(changeInProject.getSaleFourNumber());
            achiCommEntity.setSaleStaffId(changeInProject.getSaleFourStaffId());
            achiCommEntity.setSaleStaffName(changeInProject.getSaleFourStaffName());
            achiCommEntity.setSaleIdentityCard(changeInProject.getSaleFourIdentity());
            achiCommEntity.setSaleRatio(changeInProject.getSaleFourRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(changeInProject.getAchievementAmount(), BigDecimalUtils.div(changeInProject.getSaleFourRatio(), hundredBD)));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(changeInProject.getCommissionAmount(), BigDecimalUtils.div(changeInProject.getSaleFourRatio(), hundredBD)));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(changeInProject.getAchievementAmount(), BigDecimalUtils.div(changeInProject.getSaleFourRatio(), hundredBD)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(changeInProject.getCommissionAmount(), BigDecimalUtils.div(changeInProject.getSaleFourRatio(), hundredBD)));
            entities.add(achiCommEntity);
        } if (null != changeInProject.getSaleFiveStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setDocNum(changeInProject.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_card_change);
            achiCommEntity.setDocDate(changeInProject.getDocDate());
            achiCommEntity.setTradeName(changeInProject.getProjectName());
            achiCommEntity.setBrandNumber(changeInProject.getSaleFiveNumber());
            achiCommEntity.setSaleStaffId(changeInProject.getSaleFiveStaffId());
            achiCommEntity.setSaleStaffName(changeInProject.getSaleFiveStaffName());
            achiCommEntity.setSaleIdentityCard(changeInProject.getSaleFiveIdentity());
            achiCommEntity.setSaleRatio(changeInProject.getSaleFiveRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(changeInProject.getAchievementAmount(), BigDecimalUtils.div(changeInProject.getSaleFiveRatio(), hundredBD)));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(changeInProject.getCommissionAmount(), BigDecimalUtils.div(changeInProject.getSaleFiveRatio(), hundredBD)));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(changeInProject.getAchievementAmount(), BigDecimalUtils.div(changeInProject.getSaleFiveRatio(), hundredBD)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(changeInProject.getCommissionAmount(), BigDecimalUtils.div(changeInProject.getSaleFiveRatio(), hundredBD)));
            entities.add(achiCommEntity);
        } if (null != changeInProject.getSaleSixStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setDocNum(changeInProject.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_card_change);
            achiCommEntity.setDocDate(changeInProject.getDocDate());
            achiCommEntity.setTradeName(changeInProject.getProjectName());
            achiCommEntity.setBrandNumber(changeInProject.getSaleSixNumber());
            achiCommEntity.setSaleStaffId(changeInProject.getSaleSixStaffId());
            achiCommEntity.setSaleStaffName(changeInProject.getSaleSixStaffName());
            achiCommEntity.setSaleIdentityCard(changeInProject.getSaleSixIdentity());
            achiCommEntity.setSaleRatio(changeInProject.getSaleSixRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(changeInProject.getAchievementAmount(), BigDecimalUtils.div(changeInProject.getSaleSixRatio(), hundredBD)));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(changeInProject.getCommissionAmount(), BigDecimalUtils.div(changeInProject.getSaleSixRatio(), hundredBD)));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(changeInProject.getAchievementAmount(), BigDecimalUtils.div(changeInProject.getSaleSixRatio(), hundredBD)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(changeInProject.getCommissionAmount(), BigDecimalUtils.div(changeInProject.getSaleSixRatio(), hundredBD)));
            entities.add(achiCommEntity);
        } if (null != changeInProject.getSaleSevenStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setDocNum(changeInProject.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_card_change);
            achiCommEntity.setDocDate(changeInProject.getDocDate());
            achiCommEntity.setTradeName(changeInProject.getProjectName());
            achiCommEntity.setBrandNumber(changeInProject.getSaleSevenNumber());
            achiCommEntity.setSaleStaffId(changeInProject.getSaleSevenStaffId());
            achiCommEntity.setSaleStaffName(changeInProject.getSaleSevenStaffName());
            achiCommEntity.setSaleIdentityCard(changeInProject.getSaleSevenIdentity());
            achiCommEntity.setSaleRatio(changeInProject.getSaleSevenRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(changeInProject.getAchievementAmount(), BigDecimalUtils.div(changeInProject.getSaleSevenRatio(), hundredBD)));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(changeInProject.getCommissionAmount(), BigDecimalUtils.div(changeInProject.getSaleSevenRatio(), hundredBD)));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(changeInProject.getAchievementAmount(), BigDecimalUtils.div(changeInProject.getSaleSevenRatio(), hundredBD)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(changeInProject.getCommissionAmount(), BigDecimalUtils.div(changeInProject.getSaleSevenRatio(), hundredBD)));
            entities.add(achiCommEntity);
        } if (null != changeInProject.getSaleEightStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setDocNum(changeInProject.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_card_change);
            achiCommEntity.setDocDate(changeInProject.getDocDate());
            achiCommEntity.setTradeName(changeInProject.getProjectName());
            achiCommEntity.setBrandNumber(changeInProject.getSaleEightNumber());
            achiCommEntity.setSaleStaffId(changeInProject.getSaleEightStaffId());
            achiCommEntity.setSaleStaffName(changeInProject.getSaleEightStaffName());
            achiCommEntity.setSaleIdentityCard(changeInProject.getSaleEightIdentity());
            achiCommEntity.setSaleRatio(changeInProject.getSaleEightRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(changeInProject.getAchievementAmount(), BigDecimalUtils.div(changeInProject.getSaleEightRatio(), hundredBD)));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(changeInProject.getCommissionAmount(), BigDecimalUtils.div(changeInProject.getSaleEightRatio(), hundredBD)));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(changeInProject.getAchievementAmount(), BigDecimalUtils.div(changeInProject.getSaleEightRatio(), hundredBD)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(changeInProject.getCommissionAmount(), BigDecimalUtils.div(changeInProject.getSaleEightRatio(), hundredBD)));
            entities.add(achiCommEntity);
        }

        return entities;
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public synchronized CardChangeInProject insert(CardChangeList cardChangeList, CardChangeInProjectRequest cardChangeInProjectRequest) throws SmsException {
        CardChangeInProject cardChangeInProject = new CardChangeInProject();
        BeanUtils.copyProperties(cardChangeInProjectRequest, cardChangeInProject);
        cardChangeInProject.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        cardChangeInProject.setDocNum(cardChangeList.getDocNum());
        cardChangeInProject.setDocDate(cardChangeList.getDocDate());
        //设置业务员
        List<StaffRequest> staffLists = cardChangeInProjectRequest.getStaffLists();
        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,cardChangeInProject);
        //计算业绩
        List<PayList> payLists = cardChangeInProjectRequest.getPayLists();
        cardChangeInProject = this.setAchiComm(cardChangeInProject, payLists, cardChangeList.getChangeInPayMoney());
        //账户添加
        Long courseAccountId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
        CourseAccount courseAccount = new CourseAccount();
        BeanUtils.copyProperties(cardChangeInProject, courseAccount);
        courseAccount.setId(courseAccountId);
        courseAccount.setCourseType("3");//加价转疗程类型
        courseAccount.setCourseNum(cardChangeInProject.getDocNum());
        courseAccount.setStoreId(cardChangeList.getStoreId());
        courseAccount.setStoreName(cardChangeList.getStoreName());

        if(cardChangeList.getChangeInPayMoney().add(cardChangeList.getDebtMoney()).compareTo(BigDecimal.valueOf(0))!=0){
            cardChangeInProject.setAccountId(courseAccountId);
            courseAccount = ssmCourseAccountService.addCourseAccount(courseAccount, cardChangeList, cardChangeInProject);
        }
        cardChangeInProject.setBeforePrice(BigDecimal.valueOf(0));
        cardChangeInProject.setBeforeRestMoney(BigDecimal.valueOf(0));
        cardChangeInProject.setBeforeConsumeMoney(BigDecimal.valueOf(0));
        cardChangeInProject.setBeforeRestCount(0);
        cardChangeInProject.setBeforeConsumeCount(0);
        cardChangeInProject.setBackPrice(courseAccount.getPrice());
        cardChangeInProject.setBackRestMoney(courseAccount.getCourseRestPrice());
        cardChangeInProject.setBackConsumeMoney(courseAccount.getCourseConsumePrice());
        cardChangeInProject.setBackRestCount(courseAccount.getCourseRestCount());
        cardChangeInProject.setBackConsumeCount(courseAccount.getCourseConsumeCount());

        cardChangeInProject.setCourseRestCount(courseAccount.getCourseRestCount());
        cardChangeInProject.setCourseConsumeCount(courseAccount.getCourseConsumeCount());
        cardChangeInProject.setChangeInPayMoney(cardChangeList.getChangeInPayMoney());
        cardChangeInProject.setChangeOutMoney(cardChangeList.getChangeOutMoney());
        cardChangeInProject.setStoreId(cardChangeList.getStoreId());
        cardChangeInProject.setStoreName(cardChangeList.getStoreName());
        try {
            int i = dao.saveNotNull(cardChangeInProject);
            CardChangeInProject cardChangeInProject1 = new CardChangeInProject();
            cardChangeInProject1.setDocNum(cardChangeInProject.getDocNum());
            List<CardChangeInProject> cardChangeInProject2 = dao.select(cardChangeInProject1);
            //高管业绩
            if(null != cardChangeInProjectRequest.getSalesmens()){
                List<Salesman> salesmens = cardChangeInProjectRequest.getSalesmens();
                BigDecimal reduce5 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType()==0).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal reduce6 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType()==1).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
                if(null != reduce5 && reduce5.compareTo(BigDecimal.valueOf(100))!=0 && reduce5.compareTo(BigDecimal.valueOf(0))!=0){
                    throw new SmsException(ResponseCode.MSG,"高管业绩占比和不等于100");
                }
                if(null != reduce6 && reduce6.compareTo(BigDecimal.valueOf(100))!=0 && reduce6.compareTo(BigDecimal.valueOf(0))!=0){
                    throw new SmsException(ResponseCode.MSG,"管理员业绩占比和不等于100");
                }
                for (Salesman salesmen : salesmens) {
                    salesmen.setOrderId(String.valueOf(cardChangeInProject2.get(0).getId()));
                    salesmen.setOrderNum(cardChangeInProject.getDocNum());
                    salesmen.setOrderType(3);
                    salesmen.setOrderDate(new Date());
                    if(cardChangeList.getChangeInPayMoney().compareTo(BigDecimal.valueOf(0))!=0){
                        salesmen.setState(0);
                    }else{
                        salesmen.setState(1);
                    }
                    salesmen.setOperatorBy(cardChangeList.getInputBy());
                    salesmen.setMoney(cardChangeInProject.getChangeInPayMoney());
                    salesmen.setProjectId(cardChangeInProject.getProjectId());
                    salesmen.setIsAddition(cardChangeList.getIsAddition());
                }
                ssmSalesmanService.addBatch(salesmens);
            }
        }catch (Exception e){
            log.error("SsmCardChangeInProjectServiceImpl.insert:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        //添加账户交易记录
        if(cardChangeList.getChangeInPayMoney().add(cardChangeList.getDebtMoney()).compareTo(BigDecimal.valueOf(0))!=0){
            AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(cardChangeInProject, cardChangeList, courseAccount);
            ssmAccountTradeRecordService.addRecord(accountTradeRecord);
        }

        return cardChangeInProject;
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public synchronized CardChangeInProject insertNew(CardChangeList cardChangeList, CardChangeInProjectRequest cardChangeInProjectRequest) throws SmsException {
        CardChangeInProject cardChangeInProject = new CardChangeInProject();
        BeanUtils.copyProperties(cardChangeInProjectRequest, cardChangeInProject);
        cardChangeInProject.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        cardChangeInProject.setDocNum(cardChangeList.getDocNum());
        cardChangeInProject.setDocDate(cardChangeList.getDocDate());
        //设置业务员
        List<StaffRequest> staffLists = cardChangeInProjectRequest.getStaffLists();
        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,cardChangeInProject);
        //计算业绩
        List<PayList> payLists = cardChangeInProjectRequest.getPayLists();
        cardChangeInProject = this.setAchiCommNew(cardChangeInProject, payLists, cardChangeList.getChangeInPayMoney());//形同虚设，没有用
        //账户添加
        Long courseAccountId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
        CourseAccount courseAccount = new CourseAccount();
        BeanUtils.copyProperties(cardChangeInProject, courseAccount);
        courseAccount.setId(courseAccountId);
        courseAccount.setCourseType("3");//加价转疗程类型
        courseAccount.setCourseNum(cardChangeInProject.getDocNum());
        courseAccount.setStoreId(cardChangeList.getStoreId());
        courseAccount.setStoreName(cardChangeList.getStoreName());

        if(cardChangeList.getChangeInPayMoney().compareTo(BigDecimal.valueOf(0))!=0){
            cardChangeInProject.setAccountId(courseAccountId);
            courseAccount = ssmCourseAccountService.addCourseAccount(courseAccount, cardChangeList, cardChangeInProject);
        }
        cardChangeInProject.setBeforePrice(BigDecimal.valueOf(0));
        cardChangeInProject.setBeforeRestMoney(BigDecimal.valueOf(0));
        cardChangeInProject.setBeforeConsumeMoney(BigDecimal.valueOf(0));
        cardChangeInProject.setBeforeRestCount(0);
        cardChangeInProject.setBeforeConsumeCount(0);
        cardChangeInProject.setBackPrice(courseAccount.getPrice());
        cardChangeInProject.setBackRestMoney(courseAccount.getCourseRestPrice());
        cardChangeInProject.setBackConsumeMoney(courseAccount.getCourseConsumePrice());
        cardChangeInProject.setBackRestCount(courseAccount.getCourseRestCount());
        cardChangeInProject.setBackConsumeCount(courseAccount.getCourseConsumeCount());

        cardChangeInProject.setCourseRestCount(courseAccount.getCourseRestCount());
        cardChangeInProject.setCourseConsumeCount(courseAccount.getCourseConsumeCount());
        cardChangeInProject.setChangeInPayMoney(cardChangeList.getChangeInPayMoney());
        cardChangeInProject.setChangeOutMoney(cardChangeList.getChangeOutMoney());
        cardChangeInProject.setStoreId(cardChangeList.getStoreId());
        cardChangeInProject.setStoreName(cardChangeList.getStoreName());
        cardChangeInProject.setCardAchievementAmount(cardChangeInProject.getChangeInMoney().subtract(cardChangeInProject.getChangeInPayMoney()).subtract(cardChangeInProject.getDebtMoney()).multiply(cardChangeInProject.getCardSalesAchievement()));
        cardChangeInProject.setCardCommissionAmount(cardChangeInProject.getCardAchievementAmount().multiply(cardChangeInProject.getCardSalesCommission()));
        try {
            int i = dao.saveNotNull(cardChangeInProject);
            CardChangeInProject cardChangeInProject1 = new CardChangeInProject();
            cardChangeInProject1.setDocNum(cardChangeInProject.getDocNum());
            List<CardChangeInProject> cardChangeInProject2 = dao.select(cardChangeInProject1);
            //高管业绩
            if(null != cardChangeInProjectRequest.getSalesmens()){
                List<Salesman> salesmens = cardChangeInProjectRequest.getSalesmens();
                BigDecimal reduce5 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType()==0).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal reduce6 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType()==1).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
                if(null != reduce5 && reduce5.compareTo(BigDecimal.valueOf(100))!=0 && reduce5.compareTo(BigDecimal.valueOf(0))!=0){
                    throw new SmsException(ResponseCode.MSG,"高管业绩占比和不等于100");
                }
                if(null != reduce6 && reduce6.compareTo(BigDecimal.valueOf(100))!=0 && reduce6.compareTo(BigDecimal.valueOf(0))!=0){
                    throw new SmsException(ResponseCode.MSG,"管理员业绩占比和不等于100");
                }
                for (Salesman salesmen : salesmens) {
                    salesmen.setOrderId(String.valueOf(cardChangeInProject2.get(0).getId()));
                    salesmen.setOrderNum(cardChangeInProject.getDocNum());
                    salesmen.setOrderType(3);
                    salesmen.setOrderDate(new Date());
                    if(cardChangeList.getChangeInPayMoney().compareTo(BigDecimal.valueOf(0))!=0){
                        salesmen.setState(0);
                    }else{
                        salesmen.setState(1);
                    }
                    salesmen.setOperatorBy(cardChangeList.getInputBy());
                    salesmen.setMoney(cardChangeInProject.getChangeInPayMoney());
                    salesmen.setProjectId(cardChangeInProject.getProjectId());
                    salesmen.setIsAddition(cardChangeList.getIsAddition());
                }
                ssmSalesmanService.addBatch(salesmens);
            }
        }catch (Exception e){
            log.error("SsmCardChangeInProjectServiceImpl.insert:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        //添加账户交易记录
        if(cardChangeList.getChangeInPayMoney().compareTo(BigDecimal.valueOf(0))!=0){
            AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(cardChangeInProject, cardChangeList, courseAccount);
            ssmAccountTradeRecordService.addRecord(accountTradeRecord);
        }

        return cardChangeInProject;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public synchronized CardChangeInProject audit(CardChangeList cardChangeList, CardChangeInProject cardChangeInProjectRequest) throws SmsException {
        CourseAccount courseAccount1 = new CourseAccount();
        if(null == cardChangeInProjectRequest.getAccountId()){
            Long courseAccountId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
            CourseAccount courseAccount = new CourseAccount();
            BeanUtils.copyProperties(cardChangeInProjectRequest, courseAccount);
            courseAccount.setId(courseAccountId);
            courseAccount.setCourseType("3");//加价转疗程类型
            courseAccount.setCourseNum(cardChangeInProjectRequest.getDocNum());
            courseAccount.setStoreId(cardChangeList.getStoreId());
            courseAccount.setStoreName(cardChangeList.getStoreName());
            courseAccount1 = ssmCourseAccountService.addCourseAccount(courseAccount, cardChangeList, cardChangeInProjectRequest);
            cardChangeInProjectRequest.setBeforePrice(BigDecimal.valueOf(0));
            cardChangeInProjectRequest.setBeforeRestMoney(BigDecimal.valueOf(0));
            cardChangeInProjectRequest.setBeforeConsumeMoney(BigDecimal.valueOf(0));
            cardChangeInProjectRequest.setBeforeRestCount(0);
            cardChangeInProjectRequest.setBeforeConsumeCount(0);
            cardChangeInProjectRequest.setBackPrice(courseAccount1.getPrice());
            cardChangeInProjectRequest.setBackRestMoney(courseAccount1.getCourseRestPrice());
            cardChangeInProjectRequest.setBackConsumeMoney(courseAccount1.getCourseConsumePrice());
            cardChangeInProjectRequest.setBackRestCount(courseAccount1.getCourseRestCount());
            cardChangeInProjectRequest.setBackConsumeCount(courseAccount1.getCourseConsumeCount());
            cardChangeInProjectRequest.setAccountId(courseAccount1.getId());
            int update = dao.updateByPrimaryKeySelective(cardChangeInProjectRequest);
            if(update == 0){
                throw new SmsException(ResponseCode.MSG,"审核失败");
            }
        }else{
            CourseAccount courseAccount = new CourseAccount();
            courseAccount.setId(cardChangeInProjectRequest.getAccountId());
            CourseAccount courseAccount2 = ssmCourseAccountService.selectByPrimaryKey(courseAccount.getId());
            courseAccount1 = ssmCourseAccountService.addCourseAccount(courseAccount2, cardChangeList, cardChangeInProjectRequest);
            cardChangeInProjectRequest.setBeforePrice(BigDecimal.valueOf(0));
            cardChangeInProjectRequest.setBeforeRestMoney(BigDecimal.valueOf(0));
            cardChangeInProjectRequest.setBeforeConsumeMoney(BigDecimal.valueOf(0));
            cardChangeInProjectRequest.setBeforeRestCount(0);
            cardChangeInProjectRequest.setBeforeConsumeCount(0);
            cardChangeInProjectRequest.setBackPrice(courseAccount1.getPrice());
            cardChangeInProjectRequest.setBackRestMoney(courseAccount1.getCourseRestPrice());
            cardChangeInProjectRequest.setBackConsumeMoney(courseAccount1.getCourseConsumePrice());
            cardChangeInProjectRequest.setBackRestCount(courseAccount1.getCourseRestCount());
            cardChangeInProjectRequest.setBackConsumeCount(courseAccount1.getCourseConsumeCount());

            cardChangeInProjectRequest.setAccountId(courseAccount2.getId());
            int update = dao.updateByPrimaryKeySelective(cardChangeInProjectRequest);
            if(update == 0){
                throw new SmsException(ResponseCode.MSG,"审核失败");
            }
        }

        PayList payList = new PayList();
        payList.setDocId(cardChangeList.getDocNum());
        List<PayList> payListList = ssmPayService.select(payList);
        if(payListList!=null&&payListList.size()>0) {
            for (PayList list : payListList) {
                list.setIsCancel(0);
                ssmPayService.updateByNum(list);
            }
        }
        Salesman salesman = new Salesman();
        salesman.setOrderId(String.valueOf(cardChangeInProjectRequest.getId()));
        salesman.setOrderNum(cardChangeInProjectRequest.getDocNum());
        salesman.setOrderType(3);
        List<Salesman> select = ssmSalesmanService.select(salesman);
        for (Salesman salesman1 : select) {
            salesman1.setState(0);
            salesman1.setOperatorBy(cardChangeList.getAuditBy());
            ssmSalesmanService.updateNotNull(salesman1);
        }
        AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(cardChangeInProjectRequest, cardChangeList, courseAccount1);
        ssmAccountTradeRecordService.addRecord(accountTradeRecord);


        return cardChangeInProjectRequest;
    }


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

        for (int i = 0; i < staffLists.size(); i++) {
            StaffRequest staffRequest = staffLists.get(i);
            if (i == 0){
                cardChangeInProject.setSaleOneStaffId(staffRequest.getId());
                cardChangeInProject.setSaleOneStaffName(staffRequest.getStaffName());
                cardChangeInProject.setSaleOneIdentity(staffRequest.getIdentityCard());
                cardChangeInProject.setSaleOneRatio(staffRequest.getRatio());
                cardChangeInProject.setSaleOneNumber(staffRequest.getBrandNumber());
            }else if (i == 1){
                cardChangeInProject.setSaleTwoStaffId(staffRequest.getId());
                cardChangeInProject.setSaleTwoStaffName(staffRequest.getStaffName());
                cardChangeInProject.setSaleTwoIdentity(staffRequest.getIdentityCard());
                cardChangeInProject.setSaleTwoRatio(staffRequest.getRatio());
                cardChangeInProject.setSaleTwoNumber(staffRequest.getBrandNumber());
            }else if (i == 2){
                cardChangeInProject.setSaleThreeStaffId(staffRequest.getId());
                cardChangeInProject.setSaleThreeStaffName(staffRequest.getStaffName());
                cardChangeInProject.setSaleThreeIdentity(staffRequest.getIdentityCard());
                cardChangeInProject.setSaleThreeRatio(staffRequest.getRatio());
                cardChangeInProject.setSaleThreeNumber(staffRequest.getBrandNumber());
            }else if(i == 3){
                cardChangeInProject.setSaleFourStaffId(staffRequest.getId());
                cardChangeInProject.setSaleFourStaffName(staffRequest.getStaffName());
                cardChangeInProject.setSaleFourIdentity(staffRequest.getIdentityCard());
                cardChangeInProject.setSaleFourRatio(staffRequest.getRatio());
                cardChangeInProject.setSaleFourNumber(staffRequest.getBrandNumber());

            }else if (i == 4){
                cardChangeInProject.setSaleFiveStaffId(staffRequest.getId());
                cardChangeInProject.setSaleFiveStaffName(staffRequest.getStaffName());
                cardChangeInProject.setSaleFiveIdentity(staffRequest.getIdentityCard());
                cardChangeInProject.setSaleFiveRatio(staffRequest.getRatio());
                cardChangeInProject.setSaleFiveNumber(staffRequest.getBrandNumber());
            }else if (i == 5){
                cardChangeInProject.setSaleSixStaffId(staffRequest.getId());
                cardChangeInProject.setSaleSixStaffName(staffRequest.getStaffName());
                cardChangeInProject.setSaleSixIdentity(staffRequest.getIdentityCard());
                cardChangeInProject.setSaleSixRatio(staffRequest.getRatio());
                cardChangeInProject.setSaleSixNumber(staffRequest.getBrandNumber());
            }else if (i == 6){
                cardChangeInProject.setSaleSevenStaffId(staffRequest.getId());
                cardChangeInProject.setSaleSevenStaffName(staffRequest.getStaffName());
                cardChangeInProject.setSaleSevenIdentity(staffRequest.getIdentityCard());
                cardChangeInProject.setSaleSevenRatio(staffRequest.getRatio());
                cardChangeInProject.setSaleSevenNumber(staffRequest.getBrandNumber());
            }else if (i == 7){
                cardChangeInProject.setSaleEightStaffId(staffRequest.getId());
                cardChangeInProject.setSaleEightStaffName(staffRequest.getStaffName());
                cardChangeInProject.setSaleEightIdentity(staffRequest.getIdentityCard());
                cardChangeInProject.setSaleEightRatio(staffRequest.getRatio());
                cardChangeInProject.setSaleEightNumber(staffRequest.getBrandNumber());
            }
        }
    }

    public CardChangeInProject setAchiCommNew(CardChangeInProject cardChangeInProject, List<PayList> payLists, BigDecimal changeInPayMoney){

        BigDecimal times = BigDecimalUtils.bigDecimal(cardChangeInProject.getChangeInTime().toString());
        //现付销售业绩标准  >0 <1比率   >1固定金额
        BigDecimal achiRatio = cardChangeInProject.getSalesAchievement();//1
        //现付销售提成标准  >0 <1比率   >1固定金额
        BigDecimal commRatio = cardChangeInProject.getSalesCommission();//0.1
//        //卡付销售业绩标准
//        BigDecimal cardAchiRatio = cardChangeInProject.getCardSalesAchievement();//1
//        //卡付销售提成标准
//        BigDecimal cardCommRatio = cardChangeInProject.getCardSalesCommission();//0.02
        if (null != payLists && payLists.size() > 0) {
            //比率
            if (BigDecimalUtils.compareTo(achiRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
                cardChangeInProject.setAchievementAmount(BigDecimalUtils.multiply(achiRatio, changeInPayMoney));
            }else {//固定金额
                cardChangeInProject.setAchievementAmount(BigDecimalUtils.
                        multiply(BigDecimalUtils.
                                multiply(BigDecimalUtils.
                                        div(changeInPayMoney, cardChangeInProject.getTransactionMoney()), achiRatio), times));
            }
            //提成比率
            if (BigDecimalUtils.compareTo(commRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
                cardChangeInProject.setCommissionAmount(BigDecimalUtils.multiply(commRatio, cardChangeInProject.getAchievementAmount()));
            }else {//提成固定金额
                cardChangeInProject.setCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(changeInPayMoney, cardChangeInProject.getTransactionMoney()), commRatio), times));
            }
        }
        return cardChangeInProject;
    }
    public CardChangeInProject setAchiComm(CardChangeInProject cardChangeInProject, List<PayList> payLists, BigDecimal changeInPayMoney){

        BigDecimal times = BigDecimalUtils.bigDecimal(cardChangeInProject.getChangeInTime().toString());
        //现付销售业绩标准  >0 <1比率   >1固定金额
        BigDecimal achiRatio = cardChangeInProject.getSalesAchievement();
        //现付销售提成标准  >0 <1比率   >1固定金额
        BigDecimal commRatio = cardChangeInProject.getSalesCommission();
        if (null != payLists && payLists.size() > 0) {
            //比率
            if (BigDecimalUtils.compareTo(achiRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
                cardChangeInProject.setAchievementAmount(BigDecimalUtils.multiply(achiRatio, changeInPayMoney));
            }else {//固定金额
                cardChangeInProject.setAchievementAmount(BigDecimalUtils.
                        multiply(BigDecimalUtils.
                                multiply(BigDecimalUtils.
                                        div(changeInPayMoney, cardChangeInProject.getTransactionMoney()), achiRatio), times));
            }
            //提成比率
            if (BigDecimalUtils.compareTo(commRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
                cardChangeInProject.setCommissionAmount(BigDecimalUtils.multiply(commRatio, cardChangeInProject.getAchievementAmount()));
            }else {//提成固定金额
                cardChangeInProject.setCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(changeInPayMoney, cardChangeInProject.getTransactionMoney()), commRatio), times));
            }
        }
        return cardChangeInProject;
    }

    public CardChangeInProject setAchiComm(CardChangeInProject cardChangeInProject, BigDecimal changeInMoney){
        BigDecimal times = BigDecimalUtils.bigDecimal(cardChangeInProject.getChangeInTime().toString());
        //现付销售业绩标准  >0 <1比率   >1固定金额
        BigDecimal achiRatio = cardChangeInProject.getSalesAchievement();
        //现付销售提成标准  >0 <1比率   >1固定金额
        BigDecimal commRatio = cardChangeInProject.getSalesCommission();

        //比率
        if (BigDecimalUtils.compareTo(achiRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
            cardChangeInProject.setAchievementAmount(BigDecimalUtils.multiply(achiRatio, changeInMoney));
        }else {//固定金额
            cardChangeInProject.setAchievementAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(changeInMoney, cardChangeInProject.getTransactionMoney()), achiRatio), times));
        }
        //提成比率
        if (BigDecimalUtils.compareTo(commRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
            cardChangeInProject.setCommissionAmount(BigDecimalUtils.multiply(commRatio, cardChangeInProject.getAchievementAmount()));
        }else {//提成固定金额
            cardChangeInProject.setCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(changeInMoney, cardChangeInProject.getTransactionMoney()), commRatio), times));
        }

        return cardChangeInProject;
    }

    /*
     * 账户交易记录属性赋值 疗程
     * */
    public AccountTradeRecord setAccountTradeRecord(CardChangeInProject cardChangeInProject,CardChangeList cardChangeList, CourseAccount courseAccount){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(cardChangeInProject.getStoreId());
        accountTradeRecord.setStoreName(cardChangeInProject.getStoreName());
        accountTradeRecord.setMemberId(cardChangeInProject.getMemberId());
        accountTradeRecord.setMemberName(cardChangeInProject.getMemberName());
//        accountTradeRecord.setMemberIdentity(cardChangeInProject.getMemberIdentity());
        accountTradeRecord.setMemberPhone(cardChangeInProject.getMobilePhone());
        accountTradeRecord.setAccountId(courseAccount.getId());
        accountTradeRecord.setAccountName(courseAccount.getCourseProjectName());

        if(cardChangeList.getState() == 3) {
            if(cardChangeList.getChangeInPayMoney().add(cardChangeList.getDebtMoney()).compareTo(BigDecimal.valueOf(0))==0){
                accountTradeRecord.setAccountType("LCNTZR");
            }else {
                accountTradeRecord.setAccountType(Constant.account_type_project);
            }
            accountTradeRecord.setInputDate(cardChangeInProject.getDocDate());
            accountTradeRecord.setInputBy(cardChangeList.getInputBy());
            accountTradeRecord.setAccountInCount(courseAccount.getCourseCount());
            accountTradeRecord.setAccountInMoney(cardChangeInProject.getChangeInMoney());
        }else {
            if(cardChangeList.getChangeInPayMoney().add(cardChangeList.getDebtMoney()).compareTo(BigDecimal.valueOf(0))==0){
                accountTradeRecord.setAccountType("LCNTZR");
            }else {
                accountTradeRecord.setAccountType(Constant.account_type_project_cancel);
            }
            accountTradeRecord.setInputDate(cardChangeList.getCancelDate());
            accountTradeRecord.setInputBy(cardChangeList.getCancelBy());
            accountTradeRecord.setAccountInCount(courseAccount.getCourseCount());
            accountTradeRecord.setAccountSpendMoney(cardChangeInProject.getChangeInMoney());
        }
        accountTradeRecord.setIsAddition(cardChangeList.getIsAddition());
        accountTradeRecord.setDocId(cardChangeInProject.getId());
        accountTradeRecord.setDebtMoney(cardChangeList.getDebtMoney());
        accountTradeRecord.setDocNum(cardChangeInProject.getDocNum());
        accountTradeRecord.setDocType(Constant.doc_type_card_change);
        accountTradeRecord.setTradeId(courseAccount.getCourseProjectId());
        accountTradeRecord.setTradeName(courseAccount.getCourseProjectName());
        accountTradeRecord.setTradeMoney(courseAccount.getCourseProjectMoney());
        accountTradeRecord.setTradeCount(courseAccount.getCourseCount());
        accountTradeRecord.setAccountRestCount(courseAccount.getCourseRestCount());
        accountTradeRecord.setAccountConsumeCount(courseAccount.getCourseConsumeCount());
        accountTradeRecord.setPrice(cardChangeInProject.getChangeInMoney().divide(BigDecimalUtils.bigDecimal(cardChangeInProject.getChangeInTime().toString()),4,BigDecimal.ROUND_HALF_UP));
        accountTradeRecord.setAccountRestMoney(courseAccount.getCourseRestPrice());
        accountTradeRecord.setAccountConsumeMoney(courseAccount.getCourseConsumePrice());
        accountTradeRecord.setCardMoney(cardChangeList.getChangeOutMoney());
        accountTradeRecord.setCashMoney(cardChangeList.getChangeInPayMoney());
        return accountTradeRecord;
    }


    @Override
    public int updateStaff(CardChangeInProjectRequest cardChangeInProjectRequest) throws SmsException {
        int i = 0;
        CardChangeInProject cardChangeInProject = new CardChangeInProject();
        BeanUtils.copyProperties(cardChangeInProjectRequest, cardChangeInProject);
        //设置业务员
        List<StaffRequest> staffLists = cardChangeInProjectRequest.getStaffLists();
        this.setStaffValue(staffLists,cardChangeInProject);
        try {
            i = dao.updateStaff(cardChangeInProject);
            CardChangeInProject cardChangeInProject2 = new CardChangeInProject();
            cardChangeInProject2.setId(cardChangeInProject.getId());
            CardChangeInProject cardChangeInProject1 = dao.selectOne(cardChangeInProject2);
            Salesman salesman = new Salesman();
            salesman.setOrderId(String.valueOf(cardChangeInProject.getId()));
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            Date date = cardChangeInProject1.getDocDate();
            for (Salesman salesman1 : salesmen) {
                date = salesman1.getOrderDate();
                ssmSalesmanService.delete(salesman1);
            }
            if(null != cardChangeInProjectRequest.getSalesmens()){
                List<Salesman> salesmens = cardChangeInProjectRequest.getSalesmens();
                Long storeId = cardChangeInProjectRequest.getStoreId();
                BaseStore stores = new BaseStore();
                stores.setId(storeId);
                BaseStore baseStore = ssmBaseStoreService.selectOne(stores);
                for (Salesman salesmen2 : salesmens) {
                    Random r = new Random(3);
                    int i1 = r.nextInt();
                    salesmen2.setId(salesmen2.getId()+i1);
                    salesmen2.setOrderId(String.valueOf(cardChangeInProject1.getId()));
                    salesmen2.setOrderNum(cardChangeInProject1.getDocNum());
                    salesmen2.setOrderType(3);
                    salesmen2.setOrderDate(date);
                    salesmen2.setState(0);
                    salesmen2.setMoney(cardChangeInProject1.getChangeInPayMoney());
                    salesmen2.setProjectId(cardChangeInProject1.getProjectId());
                    salesmen2.setStoreNum(baseStore.getStoreNum());
                    salesmen2.setStoreName(baseStore.getStoreName());
                    salesmen2.setStoreIdOrder(baseStore.getId());
                }
                ssmSalesmanService.addBatch(salesmens);
            }

        }catch (Exception e){
            log.error("SsmCardChangeInProjectServiceImpl.insert:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return i;
    }

    @Override
    public int cancel(CardChangeList cardChangeList) throws SmsException {
        int i = 0;
        CardChangeInProject cardChangeInProject = new CardChangeInProject();
        cardChangeInProject.setDocNum(cardChangeList.getDocNum());
        //cardChangeInProject.setStoreId(cardChangeList.getStoreId());
        cardChangeInProject = dao.selectOne(cardChangeInProject);
        CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(cardChangeInProject.getAccountId());

        if(cardChangeInProject.getBackPrice().compareTo(courseAccount.getPrice())!=0){
            throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
        }
        if(cardChangeInProject.getBackRestMoney().compareTo(courseAccount.getCourseRestPrice())!=0){
            throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
        }
        if(cardChangeInProject.getBackConsumeMoney().compareTo(courseAccount.getCourseConsumePrice())!=0){
            throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
        }
        if(cardChangeInProject.getBackRestCount() != courseAccount.getCourseRestCount()){
            throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
        }
        if(cardChangeInProject.getBackConsumeCount() != courseAccount.getCourseConsumeCount()){
            throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
        }

        //判断单据购买次数和账户剩余次数是否相等
        if(cardChangeInProject.getChangeInTime() != courseAccount.getCourseRestCount()){
            throw new SmsException(ResponseCode.CANCEL_NOT_PERMISSION,"单据购买后次数和账户剩余次数不相等");
        }
        //扣减账户次数
//        ssmCourseAccountService.subCount(courseAccount, cardChangeInProject.getChangeInTime(), 1);
        courseAccount.setPrice(cardChangeInProject.getBeforePrice());
        courseAccount.setCourseRestPrice(cardChangeInProject.getBeforeRestMoney());
        courseAccount.setCourseConsumePrice(cardChangeInProject.getBeforeConsumeMoney());
        courseAccount.setCourseRestCount(cardChangeInProject.getBeforeRestCount());
        courseAccount.setCourseConsumeCount(cardChangeInProject.getBeforeConsumeCount());
        ssmCourseAccountService.updateNotNull(courseAccount);

        //账户直接删除 次数置0
        courseAccount.setCourseRestCount(0);
        courseAccount.setCourseConsumeCount(0);
        //添加账户交易记录
        AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(cardChangeInProject, cardChangeList, courseAccount);
        accountTradeRecord.setOrderStatu(1);
        ssmAccountTradeRecordService.addRecord(accountTradeRecord);
        //更新转入疗程账户信息
        cardChangeInProject.setCourseRestCount(courseAccount.getCourseRestCount());
        cardChangeInProject.setCourseConsumeCount(courseAccount.getCourseConsumeCount());
        try {
            i = dao.updateByPrimaryKeySelective(cardChangeInProject);
        }catch (Exception e){
            log.error("SsmCardChangeInProjectServiceImpl.cancel:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return i;
    }

    @Override
    public CardChangeInProject insertNT(CardChangeList cardChangeList, CardChangeInProjectRequest cardChangeInProjectRequest) throws SmsException {
        CardChangeInProject cardChangeInProject = new CardChangeInProject();
        BeanUtils.copyProperties(cardChangeInProjectRequest, cardChangeInProject);
        cardChangeInProject.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        cardChangeInProject.setDocNum(cardChangeList.getDocNum());
        cardChangeInProject.setDocDate(cardChangeList.getDocDate());
        //设置业务员
        List<StaffRequest> staffLists = cardChangeInProjectRequest.getStaffLists();
        this.setStaffValue(staffLists,cardChangeInProject);
        //计算业绩
        cardChangeInProject = this.setAchiComm(cardChangeInProject,  cardChangeList.getChangeInMoney());
        try {
            int i = dao.saveNotNull(cardChangeInProject);
        }catch (Exception e){
            log.error("SsmCardChangeInProjectServiceImpl.insertNT:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return cardChangeInProject;
    }

    @Override
    public int audit(CardChangeList cardChangeList) throws SmsException {
        int i = 0;
        CardChangeInProject cardChangeInProject = new CardChangeInProject();
        cardChangeInProject.setDocNum(cardChangeList.getDocNum());
        cardChangeInProject.setStoreId(cardChangeList.getStoreId());
        cardChangeInProject = dao.selectOne(cardChangeInProject);

        //账户添加
        Long courseAccountId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
        CourseAccount courseAccount = new CourseAccount();
        BeanUtils.copyProperties(cardChangeInProject, courseAccount);
        courseAccount.setId(courseAccountId);
        courseAccount.setCourseType("4");//内调类型
        courseAccount.setCourseNum(cardChangeInProject.getDocNum());
        cardChangeInProject.setAccountId(courseAccountId);
        courseAccount = ssmCourseAccountService.addCourseAccount(courseAccount, cardChangeList, cardChangeInProject);
        cardChangeInProject.setCourseRestCount(courseAccount.getCourseRestCount());
        cardChangeInProject.setCourseConsumeCount(courseAccount.getCourseConsumeCount());
        try {
            i = dao.saveNotNull(cardChangeInProject);
        }catch (Exception e){
            log.error("SsmCardChangeInProjectServiceImpl.audit:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        //添加账户交易记录
        AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(cardChangeInProject, cardChangeList, courseAccount);
        ssmAccountTradeRecordService.addRecord(accountTradeRecord);
        return i;
    }

    @Override
    public int unAudit(CardChangeList cardChangeList) throws SmsException {
        int i = 0;
        CardChangeInProject cardChangeInProject = new CardChangeInProject();
        cardChangeInProject.setDocNum(cardChangeList.getDocNum());
        cardChangeInProject.setStoreId(cardChangeList.getStoreId());
        cardChangeInProject = dao.selectOne(cardChangeInProject);
        CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(cardChangeInProject.getAccountId());
        //判断单据购买次数和账户剩余次数是否相等
        if(cardChangeInProject.getChangeInTime() != courseAccount.getCourseRestCount()){
            throw new SmsException(ResponseCode.CANCEL_NOT_PERMISSION,"单据购买后次数和账户剩余次数不相等");
        }
        //账户直接删除 次数置0
        courseAccount.setCourseRestCount(0);
        courseAccount.setCourseConsumeCount(0);
        //添加账户交易记录
        AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(cardChangeInProject, cardChangeList, courseAccount);
        ssmAccountTradeRecordService.addRecord(accountTradeRecord);
        //更新转入疗程账户信息
        cardChangeInProject.setCourseRestCount(courseAccount.getCourseRestCount());
        cardChangeInProject.setCourseConsumeCount(courseAccount.getCourseConsumeCount());
        try {
            i = dao.updateByPrimaryKeySelective(cardChangeInProject);
        }catch (Exception e){
            log.error("SsmCardChangeInProjectServiceImpl.unAudit:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return i;
    }

    @Override
    public List<CardChangeInProject> selectListCard(Long storeId, String dateStr) throws SmsException {
        Example example = new Example(CardChangeInProject.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("storeId", storeId);
        criteria.andLike("docDate", dateStr + "%");
        List<CardChangeInProject> list = dao.selectByExample(example);
        List<CardChangeInProject> lists = new ArrayList<>();
        for (CardChangeInProject cardChangeInProject : list) {
            CardChangeList cardChangeList = new CardChangeList();
            cardChangeList.setStoreId(cardChangeInProject.getStoreId());
            cardChangeList.setState(3);
            cardChangeList.setDocNum(cardChangeInProject.getDocNum());
            CardChangeList cardChangeList1 = ssmCardChangeService.selectOne(cardChangeList);
            if(null != cardChangeList1){
                lists.add(cardChangeInProject);
            }
        }
        return lists;
    }

    @Override
    public List<CardChangeInProject> selectListNew(CardChangeListRequest cardChangeListRequest) {
        return mapper.selectNew(cardChangeListRequest);
    }


}
