package com.ssm.manage.service.impl;

import cn.hutool.core.text.StrBuilder;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.BigDecimalUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.SsmCardChangeOutProjectDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.extendEntity.AchiCommEntity;
import com.ssm.manage.mapper.CardChangeOutProjectMapper;
import com.ssm.manage.query.*;
import com.ssm.manage.response.CardChangeInProjectResponse;
import com.ssm.manage.response.CardChangeOutProjectResponse;
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 java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SsmCardChangeOutProjectServiceImpl extends BaseServiceImpl<CardChangeOutProject> implements SsmCardChangeOutProjectService {
    @Autowired
    private SsmCourseAccountService ssmCourseAccountService;

    @Autowired
    private SsmCardChangeInProjectService ssmCardChangeInProjectService;

    @Autowired
    private SsmCourseService ssmCourseService;

    @Autowired
    private SsmStoreParaService ssmStoreParaService;

    @Autowired
    private SsmAccountTradeRecordService ssmAccountTradeRecordService;
    @Autowired
    private SsmProjectService ssmProjectService;

    @Autowired
    private SsmCardChangeOutProjectDao dao;

    @Autowired
    private SsmSalesmanService ssmSalesmanService;

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

    @Override
    public List<CardChangeOutProject> selectList(CardChangeOutProjectRequest cardChangeOutProjectRequest) {
        CardChangeOutProject cardChangeOutProject = new CardChangeOutProject();
        BeanUtils.copyProperties(cardChangeOutProjectRequest, cardChangeOutProject);
        List<CardChangeOutProject> list = dao.select(cardChangeOutProject);
        for (CardChangeOutProject changeOutProject : list) {
            BaseProject baseProject = new BaseProject();
            baseProject.setId(changeOutProject.getCourseProjectId());
            BaseProject baseProject1 = ssmProjectService.selectOne(baseProject);
            changeOutProject.setProjectNum(baseProject1.getProjectNum());
        }
        return list;
    }

    @Override
    public List<CardChangeOutProjectResponse> selectList1(CardChangeOutProjectRequest cardChangeOutProjectRequest) {
        CardChangeOutProject cardChangeOutProject = new CardChangeOutProject();
        BeanUtils.copyProperties(cardChangeOutProjectRequest, cardChangeOutProject);
        List<CardChangeOutProject> list = dao.select(cardChangeOutProject);
        List<CardChangeOutProjectResponse> responses = new ArrayList<>();
        for (CardChangeOutProject changeOutProject : list) {

            CardChangeOutProjectResponse cardChangeOutProjectResponse = new CardChangeOutProjectResponse();
            BeanUtils.copyProperties(changeOutProject, cardChangeOutProjectResponse);
            //设置业务员
            List<AchiCommEntity> entities = this.getAchiCommList(changeOutProject);
            cardChangeOutProjectResponse.setEntities(entities);

            BaseProject baseProject = new BaseProject();
            baseProject.setId(changeOutProject.getCourseProjectId());
            BaseProject baseProject1 = ssmProjectService.selectOne(baseProject);
            cardChangeOutProjectResponse.setProjectNum(baseProject1.getProjectNum());
            Salesman salesman = new Salesman();
//            salesman.setOrderNum(cardChangeOutProjectResponse.getDocNum());
//            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
//            cardChangeOutProjectResponse.setSalesmen(salesmen);
//            if(salesmen==null||salesmen.size()==0){
                CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(cardChangeOutProjectResponse.getAccountId());
                salesman.setOrderNum(courseAccount.getCourseNum());
                List<Salesman> selectList = ssmSalesmanService.selectList(salesman);
            for (Salesman salesman1 : selectList) {
                salesman1.setType(salesman1.getStaffType());
            }
                cardChangeOutProjectResponse.setSalesmen(selectList);
//            }
            //查询huan'kan
            responses.add(cardChangeOutProjectResponse);
        }
        return responses;
    }

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

        if (null != changeOutProject.getSaleOneStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setDocNum(changeOutProject.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_card_change);
            achiCommEntity.setDocDate(changeOutProject.getDocDate());
            achiCommEntity.setTradeName(changeOutProject.getCourseProjectName());
            achiCommEntity.setBrandNumber(changeOutProject.getSaleOneNumber());
            achiCommEntity.setSaleStaffId(changeOutProject.getSaleOneStaffId());
            achiCommEntity.setSaleStaffName(changeOutProject.getSaleOneStaffName());
            achiCommEntity.setSaleIdentityCard(changeOutProject.getSaleOneIdentity());
            achiCommEntity.setSaleRatio(changeOutProject.getSaleOneRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(changeOutProject.getAchievementAmount(),
                    BigDecimalUtils.div(changeOutProject.getSaleOneRatio(), hundredBD)));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(changeOutProject.getCommissionAmount(),
                    BigDecimalUtils.div(changeOutProject.getSaleOneRatio(), hundredBD)));
            /*achiCommEntity.setCashAchi(BigDecimalUtils.multiply(changeOutProject.getAchievementAmount(), BigDecimalUtils.div(changeOutProject.getSaleOneRatio(), hundredBD)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(changeOutProject.getCommissionAmount(), BigDecimalUtils.div(changeOutProject.getSaleOneRatio(), hundredBD)));*/
            entities.add(achiCommEntity);
        }
        if (null != changeOutProject.getSaleTwoStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setDocNum(changeOutProject.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_card_change);
            achiCommEntity.setDocDate(changeOutProject.getDocDate());
            achiCommEntity.setTradeName(changeOutProject.getCourseProjectName());
            achiCommEntity.setBrandNumber(changeOutProject.getSaleTwoNumber());
            achiCommEntity.setSaleStaffId(changeOutProject.getSaleTwoStaffId());
            achiCommEntity.setSaleStaffName(changeOutProject.getSaleTwoStaffName());
            achiCommEntity.setSaleIdentityCard(changeOutProject.getSaleTwoIdentity());
            achiCommEntity.setSaleRatio(changeOutProject.getSaleTwoRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(changeOutProject.getAchievementAmount(), BigDecimalUtils.div(changeOutProject.getSaleTwoRatio(), hundredBD)));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(changeOutProject.getCommissionAmount(), BigDecimalUtils.div(changeOutProject.getSaleTwoRatio(), hundredBD)));

            entities.add(achiCommEntity);
        }
        if (null != changeOutProject.getSaleThreeStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setDocNum(changeOutProject.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_card_change);
            achiCommEntity.setDocDate(changeOutProject.getDocDate());
            achiCommEntity.setTradeName(changeOutProject.getCourseProjectName());
            achiCommEntity.setBrandNumber(changeOutProject.getSaleThreeNumber());
            achiCommEntity.setSaleStaffId(changeOutProject.getSaleThreeStaffId());
            achiCommEntity.setSaleStaffName(changeOutProject.getSaleThreeStaffName());
            achiCommEntity.setSaleIdentityCard(changeOutProject.getSaleThreeIdentity());
            achiCommEntity.setSaleRatio(changeOutProject.getSaleThreeRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(changeOutProject.getAchievementAmount(), BigDecimalUtils.div(changeOutProject.getSaleThreeRatio(), hundredBD)));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(changeOutProject.getCommissionAmount(), BigDecimalUtils.div(changeOutProject.getSaleThreeRatio(), hundredBD)));

            entities.add(achiCommEntity);
        }
        if (null != changeOutProject.getSaleFourStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setDocNum(changeOutProject.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_card_change);
            achiCommEntity.setDocDate(changeOutProject.getDocDate());
            achiCommEntity.setTradeName(changeOutProject.getCourseProjectName());
            achiCommEntity.setBrandNumber(changeOutProject.getSaleFourNumber());
            achiCommEntity.setSaleStaffId(changeOutProject.getSaleFourStaffId());
            achiCommEntity.setSaleStaffName(changeOutProject.getSaleFourStaffName());
            achiCommEntity.setSaleIdentityCard(changeOutProject.getSaleFourIdentity());
            achiCommEntity.setSaleRatio(changeOutProject.getSaleFourRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(changeOutProject.getAchievementAmount(), BigDecimalUtils.div(changeOutProject.getSaleFourRatio(), hundredBD)));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(changeOutProject.getCommissionAmount(), BigDecimalUtils.div(changeOutProject.getSaleFourRatio(), hundredBD)));

            entities.add(achiCommEntity);
        } if (null != changeOutProject.getSaleFiveStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setDocNum(changeOutProject.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_card_change);
            achiCommEntity.setDocDate(changeOutProject.getDocDate());
            achiCommEntity.setTradeName(changeOutProject.getCourseProjectName());
            achiCommEntity.setBrandNumber(changeOutProject.getSaleFiveNumber());
            achiCommEntity.setSaleStaffId(changeOutProject.getSaleFiveStaffId());
            achiCommEntity.setSaleStaffName(changeOutProject.getSaleFiveStaffName());
            achiCommEntity.setSaleIdentityCard(changeOutProject.getSaleFiveIdentity());
            achiCommEntity.setSaleRatio(changeOutProject.getSaleFiveRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(changeOutProject.getAchievementAmount(), BigDecimalUtils.div(changeOutProject.getSaleFiveRatio(), hundredBD)));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(changeOutProject.getCommissionAmount(), BigDecimalUtils.div(changeOutProject.getSaleFiveRatio(), hundredBD)));

            entities.add(achiCommEntity);
        } if (null != changeOutProject.getSaleSixStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setDocNum(changeOutProject.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_card_change);
            achiCommEntity.setDocDate(changeOutProject.getDocDate());
            achiCommEntity.setTradeName(changeOutProject.getCourseProjectName());
            achiCommEntity.setBrandNumber(changeOutProject.getSaleSixNumber());
            achiCommEntity.setSaleStaffId(changeOutProject.getSaleSixStaffId());
            achiCommEntity.setSaleStaffName(changeOutProject.getSaleSixStaffName());
            achiCommEntity.setSaleIdentityCard(changeOutProject.getSaleSixIdentity());
            achiCommEntity.setSaleRatio(changeOutProject.getSaleSixRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(changeOutProject.getAchievementAmount(), BigDecimalUtils.div(changeOutProject.getSaleSixRatio(), hundredBD)));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(changeOutProject.getCommissionAmount(), BigDecimalUtils.div(changeOutProject.getSaleSixRatio(), hundredBD)));

            entities.add(achiCommEntity);
        } if (null != changeOutProject.getSaleSevenStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setDocNum(changeOutProject.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_card_change);
            achiCommEntity.setDocDate(changeOutProject.getDocDate());
            achiCommEntity.setTradeName(changeOutProject.getCourseProjectName());
            achiCommEntity.setBrandNumber(changeOutProject.getSaleSevenNumber());
            achiCommEntity.setSaleStaffId(changeOutProject.getSaleSevenStaffId());
            achiCommEntity.setSaleStaffName(changeOutProject.getSaleSevenStaffName());
            achiCommEntity.setSaleIdentityCard(changeOutProject.getSaleSevenIdentity());
            achiCommEntity.setSaleRatio(changeOutProject.getSaleSevenRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(changeOutProject.getAchievementAmount(), BigDecimalUtils.div(changeOutProject.getSaleSevenRatio(), hundredBD)));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(changeOutProject.getCommissionAmount(), BigDecimalUtils.div(changeOutProject.getSaleSevenRatio(), hundredBD)));

            entities.add(achiCommEntity);
        } if (null != changeOutProject.getSaleEightStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setDocNum(changeOutProject.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_card_change);
            achiCommEntity.setDocDate(changeOutProject.getDocDate());
            achiCommEntity.setTradeName(changeOutProject.getCourseProjectName());
            achiCommEntity.setBrandNumber(changeOutProject.getSaleEightNumber());
            achiCommEntity.setSaleStaffId(changeOutProject.getSaleEightStaffId());
            achiCommEntity.setSaleStaffName(changeOutProject.getSaleEightStaffName());
            achiCommEntity.setSaleIdentityCard(changeOutProject.getSaleEightIdentity());
            achiCommEntity.setSaleRatio(changeOutProject.getSaleEightRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(changeOutProject.getAchievementAmount(), BigDecimalUtils.div(changeOutProject.getSaleEightRatio(), hundredBD)));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(changeOutProject.getCommissionAmount(), BigDecimalUtils.div(changeOutProject.getSaleEightRatio(), hundredBD)));

            entities.add(achiCommEntity);
        }

        return entities;
    }


    @Override
    public int insert(CardChangeList cardChangeList, List<CardChangeOutProjectRequest> cardChangeOutProjectRequests) throws SmsException {
        int i = 0;
        for (CardChangeOutProjectRequest cardChangeOutProjectRequest : cardChangeOutProjectRequests) {
            CardChangeOutProject cardChangeOutProject = new CardChangeOutProject();
            BeanUtils.copyProperties(cardChangeOutProjectRequest, cardChangeOutProject);
            cardChangeOutProject.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            cardChangeOutProject.setDocNum(cardChangeList.getDocNum());
            cardChangeOutProject.setDocDate(cardChangeList.getDocDate());
            cardChangeOutProject.setStoreId(cardChangeList.getStoreId());
            cardChangeOutProject.setStoreName(cardChangeList.getStoreName());
            //cardChangeOutProject.setAchievementAmount();
            //设置业务员
            List<StaffRequest> staffLists = cardChangeOutProjectRequest.getStaffLists();
            List<StaffRequest> collect = new ArrayList<>();
            if(staffLists!=null && staffLists.size()>0){
                collect = staffLists.stream().filter(item->item.getId()!=null).collect(Collectors.toList());
            }
            if(null != collect && collect.size()>0){
                BigDecimal reduce = collect.stream().map(StaffRequest::getRatio).reduce(BigDecimal.ZERO, BigDecimal::add);
                for (StaffRequest staffRequest : collect) {
                    staffRequest.setRatio(staffRequest.getRatio().divide(reduce,4,BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)));
                }
                this.setStaffValue(collect,cardChangeOutProject);
                //计算业绩
                cardChangeOutProject = this.setAchiComm(cardChangeOutProject, cardChangeOutProject.getChangeOutMoney());

                if(cardChangeList.getChangeInPayMoney().add(cardChangeList.getDebtMoney()).compareTo(BigDecimal.valueOf(0))!=0){
                //账户扣减次数
                CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(cardChangeOutProject.getAccountId());
                cardChangeOutProject.setBeforePrice(courseAccount.getPrice());
                cardChangeOutProject.setBeforeRestMoney(courseAccount.getCourseRestPrice());
                cardChangeOutProject.setBeforeConsumeMoney(courseAccount.getCourseConsumePrice());
                cardChangeOutProject.setBeforeRestCount(courseAccount.getCourseRestCount());
                cardChangeOutProject.setBeforeConsumeCount(courseAccount.getCourseConsumeCount());


                courseAccount = ssmCourseAccountService.subCount1(cardChangeList,courseAccount, cardChangeOutProject.getChangeOutTime(), 0,cardChangeOutProjectRequest.getChangeOutMoney());
//                courseAccount = ssmCourseAccountService.subCount(courseAccount, cardChangeOutProject.getChangeOutTime(), 0);
                cardChangeOutProject.setBackPrice(courseAccount.getPrice());
                cardChangeOutProject.setBackRestMoney(courseAccount.getCourseRestPrice());
                cardChangeOutProject.setBackConsumeMoney(courseAccount.getCourseConsumePrice());
                cardChangeOutProject.setBackRestCount(courseAccount.getCourseRestCount());
                cardChangeOutProject.setBackConsumeCount(courseAccount.getCourseConsumeCount());

                cardChangeOutProject.setCourseRestCount(courseAccount.getCourseRestCount());
                cardChangeOutProject.setCourseConsumeCount(courseAccount.getCourseConsumeCount());

                //添加账户交易记录
                AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(cardChangeOutProject, cardChangeList, courseAccount, 0);
                ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                }

                try {
                    i = dao.saveNotNull(cardChangeOutProject);
                }catch (Exception e){
                    log.error("SsmCardChangeOutProjectServiceImpl.insert:", e);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
                }
            }
            else{
                if(cardChangeList.getChangeInPayMoney().add(cardChangeList.getDebtMoney()).compareTo(BigDecimal.valueOf(0))!=0){
                    //账户扣减次数
                    CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(cardChangeOutProject.getAccountId());
                    cardChangeOutProject.setBeforePrice(courseAccount.getPrice());
                    cardChangeOutProject.setBeforeRestMoney(courseAccount.getCourseRestPrice());
                    cardChangeOutProject.setBeforeConsumeMoney(courseAccount.getCourseConsumePrice());
                    cardChangeOutProject.setBeforeRestCount(courseAccount.getCourseRestCount());
                    cardChangeOutProject.setBeforeConsumeCount(courseAccount.getCourseConsumeCount());
                    courseAccount = ssmCourseAccountService.subCount(courseAccount, cardChangeOutProject.getChangeOutTime(), 0);

                    cardChangeOutProject.setBackPrice(courseAccount.getPrice());
                    cardChangeOutProject.setBackRestMoney(courseAccount.getCourseRestPrice());
                    cardChangeOutProject.setBackConsumeMoney(courseAccount.getCourseConsumePrice());
                    cardChangeOutProject.setBackRestCount(courseAccount.getCourseRestCount());
                    cardChangeOutProject.setBackConsumeCount(courseAccount.getCourseConsumeCount());
                    cardChangeOutProject.setCourseRestCount(courseAccount.getCourseRestCount());
                    cardChangeOutProject.setCourseConsumeCount(courseAccount.getCourseConsumeCount());
                    //添加账户交易记录
                    AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(cardChangeOutProject, cardChangeList, courseAccount, 0);
                    ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                }

                try {
                    i = dao.saveNotNull(cardChangeOutProject);
                }catch (Exception e){
                    log.error("SsmCardChangeOutProjectServiceImpl.insert:", e);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
                }
            }
        }
