package com.ssm.manage.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.BigDecimalUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.core.utils.StoreParaUtils;
import com.ssm.manage.dao.SsmServiceOrderDao;
import com.ssm.manage.dao.SsmServiceOrdersDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.extendEntity.AchiCommEntity;
import com.ssm.manage.query.*;
import com.ssm.manage.response.*;
import com.ssm.manage.service.*;
import com.ssm.manage.utils.Constant;
import com.ssm.manage.utils.DateUtils;
import com.ssm.util.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
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.*;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;

@Service
@Slf4j
public class SsmServiceOrdersServiceImpl extends BaseServiceImpl<ServiceOrders> implements SsmServiceOrdersService {

    private static String staffKey = "staffKey";

    @Autowired
    private RedisClient<StaffResponse> redisClient;

    @Autowired
    private SsmServiceOrdersDao dao;
    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmProjectService ssmProjectService;
    @Autowired
    private SsmMemberCsService ssmMemberCsService;

    @Autowired
    private SsmRechargeTypeSevice ssmRechargeTypeSevice;

    @Autowired
    private SsmRechargeAccountService ssmRechargeAccountService;

    @Autowired
    private SsmCashAccountSrevice ssmCashAccountSrevice;

    @Autowired
    private SsmAccountTradeRecordService ssmAccountTradeRecordService;

    @Autowired
    private SsmStoreMemberService ssmStoreMemberService;

    @Autowired
    private SsmCourseAccountService ssmCourseAccountService;

    @Autowired
    private SsmStoreRoomService ssmStoreRoomService;
    @Autowired
    private SsmStoreSettlementService ssmStoreSettlementService;

    @Autowired
    private SsmPayService ssmPayService;

    @Autowired
    private SsmClockServiceService ssmClockServiceService;

    @Autowired
    private SsmStoreRoomHandService ssmStoreRoomHandService;
    @Autowired
    private SsmServiceOrderService ssmServiceOrderService;

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