//        for (CardChangeOutProjectRequest outProjectRequest : cardChangeOutProjectRequests) {
//
//        }
        return i;
    }

    @Override
    public int insertNew(CardChangeList cardChangeList, List<CardChangeOutProjectRequest> cardChangeOutProjectRequests) throws SmsException {
        int i = 0;

        for (CardChangeOutProjectRequest cardChangeOutProjectRequest : cardChangeOutProjectRequests) {
                CardChangeOutProject cardChangeOutProject = new CardChangeOutProject();
                BeanUtils.copyProperties(cardChangeOutProjectRequest, cardChangeOutProject);
//            CourseList courseList = new CourseList();
//            ssmCourseService.selectOne(courseList);
                cardChangeOutProject.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                cardChangeOutProject.setDocNum(cardChangeList.getDocNum());
                cardChangeOutProject.setDocDate(cardChangeList.getDocDate());
                cardChangeOutProject.setDocNum(cardChangeOutProjectRequest.getCourseNum());
                cardChangeOutProject.setStoreId(cardChangeList.getStoreId());
                cardChangeOutProject.setStoreName(cardChangeList.getStoreName());
                cardChangeOutProject.setStoreId(cardChangeList.getStoreId());
                //cardChangeOutProject.setAchievementAmount();
                //设置业务员
                List<StaffRequest> staffLists = cardChangeOutProjectRequest.getStaffLists();
                if(null != staffLists){
                    this.setStaffValue(staffLists,cardChangeOutProject);
                    //计算业绩
                    cardChangeOutProject = this.setAchiComm1(cardChangeOutProject, cardChangeOutProject.getChangeOutMoney());
                    if(cardChangeList.getChangeInPayMoney().compareTo(BigDecimal.valueOf(0))!=0){
                        //账户扣减次数
                        CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(cardChangeOutProject.getAccountId());
                        cardChangeOutProject.setBeforePrice(courseAccount.getPrice());
                        cardChangeOutProject.setBeforeRestMoney(courseAccount.getCourseRestPrice());
                        cardChangeOutProject.setBeforeConsumeMoney(courseAccount.getCourseConsumePrice());
                        cardChangeOutProject.setBeforeRestCount(courseAccount.getCourseRestCount());
                        cardChangeOutProject.setBeforeConsumeCount(courseAccount.getCourseConsumeCount());


                        courseAccount = ssmCourseAccountService.subCount1(cardChangeList,courseAccount, cardChangeOutProject.getChangeOutTime(), 0,cardChangeOutProjectRequest.getChangeOutMoney());
//                courseAccount = ssmCourseAccountService.subCount(courseAccount, cardChangeOutProject.getChangeOutTime(), 0);
                        cardChangeOutProject.setBackPrice(courseAccount.getPrice());
                        cardChangeOutProject.setBackRestMoney(courseAccount.getCourseRestPrice());
                        cardChangeOutProject.setBackConsumeMoney(courseAccount.getCourseConsumePrice());
                        cardChangeOutProject.setBackRestCount(courseAccount.getCourseRestCount());
                        cardChangeOutProject.setBackConsumeCount(courseAccount.getCourseConsumeCount());

                        cardChangeOutProject.setCourseRestCount(courseAccount.getCourseRestCount());
                        cardChangeOutProject.setCourseConsumeCount(courseAccount.getCourseConsumeCount());

                        //添加账户交易记录
                        AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(cardChangeOutProject, cardChangeList, courseAccount, 0);
                        ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                    }

                    try {
                        i = dao.saveNotNull(cardChangeOutProject);
                    }catch (Exception e){
                        log.error("SsmCardChangeOutProjectServiceImpl.insert:", e);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
                    }
                }
                else{
                    if(cardChangeList.getChangeInPayMoney().compareTo(BigDecimal.valueOf(0))!=0){
                        //账户扣减次数
                        CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(cardChangeOutProject.getAccountId());
                        cardChangeOutProject.setBeforePrice(courseAccount.getPrice());
                        cardChangeOutProject.setBeforeRestMoney(courseAccount.getCourseRestPrice());
                        cardChangeOutProject.setBeforeConsumeMoney(courseAccount.getCourseConsumePrice());
                        cardChangeOutProject.setBeforeRestCount(courseAccount.getCourseRestCount());
                        cardChangeOutProject.setBeforeConsumeCount(courseAccount.getCourseConsumeCount());
                        courseAccount = ssmCourseAccountService.subCount(courseAccount, cardChangeOutProject.getChangeOutTime(), 0);

                        cardChangeOutProject.setBackPrice(courseAccount.getPrice());
                        cardChangeOutProject.setBackRestMoney(courseAccount.getCourseRestPrice());
                        cardChangeOutProject.setBackConsumeMoney(courseAccount.getCourseConsumePrice());
                        cardChangeOutProject.setBackRestCount(courseAccount.getCourseRestCount());
                        cardChangeOutProject.setBackConsumeCount(courseAccount.getCourseConsumeCount());
                        cardChangeOutProject.setCourseRestCount(courseAccount.getCourseRestCount());
                        cardChangeOutProject.setCourseConsumeCount(courseAccount.getCourseConsumeCount());
                        //添加账户交易记录
                        AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(cardChangeOutProject, cardChangeList, courseAccount, 0);
                        ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                    }

                    try {
                        i = dao.saveNotNull(cardChangeOutProject);
                    }catch (Exception e){
                        log.error("SsmCardChangeOutProjectServiceImpl.insert:", e);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
                    }
                }
            }

        return i;
    }

    @Override
    public int inserts(CardChangeList cardChangeList, List<CardChangeOutProject> cardChangeOutProjectRequests) throws SmsException {
        int i = 1;
        for (CardChangeOutProject cardChangeOutProject : cardChangeOutProjectRequests) {
            //账户扣减次数
            CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(cardChangeOutProject.getAccountId());

            cardChangeOutProject.setBeforePrice(courseAccount.getPrice());
            cardChangeOutProject.setBeforeRestMoney(courseAccount.getCourseRestPrice());
            cardChangeOutProject.setBeforeConsumeMoney(courseAccount.getCourseConsumePrice());
            cardChangeOutProject.setBeforeRestCount(courseAccount.getCourseRestCount());
            cardChangeOutProject.setBeforeConsumeCount(courseAccount.getCourseConsumeCount());
            courseAccount = ssmCourseAccountService.subCount1(cardChangeList,courseAccount, cardChangeOutProject.getChangeOutTime(), 0,cardChangeOutProject.getChangeOutMoney());
            cardChangeOutProject.setBackPrice(courseAccount.getPrice());
            cardChangeOutProject.setBackRestMoney(courseAccount.getCourseRestPrice());
            cardChangeOutProject.setBackConsumeMoney(courseAccount.getCourseConsumePrice());
            cardChangeOutProject.setBackRestCount(courseAccount.getCourseRestCount());
            cardChangeOutProject.setBackConsumeCount(courseAccount.getCourseConsumeCount());

            cardChangeOutProject.setCourseRestCount(courseAccount.getCourseRestCount());
            cardChangeOutProject.setCourseConsumeCount(courseAccount.getCourseConsumeCount());
            //添加账户交易记录
            AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(cardChangeOutProject, cardChangeList, courseAccount, 0);
            ssmAccountTradeRecordService.addRecord(accountTradeRecord);

            i = dao.updateByPrimaryKeySelective(cardChangeOutProject);
        }

        return i;
    }


    /*
     * 账户交易记录属性赋值 转出账户
     * */
    public AccountTradeRecord setAccountTradeRecord(CardChangeOutProject cardChangeOutProject, CardChangeList cardChangeList, CourseAccount courseAccount, int type){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(cardChangeList.getStoreId());
        accountTradeRecord.setStoreName(cardChangeList.getStoreName());
        accountTradeRecord.setMemberId(cardChangeList.getMemberId());
        accountTradeRecord.setMemberName(cardChangeList.getMemberName());
//        accountTradeRecord.setMemberIdentity(cardChangeOutProject.getMemberIdentityCard());
        accountTradeRecord.setMemberPhone(cardChangeList.getMobilePhone());
        //疗程转出
        if (null != courseAccount) {
            accountTradeRecord.setAccountId(courseAccount.getId());
            accountTradeRecord.setAccountName(courseAccount.getCourseProjectName());
            //if (cardChangeList.getIsCancel() == 0 || 3 == cardChangeList.getState()) {
            if (cardChangeList.getState() == 3) {
                if(cardChangeList.getChangeInPayMoney().compareTo(BigDecimal.valueOf(0))==0){
                    accountTradeRecord.setAccountType("LCNTZC");
                }else {
                    accountTradeRecord.setAccountType(Constant.account_type_project_consume);
                }
                accountTradeRecord.setInputDate(cardChangeList.getDocDate());
                accountTradeRecord.setInputBy(cardChangeList.getInputBy());
                accountTradeRecord.setAccountSpendCount(cardChangeOutProject.getChangeOutTime());
                //花费金额为单次成交金额
                accountTradeRecord.setAccountSpendMoney(cardChangeOutProject.getChangeOutMoney());
                accountTradeRecord.setOrderStatu(0);
            }else {
                if(cardChangeList.getChangeInPayMoney().compareTo(BigDecimal.valueOf(0))==0){
                    accountTradeRecord.setAccountType("LCNTZCZF");
                }else {
                    accountTradeRecord.setAccountType(Constant.account_type_project_consume_cancel);
                }
                accountTradeRecord.setInputDate(cardChangeList.getCancelDate());
                accountTradeRecord.setInputBy(cardChangeList.getCancelBy());
                accountTradeRecord.setAccountInCount(cardChangeOutProject.getChangeOutTime());
                accountTradeRecord.setAccountInMoney(cardChangeOutProject.getChangeOutMoney());
                accountTradeRecord.setOrderStatu(1);
            }
            accountTradeRecord.setAccountRestCount(courseAccount.getCourseRestCount());
            accountTradeRecord.setAccountConsumeCount(courseAccount.getCourseConsumeCount());
        }
        accountTradeRecord.setIsAddition(cardChangeList.getIsAddition());
        accountTradeRecord.setDocId(cardChangeList.getId());
        accountTradeRecord.setDocNum(cardChangeList.getDocNum());
        if (0 == type) //加价
            accountTradeRecord.setDocType(Constant.doc_type_card_change);
        else //内调
            accountTradeRecord.setDocType(Constant.doc_type_card_change_nt);
        accountTradeRecord.setTradeId(cardChangeOutProject.getCourseProjectId());
        accountTradeRecord.setTradeName(cardChangeOutProject.getCourseProjectName());
        accountTradeRecord.setTradeMoney(cardChangeOutProject.getChangeOutMoney());
        accountTradeRecord.setTradeCount(cardChangeOutProject.getChangeOutTime());
        accountTradeRecord.setDebtMoney(cardChangeList.getDebtMoney());
        accountTradeRecord.setPrice(courseAccount.getCourseProjectMoneys().divide(BigDecimalUtils.bigDecimal(courseAccount.getCourseCounts().toString()),2,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 cancel(CardChangeList cardChangeList) throws SmsException {
        int i = 0;
        CardChangeOutProject cardChangeOutProject = new CardChangeOutProject();
        cardChangeOutProject.setDocNum(cardChangeList.getDocNum());
        List<CardChangeOutProject> list = dao.select(cardChangeOutProject);
        for (CardChangeOutProject changeOutProject : list) {
            //查询账户
            CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(changeOutProject.getAccountId());

            if(changeOutProject.getBackPrice().compareTo(courseAccount.getPrice())!=0){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            if(changeOutProject.getBackRestMoney().compareTo(courseAccount.getCourseRestPrice())!=0){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            if(changeOutProject.getBackConsumeMoney().compareTo(courseAccount.getCourseConsumePrice())!=0){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            if(changeOutProject.getBackRestCount() != courseAccount.getCourseRestCount()){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            if(changeOutProject.getBackConsumeCount() != courseAccount.getCourseConsumeCount()){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            //增加转出疗程账户次数
//            courseAccount = ssmCourseAccountService.addCount(courseAccount, changeOutProject.getChangeOutTime());
            courseAccount.setPrice(changeOutProject.getBeforePrice());
            courseAccount.setCourseRestPrice(changeOutProject.getBeforeRestMoney());
            courseAccount.setCourseConsumePrice(changeOutProject.getBeforeConsumeMoney());
            courseAccount.setCourseRestCount(changeOutProject.getBeforeRestCount());
            courseAccount.setCourseConsumeCount(changeOutProject.getBeforeConsumeCount());
            courseAccount.setExpenditureMoney(courseAccount.getExpenditureMoney().subtract(courseAccount.getPrice().multiply(BigDecimalUtils.bigDecimal(changeOutProject.getChangeOutTime().toString()))));
            ssmCourseAccountService.updateNotNull(courseAccount);
            //添加账户交易记录
            AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(changeOutProject, cardChangeList, courseAccount, 0);
            accountTradeRecord.setOrderStatu(1);
            ssmAccountTradeRecordService.addRecord(accountTradeRecord);
            //更新转出疗程账户信息
            changeOutProject.setCourseRestCount(courseAccount.getCourseRestCount());
            changeOutProject.setCourseConsumeCount(courseAccount.getCourseConsumeCount());
            try {
                i = dao.updateByPrimaryKeySelective(changeOutProject);
            }catch (Exception e){
                log.error("SsmCardChangeOutProjectServiceImpl.cancel:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
        }
        return i;
    }

    @Override
    public int updateStaff(List<CardChangeOutProjectRequest> cardChangeOutProjectRequestList) throws SmsException {
        return dao.updateStaff(cardChangeOutProjectRequestList);
    }

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

    @Override
    public int audit(CardChangeList cardChangeList) throws SmsException {
        int i = 0;
        CardChangeOutProject cardChangeOutProject = new CardChangeOutProject();
        cardChangeOutProject.setDocNum(cardChangeList.getDocNum());
        List<CardChangeOutProject> list = dao.select(cardChangeOutProject);
        for (CardChangeOutProject changeOutProject : list) {
            //查询账户
            CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(changeOutProject.getAccountId());
            //减去转出疗程账户次数
            courseAccount = ssmCourseAccountService.subCount1(cardChangeList,courseAccount, changeOutProject.getChangeOutTime(), 0,changeOutProject.getChangeOutMoney());

            //添加账户交易记录
            AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(changeOutProject, cardChangeList, courseAccount, 1);
            ssmAccountTradeRecordService.addRecord(accountTradeRecord);
            //更新转出疗程账户信息
            changeOutProject.setCourseRestCount(courseAccount.getCourseRestCount());
            changeOutProject.setCourseConsumeCount(courseAccount.getCourseConsumeCount());
            try {
                i = dao.updateByPrimaryKeySelective(changeOutProject);
            }catch (Exception e){
                log.error("SsmCardChangeOutProjectServiceImpl.audit:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
        }
        return i;
    }


    @Override
    public int unAudit(CardChangeList cardChangeList) throws SmsException {
        int i = 0;
        CardChangeOutProject cardChangeOutProject = new CardChangeOutProject();
        cardChangeOutProject.setDocNum(cardChangeList.getDocNum());
        List<CardChangeOutProject> list = dao.select(cardChangeOutProject);
        for (CardChangeOutProject changeOutProject : list) {
            //查询账户
            CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(changeOutProject.getAccountId());
            //增加转出疗程账户次数
            courseAccount = ssmCourseAccountService.addCount(courseAccount, changeOutProject.getChangeOutTime());
            //添加账户交易记录
            AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(changeOutProject, cardChangeList, courseAccount, 1);
            ssmAccountTradeRecordService.addRecord(accountTradeRecord);
            //更新转出疗程账户信息
            changeOutProject.setCourseRestCount(courseAccount.getCourseRestCount());
            changeOutProject.setCourseConsumeCount(courseAccount.getCourseConsumeCount());
            try {
                i = dao.updateByPrimaryKeySelective(changeOutProject);
            }catch (Exception e){
                log.error("SsmCardChangeOutProjectServiceImpl.unAudit:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
        }
        return i;
    }

    @Override
    public int insertLCNT(CardChangeList cardChangeList, CardChangeListRequest cardChangeListRequest ) throws SmsException {
        int i = 0;
        List<CardChangeOutProjectRequest> cardChangeOutProjectRequests = cardChangeListRequest.getCardChangeOutProjectRequests();
        for (CardChangeOutProjectRequest cardChangeOutProjectRequest : cardChangeOutProjectRequests) {
            CardChangeOutProject cardChangeOutProject = new CardChangeOutProject();
            BeanUtils.copyProperties(cardChangeOutProjectRequest, cardChangeOutProject);
            cardChangeOutProject.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            cardChangeOutProject.setDocNum(cardChangeList.getDocNum());
            cardChangeOutProject.setDocDate(cardChangeList.getDocDate());
            cardChangeOutProject.setStoreId(cardChangeList.getStoreId());
            cardChangeOutProject.setStoreName(cardChangeList.getStoreName());
            //cardChangeOutProject.setAchievementAmount();
            //查询原来的销售人员进行修改
//            Salesman salesman = new Salesman();
//            salesman.setOrderNum(cardChangeListRequest.getDocNum());
//            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
//            if(salesmen!=null && salesmen.size()>0){
//                for (Salesman salesman1 : salesmen) {
//                    salesman1.setOrderNum(cardChangeList.getDocNum());
//                    salesman1.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
//                }
//                ssmSalesmanService.addBatch(salesmen);
//            }
            //设置业务员
            List<StaffRequest> staffLists = cardChangeOutProjectRequest.getStaffLists();
            if(null != staffLists){
                this.setStaffValue(staffLists,cardChangeOutProject);
                //计算业绩
                cardChangeOutProject = this.setAchiComm(cardChangeOutProject, cardChangeOutProject.getChangeOutMoney());
                if(cardChangeList.getChangeInPayMoney().compareTo(BigDecimal.valueOf(0))!=0){
                    //账户扣减次数
                    CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(cardChangeOutProject.getAccountId());
                    cardChangeOutProject.setBeforePrice(courseAccount.getPrice());
                    cardChangeOutProject.setBeforeRestMoney(courseAccount.getCourseRestPrice());
                    cardChangeOutProject.setBeforeConsumeMoney(courseAccount.getCourseConsumePrice());
                    cardChangeOutProject.setBeforeRestCount(courseAccount.getCourseRestCount());
                    cardChangeOutProject.setBeforeConsumeCount(courseAccount.getCourseConsumeCount());


                    courseAccount = ssmCourseAccountService.subCount1(cardChangeList,courseAccount, cardChangeOutProject.getChangeOutTime(), 0,cardChangeOutProjectRequest.getChangeOutMoney());
//                courseAccount = ssmCourseAccountService.subCount(courseAccount, cardChangeOutProject.getChangeOutTime(), 0);
                    cardChangeOutProject.setBackPrice(courseAccount.getPrice());
                    cardChangeOutProject.setBackRestMoney(courseAccount.getCourseRestPrice());
                    cardChangeOutProject.setBackConsumeMoney(courseAccount.getCourseConsumePrice());
                    cardChangeOutProject.setBackRestCount(courseAccount.getCourseRestCount());
                    cardChangeOutProject.setBackConsumeCount(courseAccount.getCourseConsumeCount());

                    cardChangeOutProject.setCourseRestCount(courseAccount.getCourseRestCount());
                    cardChangeOutProject.setCourseConsumeCount(courseAccount.getCourseConsumeCount());

                    //添加账户交易记录
                    AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(cardChangeOutProject, cardChangeList, courseAccount, 0);
                    ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                }

                try {
                    i = dao.saveNotNull(cardChangeOutProject);
                }catch (Exception e){
                    log.error("SsmCardChangeOutProjectServiceImpl.insert:", e);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
                }
            }
            else{
                if(cardChangeList.getChangeInPayMoney().compareTo(BigDecimal.valueOf(0))!=0){
                    //账户扣减次数
                    CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(cardChangeOutProject.getAccountId());
                    cardChangeOutProject.setBeforePrice(courseAccount.getPrice());
                    cardChangeOutProject.setBeforeRestMoney(courseAccount.getCourseRestPrice());
                    cardChangeOutProject.setBeforeConsumeMoney(courseAccount.getCourseConsumePrice());
                    cardChangeOutProject.setBeforeRestCount(courseAccount.getCourseRestCount());
                    cardChangeOutProject.setBeforeConsumeCount(courseAccount.getCourseConsumeCount());
                    courseAccount = ssmCourseAccountService.subCount(courseAccount, cardChangeOutProject.getChangeOutTime(), 0);

                    cardChangeOutProject.setBackPrice(courseAccount.getPrice());
                    cardChangeOutProject.setBackRestMoney(courseAccount.getCourseRestPrice());
                    cardChangeOutProject.setBackConsumeMoney(courseAccount.getCourseConsumePrice());
                    cardChangeOutProject.setBackRestCount(courseAccount.getCourseRestCount());
                    cardChangeOutProject.setBackConsumeCount(courseAccount.getCourseConsumeCount());
                    cardChangeOutProject.setCourseRestCount(courseAccount.getCourseRestCount());
                    cardChangeOutProject.setCourseConsumeCount(courseAccount.getCourseConsumeCount());
                    //添加账户交易记录
                    AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(cardChangeOutProject, cardChangeList, courseAccount, 0);
                    ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                }

                try {
                    i = dao.saveNotNull(cardChangeOutProject);
                }catch (Exception e){
                    log.error("SsmCardChangeOutProjectServiceImpl.insert:", e);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
                }
            }
        }
//        for (CardChangeOutProjectRequest outProjectRequest : cardChangeOutProjectRequests) {
//
//        }
        return i;
    }

    @Override
    public int updateStaffLCNT(List<CardChangeOutProjectRequest> cardChangeOutProjectRequests) throws SmsException {
        return dao.updateStaffLCNT(cardChangeOutProjectRequests);
    }

    @Autowired
    private CardChangeOutProjectMapper mapper;
    @Override
    public List<CardChangeOutProject> selectNew(CardChangeListRequest cardChangeListRequest) {
        return mapper.selectNew(cardChangeListRequest);
    }


    /*
     * 业务员赋值
     * */
    public void setStaffValue(List<StaffRequest> staffLists, CardChangeOutProject cardChangeOutProject){
        for (int i = 0; i < staffLists.size(); i++) {
            StaffRequest staffRequest = staffLists.get(i);
            if (i == 0){
                cardChangeOutProject.setSaleOneStaffId(staffRequest.getId());
                cardChangeOutProject.setSaleOneStaffName(staffRequest.getStaffName());
                cardChangeOutProject.setSaleOneIdentity(staffRequest.getIdentityCard());
                cardChangeOutProject.setSaleOneRatio(staffRequest.getRatio());
                cardChangeOutProject.setSaleOneNumber(staffRequest.getBrandNumber());
            }else if (i == 1){
                cardChangeOutProject.setSaleTwoStaffId(staffRequest.getId());
                cardChangeOutProject.setSaleTwoStaffName(staffRequest.getStaffName());
                cardChangeOutProject.setSaleTwoIdentity(staffRequest.getIdentityCard());
                cardChangeOutProject.setSaleTwoRatio(staffRequest.getRatio());
                cardChangeOutProject.setSaleTwoNumber(staffRequest.getBrandNumber());
            }else if (i == 2){
                cardChangeOutProject.setSaleThreeStaffId(staffRequest.getId());
                cardChangeOutProject.setSaleThreeStaffName(staffRequest.getStaffName());
                cardChangeOutProject.setSaleThreeIdentity(staffRequest.getIdentityCard());
                cardChangeOutProject.setSaleThreeRatio(staffRequest.getRatio());
                cardChangeOutProject.setSaleThreeNumber(staffRequest.getBrandNumber());
            }else if (i == 3){
                cardChangeOutProject.setSaleFourStaffId(staffRequest.getId());
                cardChangeOutProject.setSaleFourStaffName(staffRequest.getStaffName());
                cardChangeOutProject.setSaleFourIdentity(staffRequest.getIdentityCard());
                cardChangeOutProject.setSaleFourRatio(staffRequest.getRatio());
                cardChangeOutProject.setSaleFourNumber(staffRequest.getBrandNumber());

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

    public CardChangeOutProject setAchiComm(CardChangeOutProject cardChangeOutProject, BigDecimal changeOutMoney){
        BigDecimal times = BigDecimalUtils.bigDecimal(cardChangeOutProject.getChangeOutTime().toString());
        //现付销售业绩标准  >0 <1比率   >1固定金额
        BigDecimal achiRatio = cardChangeOutProject.getSalesAchievement()==null?BigDecimal.valueOf(0):cardChangeOutProject.getSalesAchievement();
        //现付销售提成标准  >0 <1比率   >1固定金额
        BigDecimal commRatio = cardChangeOutProject.getSalesCommission()==null?BigDecimal.valueOf(0):cardChangeOutProject.getSalesCommission();
        //比率
        if (BigDecimalUtils.compareTo(achiRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
            cardChangeOutProject.setAchievementAmount(BigDecimalUtils.multiply(achiRatio, changeOutMoney));
        } else {//固定金额
            cardChangeOutProject.setAchievementAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(changeOutMoney, cardChangeOutProject.getUnitMoney()), achiRatio), times));
        }
        //提成比率
        if (BigDecimalUtils.compareTo(commRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
            cardChangeOutProject.setCommissionAmount(BigDecimalUtils.multiply(commRatio, cardChangeOutProject.getAchievementAmount()));
        } else {//提成固定金额
            cardChangeOutProject.setCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(changeOutMoney, cardChangeOutProject.getUnitMoney()), commRatio), times));
        }

        return cardChangeOutProject;
    }


    public CardChangeOutProject setAchiComm1(CardChangeOutProject cardChangeOutProject, BigDecimal changeOutMoney){
        String string = cardChangeOutProject.getDocNum();
        CourseList courseVo = null;
        CardChangeInProject cardChangeInProject1 = null;
        String docNum = string.substring(string.length()-11, string.length() - 3);
        StrBuilder strBuilder = new StrBuilder(docNum);
        StrBuilder docDate = strBuilder.insert(6, "-").insert(4, "-");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = null;
        try {
            parse = simpleDateFormat.parse(String.valueOf(docDate));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        if(string.startsWith("LC")){
            CourseList courseList = new CourseList();
            courseList.setDate(parse);
            courseList.setCourseReatmentNum(string);
            courseList.setProjctId(cardChangeOutProject.getCourseProjectId());
            //根据单号和项目类型查询详细的疗程信息
            courseVo = ssmCourseService.selectOne(courseList);
        }else if(string.startsWith("ZLC")){
            //根据单号查询加价转疗程的表获取相应信息
            CardChangeInProject cardChangeInProject = new CardChangeInProject();
            cardChangeInProject.setDocNum(string);
            cardChangeInProject.setProjectId(cardChangeOutProject.getCourseProjectId());
            cardChangeInProject1 = ssmCardChangeInProjectService.selectOne(cardChangeInProject);
        }

        //现付销售业绩标准
        BigDecimal cashAchiRatio = cardChangeOutProject.getSalesAchievement();
        //现付销售提成标准
        BigDecimal cashCommRation = cardChangeOutProject.getSalesCommission();
        //卡付销售业绩标准  >0 <1比率   >1固定金额
        BigDecimal achiRatio = cardChangeOutProject.getCardSalesAchievement();
        //卡付销售提成标准  >0 <1比率   >1固定金额
        BigDecimal commRatio = cardChangeOutProject.getCardSalesCommission();

        BigDecimal times = BigDecimalUtils.bigDecimal(cardChangeOutProject.getChangeOutTime().toString());
        List<StoreParament> storeParaments = ssmStoreParaService.list(cardChangeOutProject.getStoreId());
        StoreParament projectOut = null;
        for (StoreParament storeParament : storeParaments) {
            if(storeParament.getParamentName().equals("projectOut")){
                projectOut = storeParament;
            }
        }
        switch (projectOut.getParamentValue()){
            case "1":
                if(BigDecimalUtils.compareTo(achiRatio, BigDecimalUtils.bigDecimal("1")) != 1){
//                    cardChangeOutProject.setAchievementAmount(cardChangeOutProject);
                }
        }

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

        return cardChangeOutProject;
    }
}