    @Override
    public PageInfo<ServiceOrdersResponse> selectPage(ServiceOrdersRequest serviceOrderRequest) throws SmsException, ParseException {
        List<ServiceOrdersResponse> serviceOrdersResponses = new ArrayList<>();

        int pageNum = serviceOrderRequest.getPageNum();
        int pageSize = serviceOrderRequest.getPageSize();
        if(pageNum!=1){
            int page= pageNum*pageSize;
            serviceOrderRequest.setPageSize(page-1);
            serviceOrderRequest.setPageNum(pageSize);
        }else{
            serviceOrderRequest.setPageNum(0);
        }
        List<ServiceOrders> serviceOrders = dao.selectGroupIsPage(serviceOrderRequest);
        for (ServiceOrders serviceOrder : serviceOrders) {
            ServiceOrdersResponse serviceOrdersResponse = new ServiceOrdersResponse();
            BeanUtils.copyProperties(serviceOrder,serviceOrdersResponse);
            ServiceOrdersRequest serviceOrdersRequest = new ServiceOrdersRequest();
            serviceOrdersRequest.setDocDate(serviceOrderRequest.getDocDate());
            serviceOrdersRequest.setSettlementNum(serviceOrder.getSettlementNum());
            serviceOrdersRequest.setStoreId(serviceOrder.getStoreId());
            List<ServiceOrders> docNum = dao.getDocNum(serviceOrdersRequest);
            List<ServiceOrdersRequest> serviceOrdersRequests = new ArrayList<>();
            for (ServiceOrders orders : docNum) {
                ServiceOrdersRequest serviceOrdersRequest1 = new ServiceOrdersRequest();
                BeanUtils.copyProperties(orders,serviceOrdersRequest1);
                AccountTradeRecordRequest accountTradeRecordRequest = new AccountTradeRecordRequest();
                accountTradeRecordRequest.setDocType(Constant.doc_type_store_cash_room);
                accountTradeRecordRequest.setAccountType(Constant.account_type_recharge_consume_room);
                accountTradeRecordRequest.setDocId(orders.getId());
                accountTradeRecordRequest.setStoreId(orders.getStoreId());
                accountTradeRecordRequest.setInputDate(orders.getInputDate());
                List<RechargeAccountResponse> list = new ArrayList<>();
                List<AccountTradeRecord> accountTradeRecords = ssmAccountTradeRecordService.selectList(accountTradeRecordRequest);
                for (AccountTradeRecord accountTradeRecord : accountTradeRecords) {
                    RechargeAccountResponse rechargeAccountResponse = new RechargeAccountResponse();
                    RechargeAccount rechargeAccount = ssmRechargeAccountService.selectByPrimaryKey(accountTradeRecord.getAccountId());
                    BeanUtils.copyProperties(rechargeAccount,rechargeAccountResponse);
                    rechargeAccountResponse.setSpendMoney(accountTradeRecord.getAccountSpendMoney());
                    rechargeAccountResponse.setAccountGiftSpendMoney(accountTradeRecord.getAccountGiftSpendMoney());
                    list.add(rechargeAccountResponse);
                }
                serviceOrdersRequest1.setRechargeAccountResponses(list);
                serviceOrdersRequests.add(serviceOrdersRequest1);
                serviceOrdersResponse.setServiceOrdersRequests(serviceOrdersRequests);
            }
            PayList payList = new PayList();
            payList.setType("store_room");
            payList.setDocId(serviceOrder.getSettlementNum());
            payList.setStoreId(serviceOrder.getStoreId());
            List<PayList> select = ssmPayService.select(payList);
            serviceOrdersResponse.setPayLists(select);
            serviceOrdersResponses.add(serviceOrdersResponse);
        }
        PageInfo<ServiceOrdersResponse> objectPageInfo = new PageInfo<>(serviceOrdersResponses);
        List<ServiceOrders> serviceOrderssize = dao.selectGroup(serviceOrderRequest);
//        List<ServiceOrdersResponse> rateContributions1 = new ArrayList<>();
//        int pageNum = 0;
//        int pageSize = 0;
//        if(serviceOrderRequest.getPageNum()!=1){
//            pageNum=(serviceOrderRequest.getPageNum()*serviceOrderRequest.getPageSize())-11;
//        }
//        if(pageNum==0){
//            pageSize = serviceOrderRequest.getPageSize();
//        }else{
//            pageSize = (serviceOrderRequest.getPageNum()*serviceOrderRequest.getPageSize());
//        }
//        if(pageSize>rateContributions.size()){
//            pageSize= rateContributions.size();
//        }
//
//        if(rateContribution.getSorts()==0){
//            rateContributions.sort(comparing(RateContribution::getAmount).reversed());
//        }else{
//            rateContributions.sort(comparing(RateContribution::getAmount));
//        }
//
//        List<RateContribution> rateContributions2 = rateContributions.subList(pageNum, pageSize);
//        PageInfo<RateContribution> objectPageInfo = new PageInfo<>(rateContributions2);
//        objectPageInfo.setTotal(rateContributions.size());
//        return objectPageInfo;
        objectPageInfo.setTotal(serviceOrderssize.size());
        return objectPageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<AccountTradeRecord> add(List<ServiceOrdersRequest> serviceOrdersRequest,String phone) throws SmsException {
        int a = 0;
        Long storeId = serviceOrdersRequest.get(0).getStoreId();
        String storeName = serviceOrdersRequest.get(0).getStoreName();

        Date date = new Date();
        //单据号
        ServiceOrdersRequest cashListRequest = new ServiceOrdersRequest();
        cashListRequest.setDocDate(date);
        cashListRequest.setSelectDate(DateUtils.YMFormat(date));
        cashListRequest.setStoreId(storeId);
        String docNum = this.getDocNum(cashListRequest);

        List<AccountTradeRecord> list = new ArrayList<>();

        //循环结算的项目
        int w=0;
        for (ServiceOrdersRequest ordersRequest : serviceOrdersRequest) {
            w++;
            StoreSettlement storeSettlement = new StoreSettlement();
            storeSettlement.setId(ordersRequest.getId());
            StoreSettlement storeSettlement1 = ssmStoreSettlementService.selectByPrimaryKey(storeSettlement.getId());
            if(null == storeSettlement1.getServiceEndDate()){
                throw new SmsException(ResponseCode.MSG,"第"+w+"条单据技师未下钟，不能结算，请先让技师下钟");
            }
        }
        for (ServiceOrdersRequest ordersRequest : serviceOrdersRequest) {
            //结算完回去清理服务中数据
            Long id = ordersRequest.getId();
            ServiceOrders serviceOrders = new ServiceOrders();
            BeanUtils.copyProperties(ordersRequest,serviceOrders);
            if(null == serviceOrders.getServiceTechnicianOneStaffId()){
                throw new SmsException(ResponseCode.MSG,"未选择服务技师");
            }
            if(null == ordersRequest.getProjectId()){
                throw new SmsException(ResponseCode.MSG,"未选择服务项目");
            }
            serviceOrders.setState(0);
            serviceOrders.setDocDate(date);

            Long cashId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
            serviceOrders.setId(cashId);
            serviceOrders.setSettlementNum(docNum);

            StaffResponse staffResponse = new StaffResponse();
            Set<String> keys = redisClient.keys(getStaffKey(phone) + "*");
            //从redis查询 设置录单人信息 app使用
            if (keys.size() > 0){
                String key =  new ArrayList<>(keys).get(0);
                staffResponse = redisClient.get(key);
            }

            serviceOrders.setInputId(staffResponse.getId());
            serviceOrders.setInputBy(staffResponse.getStaffName());
            serviceOrders.setInputDate(new Date());

            //查询最低价控制门店参数
            StoreParament storeParament = StoreParaUtils.getStorePara(storeId, Constant.minimum);
            //有最低价控制  校验成交单价
            if ("1".equals(storeParament.getParamentValue())) {
                //会员最低价校验
                if (null != serviceOrders.getMemberId() && BigDecimalUtils.compareTo(serviceOrders.getTransactionPrice(), serviceOrders.getMinumumPriceMember()) == -1) {
                    throw new SmsException(ResponseCode.MINUMUM_PRICE_LOW, "成交价");
                } else if (null == serviceOrders.getMemberId() && BigDecimalUtils.compareTo(serviceOrders.getTransactionPrice(), serviceOrders.getMinumumPrice()) == -1) {
                    //散客最低价校验
                    throw new SmsException(ResponseCode.MINUMUM_PRICE_LOW, "成交价");
                }
            }

            serviceOrders.setAmount(serviceOrders.getAmount());
            serviceOrders.setCollectionCashAmount(serviceOrders.getCollectionCashAmount());
            serviceOrders.setCollectionRechargeAmount(serviceOrders.getCollectionRechargeAmount());
            serviceOrders.setCollectionIntegralAmount(serviceOrders.getCollectionIntegralAmount());
            serviceOrders.setCollectionGiftAmount(serviceOrders.getCollectionGiftAmount());
            serviceOrders.setCashAmount(serviceOrders.getCashAmount());
            serviceOrders.setCourseAccountId(serviceOrders.getCourseAccountId());

            //项目成交价
            BigDecimal transactionPrice = serviceOrders.getTransactionPrice();

            //充值卡付判断
            List<RechargeAccountRequest> rechargeAccountList = ordersRequest.getRechargeAccountList();

            BigDecimal discountMoneyTotal = BigDecimalUtils.bigDecimal("0");
            BigDecimal giftMoneyTotal = BigDecimalUtils.bigDecimal("0");
            if (null != rechargeAccountList && rechargeAccountList.size() > 0) {
                BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
                if (serviceOrders.getNoDiscount() == 0) {
                    //打折
                    for (RechargeAccountRequest rechargeAccountRequest : rechargeAccountList) {
                        RechargeAccount rechargeAccount = new RechargeAccount();
                        rechargeAccount.setId(rechargeAccountRequest.getId());
                        RechargeAccount rechargeAccount1 = ssmRechargeAccountService.selectByPrimaryKey(rechargeAccount.getId());
                        if(rechargeAccount1.getCardConsumeMoney().compareTo(rechargeAccountRequest.getCardConsumeMoney())!=0){
                            throw new SmsException(ResponseCode.MSG, "账户付款前可用金额和账户当前剩余可用金额不相等");
                        }
                    }
                    for (RechargeAccountRequest rechargeAccountRequest : rechargeAccountList) {
                        RechargeAccount rechargeAccount = ssmRechargeAccountService.selectByPrimaryKey(rechargeAccountRequest.getId());

                        //判断账户剩余可用金额是否小于卡付金额
                        if (BigDecimalUtils.compareTo(rechargeAccount.getCardConsumeMoney(), rechargeAccountRequest.getSpendMoney()) == -1) {
                            throw new SmsException(ResponseCode.STORE_CASH_NOT_PERMISSION, "账户可消费金额小于卡付金额");
                        }
                        if (BigDecimalUtils.compareTo(rechargeAccount.getGiftConsumeMoney(), rechargeAccountRequest.getGiftSpendMoney()) == -1) {
                            throw new SmsException(ResponseCode.STORE_CASH_NOT_PERMISSION, "账户赠送可消费金额小于卡付金额");
                        }
                        BigDecimal discountMoney = BigDecimalUtils.bigDecimal("0");
//                         && cashListRequest.getNoDiscount() == 0
                        if (rechargeAccount.getType() == 1) {

                            //计算卡付金额抵扣金额
                            discountMoney = BigDecimalUtils.div(rechargeAccountRequest.getSpendMoney(), BigDecimalUtils.div(rechargeAccountRequest.getDiscount(), hundredBd));
                            discountMoneyTotal = BigDecimalUtils.add(discountMoneyTotal, discountMoney);
                        } else if (rechargeAccount.getType() == 2) {//促销卡
                            //计算卡付金额抵扣金额
                            discountMoney = BigDecimalUtils.div(rechargeAccountRequest.getSpendMoney(), BigDecimalUtils.div(rechargeAccountRequest.getDiscount(), hundredBd).setScale(2, BigDecimal.ROUND_HALF_UP)).setScale(2, BigDecimal.ROUND_HALF_UP);
                            BigDecimal giftDiscountMoney = BigDecimalUtils.div(rechargeAccountRequest.getGiftSpendMoney(), BigDecimalUtils.div(rechargeAccountRequest.getDiscountFreeAmount(), hundredBd).setScale(2, BigDecimal.ROUND_HALF_UP)).setScale(2, BigDecimal.ROUND_HALF_UP);
                            discountMoneyTotal = BigDecimalUtils.add(discountMoneyTotal, BigDecimalUtils.add(discountMoney, giftDiscountMoney));
                        } else {
                            //discountMoneyTotal=rechargeAccountRequest.getSpendMoney();
                            discountMoneyTotal = BigDecimalUtils.add(rechargeAccountRequest.getGiftSpendMoney(), rechargeAccountRequest.getSpendMoney());
                        }
                    }

                } else {//不打折
                    BigDecimal account = BigDecimal.valueOf(0);
                    for (RechargeAccountRequest rechargeAccountRequest : rechargeAccountList) {
                        if (null == rechargeAccountRequest.getGiftSpendMoney()) {
                            rechargeAccountRequest.setGiftSpendMoney(BigDecimalUtils.bigDecimal("0"));
                        }
                        RechargeAccount rechargeAccount = ssmRechargeAccountService.selectByPrimaryKey(rechargeAccountRequest.getId());

                        //判断账户剩余可用金额是否小于卡付金额
                        //判断账户剩余可用金额是否小于卡付金额
                        if (BigDecimalUtils.compareTo(rechargeAccount.getCardConsumeMoney(), rechargeAccountRequest.getSpendMoney()) == -1) {
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            throw new SmsException(ResponseCode.STORE_CASH_NOT_PERMISSION, "账户可消费金额小于卡付金额");
                        }
                        if (BigDecimalUtils.compareTo(rechargeAccount.getGiftConsumeMoney(), rechargeAccountRequest.getGiftSpendMoney()) == -1) {
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            throw new SmsException(ResponseCode.STORE_CASH_NOT_PERMISSION, "账户赠送可消费金额小于卡付金额");
                        }
                        account = account.add(rechargeAccountRequest.getSpendMoney().add(rechargeAccountRequest.getGiftSpendMoney()));
                    }
                    discountMoneyTotal = account;
                }
            }

            //疗程卡付判断
            if (null != serviceOrders.getCourseAccountId()) {
                CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(serviceOrders.getCourseAccountId());
                if (courseAccount.getCourseConsumeCount() < serviceOrders.getNumberTimes()) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new SmsException(ResponseCode.STORE_CASH_NOT_PERMISSION, "疗程账户可用次数小于消费次数");
                }
            } else if (BigDecimalUtils.compareTo(discountMoneyTotal, BigDecimalUtils.bigDecimal("0")) == 1 &&
                    BigDecimalUtils.compareTo(serviceOrders.getCollectionCashAmount(), BigDecimalUtils.bigDecimal("0")) == 0) {
                //折扣卡收银 允许使用容差 并且没有现付
                //不存在现付 总支付金额 = 总卡付支付金额 + 积分付
                BigDecimal amount = BigDecimalUtils.add(discountMoneyTotal, BigDecimal.valueOf(0), 2);
//                    BigDecimal amount = BigDecimalUtils.add(discountMoneyTotal, serviceProject.getCollectionIntegralAmount(), 2);
                //容差值< (成交金额-总支付金额) 即支付金额和成交金额不相等
                StoreParament balance = StoreParaUtils.getStorePara(serviceOrders.getStoreId(), Constant.balance);
                if (null != balance && BigDecimalUtils.compareTo(BigDecimalUtils.bigDecimal(balance.getParamentValue()), BigDecimalUtils.subtract(transactionPrice, amount).abs()) < 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new SmsException(ResponseCode.STORE_CASH_NOT_PERMISSION, "总支付金额和成交金额不相等");
                }
            } else {
                //存在现付
                //总支付金额 = 总卡付金额抵扣金额 + 总现付 + 积分付
                BigDecimal amount = BigDecimalUtils.add(BigDecimalUtils.add(discountMoneyTotal, serviceOrders.getCollectionCashAmount()), BigDecimal.valueOf(0));
                if (BigDecimalUtils.compareTo(amount, transactionPrice) != 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new SmsException(ResponseCode.STORE_CASH_NOT_PERMISSION, "总支付金额和成交金额不相等");
                }
            }
            if(serviceOrders.getCashNumber()==1){
                StoreMemberList storeMember = ssmStoreMemberService.selectByPrimaryKey(serviceOrders.getMemberId());

                //查询会员是否有积分
                storeParament = StoreParaUtils.getStorePara(serviceOrders.getStoreId(), Constant.member_integral);
                if ("1".equals(storeParament.getParamentValue())) {
                    //查询消费金额兑换积分比例
                    StoreParament integralPara = StoreParaUtils.getStorePara(serviceOrders.getStoreId(), Constant.exp_money_by_integral);
                    String value[] = integralPara.getParamentValue().split(":");
                    //使用float类型 除法时能计算小数
                    float money = Integer.parseInt(value[0]);
                    float integral = Integer.parseInt(value[1]);
//            //使用积分支付 消费赠送积分需使用实际支付-积分金额计算  不使用积分支付 消费赠送积分使用
//            if (null != cashList.getIntegral()) {
//                if (cashListRequest.getIntegral() > 0) {
//                    cashList.setGiveIntegral(BigDecimalUtils.div(BigDecimalUtils.subtract(cashList.getCashAmount(), cashList.getCollectionIntegralAmount()), BigDecimalUtils.bigDecimal(String.valueOf(money / integral))).intValue());
//                } else {
//                    cashList.setGiveIntegral(BigDecimalUtils.div(cashList.getAmount(), BigDecimalUtils.bigDecimal(String.valueOf(money / integral))).intValue());
//                }
//            }
                    //如果使用积分支付将门店会员积分进行扣减  收银消费对会员积分进行增加
                    if (null != storeMember) {
                        if(null == cashListRequest.getIntegral()){
                            cashListRequest.setIntegral(0);
                        }
                        if (cashListRequest.getIntegral() > 0) {
                            serviceOrders.setGiveIntegral(BigDecimalUtils.div(BigDecimalUtils.subtract(serviceOrders.getCashAmount(), serviceOrders.getCollectionIntegralAmount()), BigDecimalUtils.bigDecimal(String.valueOf(money / integral))).intValue());
                            storeMember.setIntegral(storeMember.getIntegral() - cashListRequest.getIntegral() + serviceOrders.getGiveIntegral());
                        }else {
                            serviceOrders.setGiveIntegral(BigDecimalUtils.div(serviceOrders.getAmount(), BigDecimalUtils.bigDecimal(String.valueOf(money / integral))).intValue());
                            storeMember.setIntegral(storeMember.getIntegral() + serviceOrders.getGiveIntegral());
                        }
                    }
                }
            }


            int i = dao.addServiceOrders(serviceOrders);
            if(i>0) {
                a++;
                //充值卡付 扣减充值账户金额
                if (null != rechargeAccountList && rechargeAccountList.size() > 0) {
                    //计算扣减金额 并添加账户交易记录
                    list = ssmRechargeAccountService.subMoney(rechargeAccountList, serviceOrders, list);
//                ssmCashAccountSrevice.add(rechargeAccountList,cashList);
                }
                //疗程卡付 扣减疗程账户次数
                CourseAccount courseAccount = new CourseAccount();
                if (null != serviceOrders.getCourseAccountId()) {
                    courseAccount = ssmCourseAccountService.selectByPrimaryKey(serviceOrders.getCourseAccountId());
                    ssmCourseAccountService.subCount(courseAccount, serviceOrders.getNumberTimes(), 0);
                    //添加账户交易记录
                    AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(serviceOrders, courseAccount);
                    ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                    list.add(accountTradeRecord);
                }

                //回去1修改服务中的单据状态
                StoreSettlement storeSettlement = new StoreSettlement();
                storeSettlement.setId(id);
                StoreSettlement storeSettlement1 = ssmStoreSettlementService.selectByPrimaryKey(storeSettlement.getId());
                int i1 = ssmStoreSettlementService.deleteByPrimaryKey(storeSettlement1.getId());
                if(i1>0){
                    //检擦房间是否还有单据，没有就恢复房间空闲状态
                    storeSettlement.setId(null);
                    storeSettlement.setRoomHandId(storeSettlement1.getRoomHandId());
                    storeSettlement.setStoreId(storeSettlement1.getStoreId());
                    List<StoreSettlement> select = ssmStoreSettlementService.select(storeSettlement);
                    if(select.size()==0){
                        StoreRoomHand storeRoomHand = new StoreRoomHand();
                        storeRoomHand.setId(storeSettlement1.getRoomHandId());
                        StoreRoomHand storeRoomHand1 = ssmStoreRoomHandService.selectByPrimaryKey(storeRoomHand.getId());
                        storeRoomHand1.setState(0);
                        int i2 = ssmStoreRoomHandService.updateNotNull(storeRoomHand1);
                        if(i2>0){
                            StoreSettlement storeSettlement2 = new StoreSettlement();
                            storeSettlement2.setRoomId(storeSettlement1.getRoomId());
                            storeSettlement2.setStoreId(storeSettlement1.getStoreId());
                            List<StoreSettlement> select1 = ssmStoreSettlementService.select(storeSettlement2);
                            if(select1.size()==0){
                                StoreRoom storeRoom = new StoreRoom();
                                storeRoom.setId(storeSettlement1.getRoomId());
                                StoreRoom storeRoom1 = ssmStoreRoomService.selectByPrimaryKey(storeRoom.getId());
                                storeRoom1.setOnState(2);
                                int i3 = ssmStoreRoomService.updateNotNull(storeRoom1);
                                if(i3==0){
                                    throw new SmsException(ResponseCode.MSG,"更改房间空闲状态出错");
                                }
                            }
                        }else{
                            throw new SmsException(ResponseCode.MSG,"恢复房间手牌空闲状态出错");
                        }
                    }
                }else{
                    throw new SmsException(ResponseCode.MSG,"结算出错");
                }
            }else{
                throw new SmsException(ResponseCode.MSG,"结算出错");
            }
        }
        if (null != serviceOrdersRequest.get(0).getPayLists() && serviceOrdersRequest.get(0).getPayLists().size() > 0) {
            for (PayList payList : serviceOrdersRequest.get(0).getPayLists()) {
                payList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                payList.setDocId(docNum);
                payList.setType(Constant.doc_type_store_cash_room);
                payList.setStoreId(storeId);
            }
            ssmPayService.addPayList(serviceOrdersRequest.get(0).getPayLists());
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(List<ServiceOrdersRequest> serviceOrdersRequest,String phone) throws SmsException {
        int a=0;
        for (ServiceOrdersRequest ordersRequest : serviceOrdersRequest) {
            ServiceOrdersRequest serviceOrders = new ServiceOrdersRequest();
            serviceOrders.setId(ordersRequest.getId());
            serviceOrders.setDocDate(ordersRequest.getDocDate());
            ServiceOrders serviceOrders1 = dao.getDocNum(serviceOrders).get(0);
            if(null != ordersRequest.getTechnicianOneNumber()){
                serviceOrders1.setTechnicianOneNumber(ordersRequest.getTechnicianOneNumber());
                serviceOrders1.setServiceTechnicianOneStaffId(ordersRequest.getServiceTechnicianOneStaffId());
                serviceOrders1.setServiceTechnicianOneStaffName(ordersRequest.getServiceTechnicianOneStaffName());
                serviceOrders1.setServiceTechnicianOneIdentityCard(ordersRequest.getServiceTechnicianOneIdentityCard());

            }else{
                serviceOrders1.setTechnicianOneNumber(null);
                serviceOrders1.setServiceTechnicianOneStaffId(null);
                serviceOrders1.setServiceTechnicianOneStaffName(null);
                serviceOrders1.setServiceTechnicianOneIdentityCard(null);

            }
            if(null != ordersRequest.getStaffId()){
                serviceOrders1.setStaffId(ordersRequest.getStaffId());
                serviceOrders1.setStaffName(ordersRequest.getStaffName());
                serviceOrders1.setStaffNum(ordersRequest.getStaffNum());
                serviceOrders1.setBrandNumber(ordersRequest.getBrandNumber());
            }else{
                serviceOrders1.setStaffId(null);
                serviceOrders1.setStaffName(null);
                serviceOrders1.setStaffNum(null);
                serviceOrders1.setBrandNumber(null);
            }
            int i = dao.cancelServiceOrders(serviceOrders1);
            if(i>0){
                a++;
            }
        }
        if(a==serviceOrdersRequest.size()){
            return a;
        }else{
            throw new SmsException(ResponseCode.MSG,"修改失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int cancel(ServiceOrdersRequest serviceOrdersRequest, String phone,Long storeId) throws SmsException {
        int i =0;
        List<ServiceOrders> docNum = dao.getDocNum(serviceOrdersRequest);
        for (ServiceOrders serviceOrders : docNum) {
            StoreParament storeParament = StoreParaUtils.getStorePara(serviceOrders.getStoreId(), Constant.service_ticke);
            int days = (int) DateUtils.getDayDiff(serviceOrders.getDocDate(), new Date());
            if(!"0".equals(storeParament.getParamentValue())) {
                if (Integer.parseInt(storeParament.getParamentValue()) < days) {
                    throw new SmsException(ResponseCode.CANCEL_NOT_PERMISSION, "单据超过允许作废时间");
                }
            }
            //修改疗程单据状态
            serviceOrders.setState(1);
            //如果使用积分支付 将积分返回
            StoreMemberList storeMember = ssmStoreMemberService.selectByPrimaryKey(serviceOrders.getMemberId());
            //查询会员是否有积分
            StoreParament parament = StoreParaUtils.getStorePara(serviceOrders.getStoreId(), Constant.member_integral);
            if ("1".equals(parament.getParamentValue())) {
                if (null != storeMember) {
                    if (null != serviceOrders.getIntegral() && 0 != serviceOrders.getIntegral()) {
                        storeMember.setIntegral(storeMember.getIntegral() + serviceOrders.getIntegral() - serviceOrders.getGiveIntegral());
                    }else {
                        storeMember.setIntegral(storeMember.getIntegral() - serviceOrders.getGiveIntegral());
                    }
                    ssmStoreMemberService.updateByPrimaryKey(storeMember);
                }
            }
            AccountTradeRecordRequest accountTradeRecord1 = new AccountTradeRecordRequest();
            accountTradeRecord1.setDocId(serviceOrders.getId());
            accountTradeRecord1.setInputDate(serviceOrders.getInputDate());
            List<AccountTradeRecord> accountTradeRecords = ssmAccountTradeRecordService.selectList(accountTradeRecord1);
            List<AccountTradeRecord> recharge_consume = accountTradeRecords.stream().filter(accountTradeRecord -> accountTradeRecord.getAccountType().equals("recharge_consume_room")).collect(Collectors.toList());
            List<AccountTradeRecord> project_consume = accountTradeRecords.stream().filter(accountTradeRecord -> accountTradeRecord.getAccountType().equals("project_consume_room")).collect(Collectors.toList());
            List<AccountTradeRecord> cash = accountTradeRecords.stream().filter(accountTradeRecord -> accountTradeRecord.getAccountType().equals("cash_room")).collect(Collectors.toList());
            if(recharge_consume.size()>0){
                List<RechargeAccountRequest> rechargeAccountRequestList = new ArrayList<>();
                for (AccountTradeRecord accountTradeRecord : recharge_consume) {
                    RechargeAccount rechargeAccount = new RechargeAccount();
                    rechargeAccount.setId(accountTradeRecord.getAccountId());
                    RechargeAccount rechargeAccount1 = ssmRechargeAccountService.selectByPrimaryKey(rechargeAccount.getId());
                    RechargeAccountRequest rechargeAccountRequestList1 = new RechargeAccountRequest();
                    BeanUtils.copyProperties(rechargeAccount1,rechargeAccountRequestList1);
                    rechargeAccountRequestList.add(rechargeAccountRequestList1);
                }
                ssmRechargeAccountService.addMoney(rechargeAccountRequestList, serviceOrders);

            }
            if(project_consume.size()>0){
                CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(project_consume.get(0).getAccountId());
                courseAccount = ssmCourseAccountService.addCount(courseAccount, serviceOrders.getNumberTimes());

                AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(serviceOrders, courseAccount);
                accountTradeRecord.setOrderStatu(1);
                ssmAccountTradeRecordService.addRecord(accountTradeRecord);
            }
            if(cash.size()>0){
                if (serviceOrders.getCollectionCashAmount().compareTo(BigDecimalUtils.bigDecimal("0"))==1 && recharge_consume.size() == 0 && null == serviceOrders.getCourseAccountId()) {
                    //添加账户交易记录
                    AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(serviceOrders, null);
                    accountTradeRecord.setOrderStatu(1);
                    ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                }
            }

            //设置作废人信息
            if (redisClient.hasKey(getStaffKey(phone))){
                StaffResponse staffResponse = redisClient.get(getStaffKey(phone));
                serviceOrders.setUpdateId(staffResponse.getId());
                serviceOrders.setUpdateBy(staffResponse.getStaffName());
                serviceOrders.setUpdateDate(new Date());
            }
            Set<String> keys = redisClient.keys(getStaffKey(phone) + "*");
            //从redis查询 设置作废人信息 app使用
            if (keys.size() > 0){
                String key =  new ArrayList<>(keys).get(0);
                StaffResponse staffResponse = redisClient.get(key);
                serviceOrders.setUpdateId(staffResponse.getId());
                serviceOrders.setUpdateBy(staffResponse.getStaffName());
                serviceOrders.setUpdateDate(new Date());
            }
            try {
                i = dao.cancelServiceOrders(serviceOrders);
            }catch (Exception e){
                log.error("SsmCashServiceImpl.cancel:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            //将评价单进行删除操作
            MemberCs memberCs = new MemberCs();
            memberCs.setDocId(serviceOrders.getId());
            ssmMemberCsService.delete(memberCs);
        }
        return 1;
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public int addServiceOrders(ServiceOrders serviceOrders) throws SmsException {
        int i = 0;
        try {
            i = dao.addServiceOrders(serviceOrders);
        }catch (Exception e){
            log.error("SsmCashServiceImpl.addCashList:",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return i;
    }

    @Override
    public List<ServiceOrdersResponse> selectList(Long storeId, String dateStr, Date date) throws SmsException, ParseException {
        ServiceOrdersRequest serviceOrdersRequest = new ServiceOrdersRequest();
        serviceOrdersRequest.setStoreId(storeId);
        serviceOrdersRequest.setDateStr(dateStr);
        serviceOrdersRequest.setDocDate(date);
        serviceOrdersRequest.setDocState(0);
        //查出门店信息 by storeId
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(serviceOrdersRequest.getStoreId());
        //校验门店注册时间 时间之前的数据不允许查看
        if (DateUtils.compare(DateUtils.YMParse(DateUtils.YMFormat(baseStore.getFunderDate())), date) < 0){
            throw new SmsException(ResponseCode.NO_DATA);
        }
        List<ServiceOrdersResponse> listResponses = new ArrayList<>();
        List<ServiceOrders> cashLists =  dao.selectPage2(serviceOrdersRequest);
        for (ServiceOrders cashList : cashLists) {
            ServiceOrdersResponse serviceOrdersResponse = new ServiceOrdersResponse();
            BeanUtils.copyProperties(cashList,serviceOrdersResponse);
            //判断是否是疗程卡付
            List<AchiCommEntity> achiCommLists = getAchiCommLists(cashList);


            for (AchiCommEntity entity : achiCommLists) {
                entity.setDocId(cashList.getId());
                if(cashList.getSettlementNum().equals(entity.getDocNum())){
                    entity.setProjectId(cashList.getProjectNum());
                    //entity.setMemberNum(cashList.getProjectNum());
                    if(null == entity.getMemberName()){
                        entity.setMemberName(cashList.getMemberName());
                    }
                    if(null == entity.getMoney()){
                        entity.setMoney(cashList.getPriceMember());
                    }


                }
            }
            serviceOrdersResponse.setAchiCommEntities(achiCommLists);
            listResponses.add(serviceOrdersResponse);
        }
        return listResponses;
    }

    /**
     * 充值卡和现金支付
     * 业绩暂时默认百分之一百（全部添加到现付业绩里面）
     * 提成点为>1=固定金额
     * @param cashList
     * @return
     */
    public List<AchiCommEntity> getAchiCommLists(ServiceOrders cashList){
        BigDecimal GDtotalMeony = cashList.getCollectionCashAmount().add(cashList.getCollectionRechargeAmount());
        List<AchiCommEntity> entities = new ArrayList<>();
        if(null != cashList.getServiceTechnicianOneStaffId()){
            if(cashList.getIsClock()==1){ //点钟
                AchiCommEntity achiCommEntity = new AchiCommEntity();
                achiCommEntity.setMoney(GDtotalMeony);
//                achiCommEntity.setMoney(cashList.getCashAmount());
                achiCommEntity.setMemberNum(String.valueOf(cashList.getMemberId()));
                achiCommEntity.setMemberName(cashList.getMemberName());
                achiCommEntity.setProjectId(String.valueOf(cashList.getProjectId()));

                achiCommEntity.setDocNum(cashList.getSettlementNum());
                achiCommEntity.setDocType(Constant.doc_type_store_cash_room);
                achiCommEntity.setDocDate(cashList.getDocDate());
                achiCommEntity.setTradeName(cashList.getProjectName());
                achiCommEntity.setBrandNumber(cashList.getTechnicianOneNumber());
                achiCommEntity.setSaleStaffId(cashList.getServiceTechnicianOneStaffId());
                achiCommEntity.setSaleStaffName(cashList.getServiceTechnicianOneStaffName());
                achiCommEntity.setSaleIdentityCard(cashList.getServiceTechnicianOneIdentityCard());
                achiCommEntity.setSaleRatio(BigDecimal.valueOf(100));
                achiCommEntity.setCardAchi(cashList.getCollectionRechargeAmount());
                achiCommEntity.setCashAchi(cashList.getCollectionCashAmount());

                if(cashList.getCollectionCashAmount().compareTo(BigDecimal.valueOf(1))==1 &&cashList.getCollectionRechargeAmount().compareTo(BigDecimal.valueOf(1))==1 ){
                    if(cashList.getCardClockComm().compareTo(BigDecimal.valueOf(1))==1 && cashList.getClockComm().compareTo(BigDecimal.valueOf(1))!=1){//都是固定提成
//                        卡付提成
                        BigDecimal cardcomm = cashList.getCardClockComm().divide(cashList.getCardClockComm().add(cashList.getClockComm()));
                        //现付提成
                        BigDecimal cashcomm = cashList.getClockComm().divide(cashList.getCardClockComm().add(cashList.getClockComm()));
                        achiCommEntity.setCardComm(cardcomm);
                        achiCommEntity.setCashComm(cashcomm);
                    }else{
                        if(cashList.getCardClockComm().compareTo(BigDecimal.valueOf(0))!=0) {
                            if(cashList.getCollectionRechargeAmount().compareTo(BigDecimal.valueOf(1))==1){
                                //计算卡付提成
                                if(cashList.getCardClockComm().compareTo(BigDecimal.valueOf(1))==1){ //固定金额
                                    achiCommEntity.setCardComm(cashList.getCardClockComm());
                                }else{
                                    achiCommEntity.setCardComm(cashList.getCollectionRechargeAmount().multiply(cashList.getCardClockComm()));
                                }

                            }
                        }
                        if(cashList.getClockComm().compareTo(BigDecimal.valueOf(0))!=0){
                            if(cashList.getCollectionCashAmount().compareTo(BigDecimal.valueOf(1))==1){
                                //计算现付
                                if(cashList.getClockComm().compareTo(BigDecimal.valueOf(1))==1){ //固定金额
                                    achiCommEntity.setCashComm(cashList.getClockComm());
                                }else{
                                    achiCommEntity.setCashComm(cashList.getCollectionCashAmount().multiply(cashList.getClockComm()));
                                }
                            }
                        }
                    }
                }else{
                    if(cashList.getCardClockComm().compareTo(BigDecimal.valueOf(0))!=0) {
                        if(cashList.getCollectionRechargeAmount().compareTo(BigDecimal.valueOf(1))==1){
                            //计算卡付提成
                            if(cashList.getCardClockComm().compareTo(BigDecimal.valueOf(1))==1){ //固定金额
                                achiCommEntity.setCardComm(cashList.getCardClockComm());
                            }else{
                                achiCommEntity.setCardComm(cashList.getCollectionRechargeAmount().multiply(cashList.getCardClockComm()));
                            }

                        }
                    }
                    if(cashList.getClockComm().compareTo(BigDecimal.valueOf(0))!=0){
                        if(cashList.getCollectionCashAmount().compareTo(BigDecimal.valueOf(1))==1){
                            //计算现付
                            if(cashList.getClockComm().compareTo(BigDecimal.valueOf(1))==1){ //固定金额
                                achiCommEntity.setCashComm(cashList.getClockComm());
                            }else{
                                achiCommEntity.setCashComm(cashList.getCollectionCashAmount().multiply(cashList.getClockComm()));
                            }
                        }
                    }

                }
                if(null == achiCommEntity.getCashAchi()){
                    achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCardAchi() ){
                    achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCashComm()){
                    achiCommEntity.setCashComm(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCardComm()){
                    achiCommEntity.setCardComm(BigDecimal.valueOf(0));
                }
                achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
                achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));
                entities.add(achiCommEntity);
            }else{//轮钟
                AchiCommEntity achiCommEntity = new AchiCommEntity();
                achiCommEntity.setMoney(GDtotalMeony);
//                achiCommEntity.setMoney(cashList.getCashAmount());
                achiCommEntity.setMemberNum(String.valueOf(cashList.getMemberId()));
                achiCommEntity.setMemberName(cashList.getMemberName());
                achiCommEntity.setProjectId(String.valueOf(cashList.getProjectId()));

                achiCommEntity.setDocNum(cashList.getSettlementNum());
                achiCommEntity.setDocType(Constant.doc_type_store_cash_room);
                achiCommEntity.setDocDate(cashList.getDocDate());
                achiCommEntity.setTradeName(cashList.getProjectName());
                achiCommEntity.setBrandNumber(cashList.getTechnicianOneNumber());
                achiCommEntity.setSaleStaffId(cashList.getServiceTechnicianOneStaffId());
                achiCommEntity.setSaleStaffName(cashList.getServiceTechnicianOneStaffName());
                achiCommEntity.setSaleIdentityCard(cashList.getServiceTechnicianOneIdentityCard());
                achiCommEntity.setSaleRatio(BigDecimal.valueOf(100));
                achiCommEntity.setCardAchi(cashList.getCollectionRechargeAmount());
                achiCommEntity.setCashAchi(cashList.getCollectionCashAmount());

                if(cashList.getCollectionCashAmount().compareTo(BigDecimal.valueOf(1))==1 &&cashList.getCollectionRechargeAmount().compareTo(BigDecimal.valueOf(1))==1 ){
                    if(cashList.getCardClockComm().compareTo(BigDecimal.valueOf(1))==1 && cashList.getClockComm().compareTo(BigDecimal.valueOf(1))!=1){//都是固定提成
//                        卡付提成
                        BigDecimal cardcomm = cashList.getCardClockComm().divide(cashList.getCardClockComm().add(cashList.getClockComm()));
                        //现付提成
                        BigDecimal cashcomm = cashList.getClockComm().divide(cashList.getCardClockComm().add(cashList.getClockComm()));
                        achiCommEntity.setCardComm(cardcomm);
                        achiCommEntity.setCashComm(cashcomm);
                    }else{
                        if(cashList.getCardClockComm().compareTo(BigDecimal.valueOf(0))!=0) {
                            if(cashList.getCollectionRechargeAmount().compareTo(BigDecimal.valueOf(1))==1){
                                //计算卡付提成
                                if(cashList.getCardClockComm().compareTo(BigDecimal.valueOf(1))==1){ //固定金额
                                    achiCommEntity.setCardComm(cashList.getCardClockComm());
                                }else{
                                    achiCommEntity.setCardComm(cashList.getCollectionRechargeAmount().multiply(cashList.getCardClockComm()));
                                }

                            }
                        }
                        if(cashList.getClockComm().compareTo(BigDecimal.valueOf(0))!=0){
                            if(cashList.getCollectionCashAmount().compareTo(BigDecimal.valueOf(1))==1){
                                //计算现付
                                if(cashList.getClockComm().compareTo(BigDecimal.valueOf(1))==1){ //固定金额
                                    achiCommEntity.setCashComm(cashList.getClockComm());
                                }else{
                                    achiCommEntity.setCashComm(cashList.getCollectionCashAmount().multiply(cashList.getClockComm()));
                                }
                            }
                        }
                    }
                }else{
                    if(cashList.getCardClockComm().compareTo(BigDecimal.valueOf(0))!=0) {
                        if(cashList.getCollectionRechargeAmount().compareTo(BigDecimal.valueOf(1))==1){
                            //计算卡付提成
                            if(cashList.getCardClockComm().compareTo(BigDecimal.valueOf(1))==1){ //固定金额
                                achiCommEntity.setCardComm(cashList.getCardClockComm());
                            }else{
                                achiCommEntity.setCardComm(cashList.getCollectionRechargeAmount().multiply(cashList.getCardClockComm()));
                            }

                        }
                    }
                    if(cashList.getClockComm().compareTo(BigDecimal.valueOf(0))!=0){
                        if(cashList.getCollectionCashAmount().compareTo(BigDecimal.valueOf(1))==1){
                            //计算现付
                            if(cashList.getClockComm().compareTo(BigDecimal.valueOf(1))==1){ //固定金额
                                achiCommEntity.setCashComm(cashList.getClockComm());
                            }else{
                                achiCommEntity.setCashComm(cashList.getCollectionCashAmount().multiply(cashList.getClockComm()));
                            }
                        }
                    }

                }
                if(null == achiCommEntity.getCashAchi()){
                    achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCardAchi() ){
                    achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCashComm()){
                    achiCommEntity.setCashComm(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCardComm()){
                    achiCommEntity.setCardComm(BigDecimal.valueOf(0));
                }
                achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
                achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));
                entities.add(achiCommEntity);
            }
        }
        if(null != cashList.getStaffId()){//存在推销人
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(GDtotalMeony);
//                achiCommEntity.setMoney(cashList.getCashAmount());
            achiCommEntity.setMemberNum(String.valueOf(cashList.getMemberId()));
            achiCommEntity.setMemberName(cashList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(cashList.getProjectId()));

            achiCommEntity.setDocNum(cashList.getSettlementNum());
            achiCommEntity.setDocType(Constant.doc_type_store_cash_room_market);
            achiCommEntity.setDocDate(cashList.getDocDate());
            achiCommEntity.setTradeName(cashList.getProjectName());
            achiCommEntity.setBrandNumber(cashList.getBrandNumber());
            achiCommEntity.setSaleStaffId(cashList.getStaffId());
            achiCommEntity.setSaleStaffName(cashList.getStaffName());
//            achiCommEntity.setSaleIdentityCard(cas());
            achiCommEntity.setSaleRatio(BigDecimal.valueOf(100));
            achiCommEntity.setCardAchi(cashList.getCollectionRechargeAmount());
            achiCommEntity.setCashAchi(cashList.getCollectionCashAmount());
            if(cashList.getCollectionCashAmount().compareTo(BigDecimal.valueOf(1))==1 &&cashList.getCollectionRechargeAmount().compareTo(BigDecimal.valueOf(1))==1 ){
                if(cashList.getCardClockComm().compareTo(BigDecimal.valueOf(1))==1 && cashList.getClockComm().compareTo(BigDecimal.valueOf(1))!=1){//都是固定提成
//                        卡付提成
                    BigDecimal cardcomm = cashList.getCardClockComm().divide(cashList.getCardClockComm().add(cashList.getClockComm()));
                    //现付提成
                    BigDecimal cashcomm = cashList.getClockComm().divide(cashList.getCardClockComm().add(cashList.getClockComm()));
                    achiCommEntity.setCardComm(cardcomm);
                    achiCommEntity.setCashComm(cashcomm);
                }else{
                    if(cashList.getCardClockComm().compareTo(BigDecimal.valueOf(0))!=0) {
                        if(cashList.getCollectionRechargeAmount().compareTo(BigDecimal.valueOf(1))==1){
                            //计算卡付提成
                            if(cashList.getCardClockComm().compareTo(BigDecimal.valueOf(1))==1){ //固定金额
                                achiCommEntity.setCardComm(cashList.getCardClockComm());
                            }else{
                                achiCommEntity.setCardComm(cashList.getCollectionRechargeAmount().multiply(cashList.getCardClockComm()));
                            }

                        }
                    }
                    if(cashList.getClockComm().compareTo(BigDecimal.valueOf(0))!=0){
                        if(cashList.getCollectionCashAmount().compareTo(BigDecimal.valueOf(1))==1){
                            //计算现付
                            if(cashList.getClockComm().compareTo(BigDecimal.valueOf(1))==1){ //固定金额
                                achiCommEntity.setCashComm(cashList.getClockComm());
                            }else{
                                achiCommEntity.setCashComm(cashList.getCollectionCashAmount().multiply(cashList.getClockComm()));
                            }
                        }
                    }
                }
            }else{
                if(cashList.getCardClockComm().compareTo(BigDecimal.valueOf(0))!=0) {
                    if(cashList.getCollectionRechargeAmount().compareTo(BigDecimal.valueOf(1))==1){
                        //计算卡付提成
                        if(cashList.getCardClockComm().compareTo(BigDecimal.valueOf(1))==1){ //固定金额
                            achiCommEntity.setCardComm(cashList.getCardClockComm());
                        }else{
                            achiCommEntity.setCardComm(cashList.getCollectionRechargeAmount().multiply(cashList.getCardClockComm()));
                        }

                    }
                }
                if(cashList.getClockComm().compareTo(BigDecimal.valueOf(0))!=0){
                    if(cashList.getCollectionCashAmount().compareTo(BigDecimal.valueOf(1))==1){
                        //计算现付
                        if(cashList.getClockComm().compareTo(BigDecimal.valueOf(1))==1){ //固定金额
                            achiCommEntity.setCashComm(cashList.getClockComm());
                        }else{
                            achiCommEntity.setCashComm(cashList.getCollectionCashAmount().multiply(cashList.getClockComm()));
                        }
                    }
                }

            }
            if(null == achiCommEntity.getCashAchi()){
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardAchi() ){
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCashComm()){
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardComm()){
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));
            entities.add(achiCommEntity);

        }
        return entities;
    }

    /*
     * 账户交易记录属性赋值 疗程付 现付
     * */
    public AccountTradeRecord setAccountTradeRecord(ServiceOrders serviceOrders,CourseAccount courseAccount){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(serviceOrders.getStoreId());
        accountTradeRecord.setStoreName(serviceOrders.getStoreName());
        accountTradeRecord.setMemberId(serviceOrders.getMemberId());
        accountTradeRecord.setMemberName(serviceOrders.getMemberName());
        accountTradeRecord.setMemberIdentity(serviceOrders.getMemberIdentityCard());
        accountTradeRecord.setMemberPhone(serviceOrders.getMobilePhone());
        //疗程卡付
        if (null != courseAccount) {
            accountTradeRecord.setAccountId(courseAccount.getId());
            accountTradeRecord.setAccountName(courseAccount.getCourseProjectName());
            if (serviceOrders.getState() == 0) {
                accountTradeRecord.setAccountType(Constant.account_type_project_consume_room);
                accountTradeRecord.setInputDate(serviceOrders.getDocDate());
                accountTradeRecord.setAccountSpendCount(serviceOrders.getNumberTimes());
                //花费金额为单次成交金额
                accountTradeRecord.setAccountSpendMoney(serviceOrders.getTransactionPrice());
            }else {
                accountTradeRecord.setAccountType(Constant.account_type_project_consume_cancel_room);
                accountTradeRecord.setInputDate(new Date());
                accountTradeRecord.setAccountInCount(serviceOrders.getNumberTimes());
                accountTradeRecord.setAccountInMoney(serviceOrders.getTransactionPrice());
            }
            accountTradeRecord.setAccountRestCount(courseAccount.getCourseRestCount());
            accountTradeRecord.setAccountConsumeCount(courseAccount.getCourseConsumeCount());
        }else {//现付
            if (serviceOrders.getState() == 0) {
                accountTradeRecord.setAccountType(Constant.account_type_store_cash_room);
                accountTradeRecord.setAccountSpendMoney(serviceOrders.getCollectionCashAmount());
                accountTradeRecord.setInputDate(serviceOrders.getDocDate());
            }else {
                accountTradeRecord.setAccountType(Constant.account_type_store_cash_cancel_room);
                accountTradeRecord.setAccountSpendMoney(serviceOrders.getCollectionCashAmount());
                accountTradeRecord.setInputDate(new Date());
            }
        }
        accountTradeRecord.setDocId(serviceOrders.getId());
        accountTradeRecord.setDocNum(serviceOrders.getSettlementNum());
        accountTradeRecord.setDocType(Constant.doc_type_store_cash_room);
        accountTradeRecord.setTradeId(serviceOrders.getProjectId());
        accountTradeRecord.setTradeName(serviceOrders.getProjectName());
        accountTradeRecord.setTradeMoney(serviceOrders.getTransactionPrice());
        accountTradeRecord.setTradeCount(serviceOrders.getNumberTimes());

        return accountTradeRecord;
    }

    public AccountTradeRecord setAccountTradeRecord(CourseAccount courseAccount, ServiceOrders cashList, RefundOrderList refundOrderList){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(refundOrderList.getStoreId());
        accountTradeRecord.setStoreName(refundOrderList.getStoreName());
        accountTradeRecord.setMemberId(refundOrderList.getMemberId());
        accountTradeRecord.setMemberName(refundOrderList.getMemberName());
        accountTradeRecord.setMemberIdentity(refundOrderList.getMemberIdentityCard());
        accountTradeRecord.setMemberPhone(refundOrderList.getMobilePhone());
        accountTradeRecord.setAccountId(courseAccount.getId());
        accountTradeRecord.setAccountName(courseAccount.getCourseProjectName());
        if (refundOrderList.getState() == 3){//审核
            accountTradeRecord.setAccountInCount(cashList.getNumberTimes());
            accountTradeRecord.setAccountType(Constant.account_type_refund_cash_audit_room);
            accountTradeRecord.setInputDate(refundOrderList.getAuditDate());
            accountTradeRecord.setInputBy(refundOrderList.getAuditBy());
            accountTradeRecord.setAccountInMoney(cashList.getAmount());
//            accountTradeRecord.setOrderStatu(0);
        }else if (refundOrderList.getState() == 4){//反审核
            accountTradeRecord.setAccountSpendCount(cashList.getNumberTimes());
            accountTradeRecord.setAccountType(Constant.account_type_refund_cash_unaudit_room);
            accountTradeRecord.setInputDate(new Date());
            accountTradeRecord.setInputBy(refundOrderList.getAuditBy());
            accountTradeRecord.setAccountSpendMoney(cashList.getAmount());
            accountTradeRecord.setOrderStatu(0);
        }
        accountTradeRecord.setDocId(refundOrderList.getId());
        accountTradeRecord.setDocNum(refundOrderList.getRefundNum());
        accountTradeRecord.setDocType(Constant.doc_type_refund_cash_room);
        accountTradeRecord.setTradeId(courseAccount.getCourseProjectId());
        accountTradeRecord.setTradeName(courseAccount.getCourseProjectName());
        accountTradeRecord.setTradeMoney(cashList.getAmount());
        accountTradeRecord.setTradeCount(cashList.getNumberTimes());
        accountTradeRecord.setPrice(cashList.getTransactionPrice());
        if (!"2".equals(courseAccount.getCourseType())) {
            accountTradeRecord.setAccountRestCount(courseAccount.getCourseRestCount());
            accountTradeRecord.setAccountConsumeCount(courseAccount.getCourseConsumeCount());
        }else {
            accountTradeRecord.setAccountGiftRestCount(courseAccount.getCourseRestCount());
            accountTradeRecord.setAccountGiftConsumeCount(courseAccount.getCourseConsumeCount());
        }

        accountTradeRecord.setCardMoney(cashList.getCollectionRechargeAmount());
        accountTradeRecord.setCashMoney(cashList.getCollectionCashAmount());
        return accountTradeRecord;
    }

    public String getStaffKey(String phone){
        return staffKey + phone;
    }

    public String getDocNum(ServiceOrdersRequest serviceOrdersRequest) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String ymdDate = format.format(new Date()).replace("-","");
        serviceOrdersRequest.setSelectDate(ymdDate);
        List<ServiceOrders> cashLists = dao.getDocNum(serviceOrdersRequest);
        String cashNum;
        String num;
        int mm = 0;
        if (cashLists != null && cashLists.size() > 0) {
            ServiceOrders cashList = cashLists.get(0);
            mm = Integer.parseInt(cashList.getSettlementNum().substring(8)) + 1;
            if (mm < 10){
                num = "000" + mm;
            }else if (mm < 100){
                num = "00" + mm;
            }else if (mm < 1000){
                num = "0" + mm;
            }else {
                num = String.valueOf(mm);
            }
            cashNum = ymdDate + num;

        }else {
            num = "0001" ;
            cashNum = ymdDate + num;
        }
        return cashNum;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int cancelRowOnly(RefundRoomCash refundCash, RefundOrderList refundOrderList) throws SmsException {
        int i = 0;
        //查询对应收银单
        ServiceOrdersRequest cashListRequest = new ServiceOrdersRequest();
        cashListRequest.setId(refundCash.getRoomCashId());
        cashListRequest.setDocDate(refundCash.getDocDate());
        ServiceOrders cashList = dao.one(cashListRequest);
        //账户添加
        if (null != cashList.getCourseAccountId()){//疗程卡付
            //添加疗程卡次数
            CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(cashList.getCourseAccountId());
            courseAccount = ssmCourseAccountService.addCount(courseAccount, cashList.getNumberTimes(),cashList.getAmount());
            //插入账户交易记录
            AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(courseAccount,cashList , refundOrderList);
            i = ssmAccountTradeRecordService.addRecord(accountTradeRecord);
        }
        if (null != cashList.getCollectionRechargeAmount() && BigDecimalUtils.compareTo(cashList.getCollectionRechargeAmount(), BigDecimalUtils.bigDecimal("0")) == 1){//充值卡付
            //添加充值卡金额
            CashAccountList cashAccount = new CashAccountList();
            cashAccount.setCashId(cashList.getId());
            List<CashAccountList> accountLists = ssmCashAccountSrevice.select(cashAccount);
            for (CashAccountList accountList : accountLists) {
                RechargeAccount rechargeAccount = ssmRechargeAccountService.addMoney(accountList,null);
                //插入账户交易记录
                AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(rechargeAccount, accountList, refundOrderList,cashList);
                i = ssmAccountTradeRecordService.addRecord(accountTradeRecord);
            }
        }
        if (null != cashList.getCollectionCashAmount() && BigDecimalUtils.compareTo(cashList.getCollectionCashAmount(), BigDecimalUtils.bigDecimal("0")) == 1){//现付
            //添加账户交易记录
            AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(refundOrderList, cashList);
            i = ssmAccountTradeRecordService.addRecord(accountTradeRecord);
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int restoreRowOnly(RefundRoomCash refundCash, RefundOrderList refundOrderList) throws SmsException {
        int i = 0;
        //查询对应收银单
        ServiceOrdersRequest cashListRequest = new ServiceOrdersRequest();
        cashListRequest.setId(refundCash.getRoomCashId());
        cashListRequest.setDocDate(refundCash.getDocDate());
        ServiceOrders cashList = dao.one(cashListRequest);
//        //修改疗程单据状态
//        cashList.setIsCancel(0);
//
//        StoreMemberList storeMember = ssmStoreMemberService.selectByPrimaryKey(cashList.getMemberId());
//        //查询会员是否有积分
//        StoreParament storeParament = StoreParaUtils.getStorePara(cashList.getStoreId(), Constant.member_integral);
//        if ("1".equals(storeParament.getParamentValue())) {
//            if (null != storeMember) {
//                //如果使用积分支付 将积分反算
//                if (null != cashList.getIntegral() && 0 != cashList.getIntegral()) {
//                    storeMember.setIntegral(storeMember.getIntegral() - cashList.getIntegral() + cashList.getGiveIntegral());
//                }else {
//                    storeMember.setIntegral(storeMember.getIntegral() + cashList.getGiveIntegral());
//                }
//                ssmStoreMemberService.updateByPrimaryKey(storeMember);
//            }
//        }
//        try {
//            i = dao.cancel(cashList);
//        }catch (Exception e){
//            log.error("SsmCashServiceImpl.restoreRowOnly:", e);
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
//        }

        //账户添加
        if (null != cashList.getCourseAccountId()){//疗程卡付
            //添加疗程卡次数
            CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(cashList.getCourseAccountId());
            courseAccount = ssmCourseAccountService.subCount(courseAccount, cashList.getNumberTimes(), 0,cashList.getAmount());
            //插入账户交易记录
            AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(courseAccount,cashList , refundOrderList);
            accountTradeRecord.setOrderStatu(2);
            accountTradeRecord.setInputBy(refundOrderList.getAuditBy());
            i = ssmAccountTradeRecordService.addRecord(accountTradeRecord);
        }
        if (null != cashList.getCollectionRechargeAmount() && BigDecimalUtils.compareTo(cashList.getCollectionRechargeAmount(), BigDecimalUtils.bigDecimal("0")) == 1){//充值卡付
            //添加充值卡金额
            CashAccountList cashAccount = new CashAccountList();
            cashAccount.setCashId(cashList.getId());
            List<CashAccountList> accountLists = ssmCashAccountSrevice.select(cashAccount);
            for (CashAccountList accountList : accountLists) {
                RechargeAccount rechargeAccount = ssmRechargeAccountService.subMoney(accountList,null);
                //插入账户交易记录
                AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(rechargeAccount, accountList, refundOrderList,cashList);
                accountTradeRecord.setOrderStatu(2);
                accountTradeRecord.setInputDate(new Date());
                accountTradeRecord.setInputBy(refundOrderList.getAuditBy());
                i = ssmAccountTradeRecordService.addRecord(accountTradeRecord);
            }
        }
        if (null != cashList.getCollectionCashAmount() && BigDecimalUtils.compareTo(cashList.getCollectionCashAmount(), BigDecimalUtils.bigDecimal("0")) == 1){//现付
            //添加账户交易记录
            AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(refundOrderList, cashList);
            accountTradeRecord.setInputDate(new Date());
            accountTradeRecord.setOrderStatu(2);
            accountTradeRecord.setInputBy(refundOrderList.getAuditBy());
            i = ssmAccountTradeRecordService.addRecord(accountTradeRecord);
        }
        return i;
    }

    public AccountTradeRecord setAccountTradeRecord(RechargeAccount rechargeAccount, CashAccountList accountList, RefundOrderList refundOrderList,ServiceOrders serviceOrders){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(refundOrderList.getStoreId());
        accountTradeRecord.setStoreName(refundOrderList.getStoreName());
        accountTradeRecord.setMemberId(refundOrderList.getMemberId());
        accountTradeRecord.setMemberName(refundOrderList.getMemberName());
        accountTradeRecord.setMemberIdentity(refundOrderList.getMemberIdentityCard());
        accountTradeRecord.setMemberPhone(refundOrderList.getMobilePhone());
        accountTradeRecord.setAccountId(rechargeAccount.getId());
        accountTradeRecord.setAccountName(rechargeAccount.getRechargeTypeName());
        if (refundOrderList.getState() == 3){//审核
            accountTradeRecord.setAccountInMoney(accountList.getCardPayMoney());
            //赠送卡花费金额置0
            accountTradeRecord.setAccountGiftSpendMoney(accountList.getGiftPayMoney());
            accountTradeRecord.setAccountType(Constant.account_type_refund_cash_audit_room);
            accountTradeRecord.setInputDate(new Date());
        }else if (refundOrderList.getState() == 4){//反审核
            accountTradeRecord.setAccountSpendMoney(accountList.getCardPayMoney());
            //赠送卡花费金额
            accountTradeRecord.setAccountGiftSpendMoney(accountList.getGiftPayMoney());
            accountTradeRecord.setAccountType(Constant.account_type_refund_cash_unaudit_room);
            accountTradeRecord.setInputDate(refundOrderList.getAuditDate());
        }
        accountTradeRecord.setDocId(refundOrderList.getId());
        accountTradeRecord.setDocNum(refundOrderList.getRefundNum());
        accountTradeRecord.setDocType(Constant.doc_type_refund_cash_room);
        accountTradeRecord.setTradeId(rechargeAccount.getRechargeTypeId());
        accountTradeRecord.setTradeName(rechargeAccount.getRechargeTypeName());
        accountTradeRecord.setTradeMoney(accountList.getCardPayMoney().add(accountList.getGiftPayMoney()));
        accountTradeRecord.setAccountRestMoney(rechargeAccount.getCardRestMoney());
        accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney());
        accountTradeRecord.setAccountGiftRestMoney(rechargeAccount.getCardGiftMoney());
        accountTradeRecord.setAccountGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        accountTradeRecord.setCardMoney(serviceOrders.getCollectionRechargeAmount());
        accountTradeRecord.setCashMoney(serviceOrders.getCollectionCashAmount());
        return accountTradeRecord;
    }

    public AccountTradeRecord setAccountTradeRecord(RefundOrderList refundOrderList, ServiceOrders cashList){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(refundOrderList.getStoreId());
        accountTradeRecord.setStoreName(refundOrderList.getStoreName());
        accountTradeRecord.setMemberId(refundOrderList.getMemberId());
        accountTradeRecord.setMemberName(refundOrderList.getMemberName());
        accountTradeRecord.setMemberIdentity(refundOrderList.getMemberIdentityCard());
        accountTradeRecord.setMemberPhone(refundOrderList.getMobilePhone());

        if (refundOrderList.getState() == 3){//审核
            accountTradeRecord.setAccountSpendMoney(cashList.getCollectionCashAmount());
            accountTradeRecord.setAccountType(Constant.account_type_refund_cash_audit_room);
            accountTradeRecord.setInputDate(new Date());
        }else if (refundOrderList.getState() == 4){//反审核
            accountTradeRecord.setAccountInMoney(cashList.getCollectionCashAmount());
            accountTradeRecord.setAccountType(Constant.account_type_refund_cash_unaudit_room);
            accountTradeRecord.setInputDate(refundOrderList.getAuditDate());
        }
        accountTradeRecord.setDocId(refundOrderList.getId());
        accountTradeRecord.setDocNum(refundOrderList.getRefundNum());
        accountTradeRecord.setDocType(Constant.doc_type_refund_cash_room);
        accountTradeRecord.setTradeId(cashList.getProjectId());
        accountTradeRecord.setTradeName(cashList.getProjectName());
        accountTradeRecord.setTradeMoney(cashList.getTransactionPrice());
        accountTradeRecord.setTradeCount(cashList.getNumberTimes());
        accountTradeRecord.setCardMoney(cashList.getCollectionRechargeAmount());
        accountTradeRecord.setCashMoney(cashList.getCollectionCashAmount());
        return accountTradeRecord;
    }
}
