package com.ssm.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.github.pagehelper.PageInfo;
import com.ssm.manage.response.GenericResponse;
import com.ssm.manage.response.PageResponse;
import com.ssm.manage.utils.SessionHelp;
import com.ssm.core.utils.BigDecimalUtils;
import com.ssm.core.utils.ChuangLanBeanSmsUtil;
import com.ssm.manage.entity.*;
import com.ssm.manage.excelEntity.ExcelCourseList;
import com.ssm.manage.query.*;
import com.ssm.manage.response.CourseListResponse;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Api(value="门店疗程controller",tags={"门店疗程相关接口"})
@RestController
@RequestMapping("/demay/ssm/course")
@Slf4j
public class SsmCourseController {
    @Autowired
    private SsmCourseService ssmCourseService;

    @Autowired
    private SsmProjectTypeService ssmProjectTypeService;

    @Autowired
    private ChuangLanBeanSmsUtil chuangLanBeanSmsUtil;

    @Autowired
    private SmsFixService smsFixService;
    @Autowired
    private SsmRechargeAccountService ssmRechargeAccountService;

    @Autowired
    private SsmAccountTradeRecordService ssmAccountTradeRecordService;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmStoreParaService ssmStoreParaService;
    @Autowired
    private SsmProjectService ssmProjectService;

    @Autowired
    SsmSalesmanService ssmSalesmanService;

    @Autowired
    SsmPayService ssmPayService;

    @ApiOperation(value = "分页查询疗程单  (门店端-疗程单-列表分页查询疗程单)",httpMethod = "POST",response = PageResponse.class)
    @RequestMapping("/page")
    public PageResponse selectPage(@RequestBody CourseListRequest courseListRequest, HttpSession session){
        PageResponse<CourseListResponse> pageResponse = new PageResponse<>();
        if(SessionHelp.getStoreId(session)==null){
            pageResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return pageResponse;
        }
        PageInfo<CourseListResponse> pageInfo = new PageInfo<>();
        Long storeId = SessionHelp.getStoreId(session);
        courseListRequest.setStoreId(storeId);
        try {
            pageInfo = ssmCourseService.selectPage(courseListRequest);
        }catch (SmsException e){
            pageResponse.setCodeAndMsg(e);
            return pageResponse;
        }catch (Exception e){
            log.error("SsmCourseController.selectPage:",e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }

    @ApiOperation(value = "分页查询疗程单  (门店端-疗程单-列表分页查询疗程单)",httpMethod = "POST",response = PageResponse.class)
    @RequestMapping("/pageNew")
    public PageResponse selectPageNew(@RequestBody CourseListRequest courseListRequest, HttpSession session){
        PageResponse<CourseListResponse> pageResponse = new PageResponse<>();
        PageInfo<CourseListResponse> pageInfo = new PageInfo<>();
        if(SessionHelp.getStoreId(session)==null){
            pageResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return pageResponse;
        }
        Long storeId = SessionHelp.getStoreId(session);
        List<Long> listStoreId=new ArrayList<>();
        if(null == courseListRequest.getStoreList()|| courseListRequest.getStoreList().size()==0){
            courseListRequest.setSelectType(1);
            courseListRequest.setStoreId(storeId);
            listStoreId.add(storeId);
            courseListRequest.setStoreList(listStoreId);
        }else{
            courseListRequest.setSelectType(0);
        }
        try {
            pageInfo = ssmCourseService.selectPageNew(courseListRequest);
        }catch (SmsException e){
            pageResponse.setCodeAndMsg(e);
            return pageResponse;
        }catch (Exception e){
            log.error("SsmCourseController.selectPage:",e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }

    @ApiOperation(value = "根据交易记录明细关联单据Id查询单据详细信息",httpMethod = "POST",response = PageResponse.class)
    @RequestMapping("/pageDetail")
    public PageResponse pageDetail(@RequestBody CourseListRequest courseListRequest, HttpSession session){
        PageResponse<CourseListResponse> pageResponse = new PageResponse<>();
        PageInfo<CourseListResponse> pageInfo = new PageInfo<>();
        if(SessionHelp.getStoreId(session)==null){
            pageResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return pageResponse;
        }
        try {
            pageInfo = ssmCourseService.pageDetail(courseListRequest);
        }catch (SmsException e){
            pageResponse.setCodeAndMsg(e);
            return pageResponse;
        }catch (Exception e){
            log.error("SsmCourseController.selectPage:",e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }

    @ApiOperation(value = "疗程单添加  (门店端-疗程单-疗程单添加)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/add")
    public GenericResponse add(@RequestBody CourseListRequest courseListRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        String storeName = SessionHelp.getStoreName(session);
        String staffPhone = SessionHelp.getLoginAccount(session);
        courseListRequest.setStoreId(storeId);
        courseListRequest.setStoreName(storeName);
        courseListRequest.setStaffPhone(staffPhone);
        courseListRequest.setSession(session);
        int i = 0;
        try {
            i = ssmCourseService.addCourse(courseListRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmCourseController.add:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0){
            //genericResponse.setCodeAndMsg(ResponseCode.OK);
            //发送短信
            BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(storeId);
            //设置短信账户 发送 否则不发送
            if (StringUtils.isNotBlank(baseStore.getSmsAccount()) && null != baseStore.getMessagingPlatform()) {
                try {
                    if(courseListRequest.getIsAddition()==1){
                        //chuangLanBeanSmsUtil.sendCourseSms(baseStore, courseListRequest.getMobilePhone(), courseListRequest.getProjectName(),courseListRequest.getAdditionDate());
                    }else {

                        chuangLanBeanSmsUtil.sendCourseSms(baseStore, courseListRequest.getMobilePhone(), courseListRequest.getProjectName());
                    }
//                    chuangLanBeanSmsUtil.sendSLCardUseSms(baseStore, courseListRequest.getMemberName(), courseListRequest.getMobilePhone(), courseListRequest.getProjectName(), courseListRequest.getNumberTimes());
                    genericResponse.setCodeAndMsg(ResponseCode.OK);
                } catch (IOException e) {
                    log.error("SsmCourseController.add:", e);
                } catch (SmsException e) {
                    genericResponse.setCodeAndMsg(ResponseCode.SMS_SEND_OK_EXCEPTION);
                    log.error("SsmCourseController.add:", e);
                }
            }else {
                genericResponse.setCodeAndMsg(ResponseCode.SMS_NO_OK);
            }

        }
        return genericResponse;
    }
    // todo 买单
    @ApiOperation(value = "多疗程添加  (门店端-疗程单-疗程多添加)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/addList")
//    @RequestMapping("/addListBySmsFix")
    public GenericResponse addList(@RequestBody CourseListRequestNew courseListRequestNew, HttpSession session) {
        //查询容差
        GenericResponse genericResponse = new GenericResponse();
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        Long storeId = SessionHelp.getStoreId(session);//265309505575694336L;//
        String storeName = SessionHelp.getStoreName(session);//"总店";//
        String staffPhone = SessionHelp.getLoginAccount(session);//"18070793360";//
        courseListRequestNew.setStoreId(storeId);
        courseListRequestNew.setStoreName(storeName);
        courseListRequestNew.setSession(session);
        StoreParament storeParament = new StoreParament();
        storeParament.setStoreId(storeId);
        storeParament.setParamentName("balance");
        storeParament = ssmStoreParaService.selectOne(storeParament);
        //容差，五毛钱
        BigDecimal balance = new BigDecimal(storeParament.getParamentValue());

        courseListRequestNew.setStaffPhone(staffPhone);
//        courseListRequest.setStoreId(storeId);
//        courseListRequest.setStoreName(storeName);
        //判断每个疗程的现付、卡付、欠款与成交价是否相同
        BigDecimal realAmount = BigDecimalUtils.bigDecimal("0");
        BigDecimal rechargeAmount = BigDecimalUtils.bigDecimal("0");
        BigDecimal payAmount = BigDecimalUtils.bigDecimal("0");
        BigDecimal debtAmount = BigDecimalUtils.bigDecimal("0");
        //欠款
        BigDecimal debtMoneyAmount = BigDecimalUtils.bigDecimal("0");
        List<CourseListVo> collect = courseListRequestNew.getCourseLists().stream().filter(item -> item.getProjctId() != null).collect(Collectors.toList());
        for (CourseListVo courseList : collect) {
            BigDecimal courseAmount = BigDecimalUtils.bigDecimal("0");
            if(courseList.getDebtMoney()!=null && courseList.getDebtMoney().compareTo(BigDecimalUtils.bigDecimal("0"))>=0){
                debtMoneyAmount = debtMoneyAmount.add(courseList.getDebtMoney());
            }
            courseAmount = courseAmount.add(courseList.getCollectionCashAmount()).add(courseList.getCollectionRechargeAmount()).add(courseList.getDebtMoney());
//            if(courseList.getAmount().subtract(courseAmount).compareTo(new BigDecimal("0.5"))==1){
//                genericResponse.setCodeAndMsg(ResponseCode.COURSE_NOT_PERMISSION, "总支付金额和成交金额不相等");
//                return genericResponse;
//            }
            courseAmount = courseAmount.setScale(2,BigDecimal.ROUND_HALF_UP);
            if(courseList.getAmount().compareTo(courseAmount)!=0) {
                if(courseList.getAmount().subtract(courseAmount).abs().compareTo(balance)>0){
                    genericResponse.setCodeAndMsg(ResponseCode.COURSE_NOT_PERMISSION, "总支付金额和成交金额不相等");
                    return genericResponse;
                }
            }
            payAmount = payAmount.add(courseList.getDebtMoney());
            debtAmount = debtAmount.add(courseList.getDebtAmount()==null?BigDecimalUtils.bigDecimal("0"):courseList.getDebtAmount());
            realAmount =  realAmount.add(courseAmount);
            rechargeAmount =  rechargeAmount.add(courseList.getCollectionRechargeAmount());
        }
        if(payAmount.compareTo(debtAmount)>0){
            genericResponse.setCodeAndMsg(ResponseCode.COURSE_NOT_PERMISSION, "欠款超过店铺最大欠款金额");
            return genericResponse;
        }

            //判断所有疗程的成交总额是否跟卡付和现付是否相同

        List<PayList> payLists = courseListRequestNew.getPayLists();
        for (PayList payList : payLists) {
            payAmount =  payAmount.add(payList.getPayMoney());
        }
        if(payAmount.add(rechargeAmount).compareTo(realAmount)!=0){
            if(payAmount.subtract(realAmount).abs().compareTo(balance)>0){
                genericResponse.setCodeAndMsg(ResponseCode.COURSE_NOT_PERMISSION, "总支付金额和成交金额不相等");
                return genericResponse;
            }
        }
        int i = 0;
            try {
                i += ssmCourseService.addCourse1(courseListRequestNew);
            }catch (SmsException e){
                genericResponse.setCodeAndMsg(e);
                return genericResponse;
            }catch (Exception e){
                log.error("SsmCourseController.add:",e);
                genericResponse.setCodeAndMsg(ResponseCode.FAILED);
                return genericResponse;
            }
            if(courseListRequestNew.getIsSendSms()==1){

                if (i > 0){
                    //genericResponse.setCodeAndMsg(ResponseCode.OK);
                    //发送短信
                    BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(storeId);
                    //设置短信账户 发送 否则不发送
                    if (StringUtils.isNotBlank(baseStore.getSmsAccount()) && null != baseStore.getMessagingPlatform()) {
                        try {
                            if(null != courseListRequestNew.getIsAddition() && courseListRequestNew.getIsAddition()==1){
                            }else {
                                String  projectName = "";
                                for (CourseListVo courseList : courseListRequestNew.getCourseLists()) {
                                    projectName=""+courseList.getProjectName()+"次数"+courseList.getNumberTimes()+"次，赠送次数0次。";
                                    chuangLanBeanSmsUtil.sendCourseSmsNew(baseStore, courseListRequestNew.getCourseLists().get(0).getMobilePhone(),projectName,courseListRequestNew.getCourseLists().get(0).getMemberName());
                                }
                            }
                            genericResponse.setCodeAndMsg(ResponseCode.OK);
                        } catch (IOException e) {
                            log.error("SsmCourseController.add:", e);
                        } catch (SmsException e) {
                            genericResponse.setCodeAndMsg(ResponseCode.SMS_SEND_OK_EXCEPTION);
                            log.error("SsmCourseController.add:", e);
                        }
                    }else {
                        genericResponse.setCodeAndMsg(ResponseCode.SMS_NO_OK);
                    }
                }
            }else {
                genericResponse.setCodeAndMsg(ResponseCode.OK);
            }

        return genericResponse;
    }

    /**
     * 短信测试
     * @param courseListRequestNew
     * @param session
     * @return
     */
    @ApiOperation(value = "多疗程添加  (门店端-疗程单-疗程多添加)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/addListBySmsFix")
//    @RequestMapping("/addList")
    public GenericResponse addListBySmsFix(@RequestBody CourseListRequestNew courseListRequestNew, HttpSession session) {
        //查询容差
        GenericResponse genericResponse = new GenericResponse();
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        Long storeId = SessionHelp.getStoreId(session);//265309505575694336L;//
        String storeName = SessionHelp.getStoreName(session);//"总店";//
        String staffPhone = SessionHelp.getLoginAccount(session);//"18070793360";//
        courseListRequestNew.setStoreId(storeId);
        courseListRequestNew.setStoreName(storeName);
        courseListRequestNew.setSession(session);
        StoreParament storeParament = new StoreParament();
        storeParament.setStoreId(storeId);
        storeParament.setParamentName("balance");
        storeParament = ssmStoreParaService.selectOne(storeParament);
        //容差，五毛钱
        BigDecimal balance = new BigDecimal(storeParament.getParamentValue());

        courseListRequestNew.setStaffPhone(staffPhone);
//        courseListRequest.setStoreId(storeId);
//        courseListRequest.setStoreName(storeName);
        //判断每个疗程的现付、卡付、欠款与成交价是否相同
        BigDecimal realAmount = BigDecimalUtils.bigDecimal("0");
        BigDecimal rechargeAmount = BigDecimalUtils.bigDecimal("0");
        BigDecimal payAmount = BigDecimalUtils.bigDecimal("0");
        BigDecimal debtAmount = BigDecimalUtils.bigDecimal("0");
        //欠款
        BigDecimal debtMoneyAmount = BigDecimalUtils.bigDecimal("0");
        List<CourseListVo> collect = courseListRequestNew.getCourseLists().stream().filter(item -> item.getProjctId() != null).collect(Collectors.toList());
        for (CourseListVo courseList : collect) {
            BigDecimal courseAmount = BigDecimalUtils.bigDecimal("0");
            if(courseList.getDebtMoney()!=null && courseList.getDebtMoney().compareTo(BigDecimalUtils.bigDecimal("0"))>=0){
                debtMoneyAmount = debtMoneyAmount.add(courseList.getDebtMoney());
            }
            courseAmount = courseAmount.add(courseList.getCollectionCashAmount()).add(courseList.getCollectionRechargeAmount()).add(courseList.getDebtMoney());
//            if(courseList.getAmount().subtract(courseAmount).compareTo(new BigDecimal("0.5"))==1){
//                genericResponse.setCodeAndMsg(ResponseCode.COURSE_NOT_PERMISSION, "总支付金额和成交金额不相等");
//                return genericResponse;
//            }
            courseAmount = courseAmount.setScale(2,BigDecimal.ROUND_HALF_UP);
            if(courseList.getAmount().compareTo(courseAmount)!=0) {
                if(courseList.getAmount().subtract(courseAmount).abs().compareTo(balance)>0){
                    genericResponse.setCodeAndMsg(ResponseCode.COURSE_NOT_PERMISSION, "总支付金额和成交金额不相等");
                    return genericResponse;
                }
            }
            payAmount = payAmount.add(courseList.getDebtMoney());
            debtAmount = debtAmount.add(courseList.getDebtAmount()==null?BigDecimalUtils.bigDecimal("0"):courseList.getDebtAmount());
            realAmount =  realAmount.add(courseAmount);
            rechargeAmount =  rechargeAmount.add(courseList.getCollectionRechargeAmount());
        }
        if(payAmount.compareTo(debtAmount)>0){
            genericResponse.setCodeAndMsg(ResponseCode.COURSE_NOT_PERMISSION, "欠款超过店铺最大欠款金额");
            return genericResponse;
        }

        //判断所有疗程的成交总额是否跟卡付和现付是否相同

        List<PayList> payLists = courseListRequestNew.getPayLists();
        for (PayList payList : payLists) {
            payAmount =  payAmount.add(payList.getPayMoney());
        }
        if(payAmount.add(rechargeAmount).compareTo(realAmount)!=0){
            if(payAmount.subtract(realAmount).abs().compareTo(balance)>0){
                genericResponse.setCodeAndMsg(ResponseCode.COURSE_NOT_PERMISSION, "总支付金额和成交金额不相等");
                return genericResponse;
            }
        }
        int i = 0;
        try {
            i += ssmCourseService.addCourse1(courseListRequestNew);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmCourseController.add:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if(courseListRequestNew.getIsSendSms()==1){

            if (i > 0){
                //genericResponse.setCodeAndMsg(ResponseCode.OK);
                //发送短信
                BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(storeId);
                //设置短信账户 发送 否则不发送
                if (StringUtils.isNotBlank(baseStore.getSmsAccount()) && null != baseStore.getMessagingPlatform()) {
                    try {
                        if(null != courseListRequestNew.getIsAddition() && courseListRequestNew.getIsAddition()==1){
                            //chuangLanBeanSmsUtil.sendCourseSms(baseStore, courseListRequest.getMobilePhone(), courseListRequest.getProjectName(),courseListRequest.getAdditionDate());
                        }else {
                            String  projectName = "";
                            SmsFix smsFix = new SmsFix();
                            if(baseStore.getParentId()==null){
                                smsFix.setStoreId(baseStore.getId());
                            }
                            else smsFix.setStoreId(baseStore.getParentId());
                            List<Integer> types = new ArrayList<>();
                            types.add(2);
                            smsFix.setTypes(types);
                            List<SmsFix> smsFixList = smsFixService.selectByTypeAndStoreId(smsFix);
                            if(smsFixList==null || smsFixList.size()==0){
                                genericResponse.setCodeAndMsg(ResponseCode.MSG,"疗程未配置短信模板!");
                                return genericResponse;
                            }
                            for (CourseListVo courseList : courseListRequestNew.getCourseLists()) {
                                projectName="【"+courseList.getProjectName()+"】次数"+courseList.getNumberTimes()+"次，赠送次数0次。";
                                chuangLanBeanSmsUtil.sendCourseSmsNewBySmsFix(baseStore, courseListRequestNew.getCourseLists().get(0).getMobilePhone(),courseList.getProjectName(),courseList.getNumberTimes().toString(),"0",courseListRequestNew.getCourseLists().get(0).getMemberName(),smsFixList.get(0));
                            }
//                                chuangLanBeanSmsUtil.sendCourseSms(baseStore, courseListRequestNew.getCourseLists().get(0).getMobilePhone(),projectName);
                        }
//                                                chuangLanBeanSmsUtil.sendSLCardUseSms(baseStore, courseListRequest.getMemberName(), courseListRequest.getMobilePhone(), courseListRequest.getProjectName(), courseListRequest.getNumberTimes());
                        genericResponse.setCodeAndMsg(ResponseCode.OK);
                    } catch (IOException e) {
                        log.error("SsmCourseController.add:", e);
                    } catch (SmsException e) {
                        genericResponse.setCodeAndMsg(ResponseCode.SMS_SEND_OK_EXCEPTION);
                        log.error("SsmCourseController.add:", e);
                    }
                }else {
                    genericResponse.setCodeAndMsg(ResponseCode.SMS_NO_OK);
                }

                //            }
            }
        }else {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }

        return genericResponse;
    }

    @ApiOperation(value = "疗程补单短信重发",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/retransmission")
    public GenericResponse retransmission(@RequestBody CourseListRequest courseListRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        String storeName = SessionHelp.getStoreName(session);
        String staffPhone = SessionHelp.getLoginAccount(session);
        courseListRequest.setStoreId(storeId);
        courseListRequest.setStoreName(storeName);
        courseListRequest.setStaffPhone(staffPhone);
        courseListRequest.setSession(session);
        //发送短信
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(storeId);
        //设置短信账户 发送 否则不发送
        if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
            try {
                //if(courseListRequest.getIsAddition()==1){
                String projectName = "";
                for (CourseListVo courseList : courseListRequest.getCourseLists()) {
                    projectName=""+courseList.getProjectName()+"次数"+courseList.getNumberTimes()+"次，赠送次数0次。";
                    chuangLanBeanSmsUtil.sendCourseSmsNew(baseStore, courseListRequest.getMobilePhone(),projectName,courseListRequest.getCourseLists().get(0).getMemberName());
                }
//                        chuangLanBeanSmsUtil.sendCourseSms(baseStore, courseListRequest.getMobilePhone(), courseListRequest.getProjectName(),courseListRequest.getAdditionDate());
                //}
                genericResponse.setCodeAndMsg(ResponseCode.OK);
            } catch (IOException e) {
                log.error("SsmCourseController.add:", e);
            } catch (SmsException e) {
                log.error("SsmCourseController.add:", e);
                genericResponse.setCodeAndMsg(e);
            }
        }
        return genericResponse;
    }

    @ApiOperation(value = "疗程补单短信重发",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/retransmissionNew")
    public GenericResponse retransmissionNew(@RequestBody CourseListRequest courseListRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        String storeName = SessionHelp.getStoreName(session);
        String staffPhone = SessionHelp.getLoginAccount(session);
        courseListRequest.setStoreId(storeId);
        courseListRequest.setStoreName(storeName);
        courseListRequest.setStaffPhone(staffPhone);
        courseListRequest.setSession(session);
        //发送短信
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(storeId);
        //设置短信账户 发送 否则不发送
        if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
            try {
                //if(courseListRequest.getIsAddition()==1){
                String projectName = "";
                for (CourseListVo courseList : courseListRequest.getCourseLists()) {
                    SmsFix smsFix = new SmsFix();
                    if(baseStore.getParentId()==null){
                        smsFix.setStoreId(baseStore.getId());
                    }
                    else smsFix.setStoreId(baseStore.getParentId());
                    List<Integer> types = new ArrayList<>();
                    types.add(2);
                    smsFix.setTypes(types);
                    List<SmsFix> smsFixList = smsFixService.selectByTypeAndStoreId(smsFix);
                    if(smsFixList==null || smsFixList.size()==0){
                        genericResponse.setCodeAndMsg(ResponseCode.MSG,"疗程未配置短信模板!");
                        return genericResponse;
                    }
                        chuangLanBeanSmsUtil.sendCourseSmsNewBySmsFix(baseStore, courseListRequest.getMobilePhone(),courseList.getProjectName(),courseList.getNumberTimes().toString(),"0",courseListRequest.getCourseLists().get(0).getMemberName(),smsFixList.get(0));
//                    projectName="【"+courseList.getProjectName()+"】次数"+courseList.getNumberTimes()+"次，赠送次数0次。";
//                    chuangLanBeanSmsUtil.sendCourseSmsNew(baseStore, courseListRequest.getMobilePhone(),projectName,courseListRequest.getCourseLists().get(0).getMemberName());
                }
//                        chuangLanBeanSmsUtil.sendCourseSms(baseStore, courseListRequest.getMobilePhone(), courseListRequest.getProjectName(),courseListRequest.getAdditionDate());
                //}
                genericResponse.setCodeAndMsg(ResponseCode.OK);
            } catch (IOException e) {
                log.error("SsmCourseController.add:", e);
            } catch (SmsException e) {
                log.error("SsmCourseController.add:", e);
                genericResponse.setCodeAndMsg(e);
            }
        }
        return genericResponse;
    }


    @ApiOperation(value = "疗程单详情  (门店端-疗程单-疗程单作废)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/selectCourseOne")
    public GenericResponse selectCourseOne(@RequestBody CourseListRequest courseListRequest){
        GenericResponse genericResponse = new GenericResponse();
        try {
            CourseVo courseVo = ssmCourseService.selectCourseOne(courseListRequest);
            genericResponse.setData(courseVo);
        }catch (Exception e){
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }
    @ApiOperation(value = "疗程单详情  (异常单)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/selectCourseOneByError")
    public GenericResponse selectCourseOneByError(@RequestBody CourseListRequest courseListRequest){
        GenericResponse genericResponse = new GenericResponse();
        try {
            CourseVo courseVo = ssmCourseService.selectCourseOneByError(courseListRequest);
            genericResponse.setData(courseVo);
        }catch (Exception e){
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }

    @ApiOperation(value = "疗程单作废  (门店端-疗程单-疗程单作废)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/cancel")
    @Transactional(rollbackFor = Exception.class)
    public GenericResponse cancel(@RequestBody CourseListRequest courseListRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        CourseList courseList = new CourseList();
        courseList.setCourseReatmentNum(courseListRequest.getCourseReatmentNum());
        courseList.setDate(courseListRequest.getDate());
        List<CourseList> courseLists = ssmCourseService.selectList(courseList);
        int i = 0;
        for (CourseList list : courseLists) {
            Long storeId = SessionHelp.getStoreId(session);
            BeanUtils.copyProperties(list,courseListRequest);
            String storeName = SessionHelp.getStoreName(session);
            String staffPhone = SessionHelp.getLoginAccount(session);
            courseListRequest.setStoreId(storeId);
            courseListRequest.setStoreName(storeName);
            courseListRequest.setStaffPhone(staffPhone);
            try {
                i += ssmCourseService.cancel(courseListRequest);
            }catch (SmsException e){
                genericResponse.setCodeAndMsg(e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return genericResponse;
            }catch (Exception e){
                log.error("SsmCourseController.cancel:",e);
                genericResponse.setCodeAndMsg(ResponseCode.FAILED);
                return genericResponse;
            }
            if (i > 0){
                genericResponse.setCodeAndMsg(ResponseCode.OK);
            }
        }
        return genericResponse;
    }

    @ApiOperation(value = "疗程单修改业务员  (门店端-疗程单-疗程单修改业务员)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/updateStaff")
    public GenericResponse updateStaff(@RequestBody CourseListRequest courseListRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        String storeName = SessionHelp.getStoreName(session);
        String staffPhone = SessionHelp.getLoginAccount(session);
        courseListRequest.setStoreId(storeId);
        courseListRequest.setStoreName(storeName);
        courseListRequest.setStaffPhone(staffPhone);
        courseListRequest.setSession(session);
        int i = 0;
        try {
            i = ssmCourseService.updateStaff(courseListRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmCourseController.updateStaff:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0){
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }





    @ApiOperation(value = "单据导出", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/courseList/exportachis")
    public void exportachis(@RequestBody CourseListRequest courseListRequest, HttpSession session) {
        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        ExcelWriter excelWriter = null;
        OutputStream out = null;
//        courseListRequest.setStoreId(SessionHelp.getStoreId(session));
        try {
            String fileName = "projectType";
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + ".xlsx");
            out = response.getOutputStream();
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/courseList.xlsx");
//            BeanUtils.copyProperties(projectTypeRequest, baseProjectType);
            List<ExcelCourseList> excelBaseProjectTypeList = new ArrayList<>();
            List<CourseList> list = ssmCourseService.selectList(courseListRequest);
            AccountTradeRecordRequest accountTradeRecordRequest = new AccountTradeRecordRequest();
            accountTradeRecordRequest.setInputDate(courseListRequest.getDate());
            accountTradeRecordRequest.setStoreIds(courseListRequest.getStoreIds());
            accountTradeRecordRequest.setDocType("card_use");
            BigDecimal hundred = new BigDecimal("100");
            List<AccountTradeRecord> accountTradeRecordList = ssmAccountTradeRecordService.selectListByMonthly(accountTradeRecordRequest);
            //查询充值账户
            List<Long> collect1 = accountTradeRecordList.stream().map(item -> item.getAccountId()).collect(Collectors.toList());
            List<RechargeAccount>  rechargeAccountList = ssmRechargeAccountService.selectByIds(collect1);
            if(list!=null) {
//            salesmen = ssmSalesmanService.selectList(salesman);
                //所有门店
                List<BaseStore> select = ssmBaseStoreService.select(null);
                //所有项目id
                List<Long> projectIds = list.stream().filter(courseList -> courseList.getProjctId() != null).map(CourseList::getProjctId).collect(Collectors.toList());
                List<BaseProject> projectList = ssmProjectService.selectList(projectIds);
                //所有单据号
                List<String> courseNums = list.stream().map(CourseList::getCourseReatmentNum).collect(Collectors.toList());
//                List<PayList> select1 = ssmPayService.select(null);
                List<PayList> payListList = ssmPayService.selectList(courseNums);
                //查询管理层和高管
                List<Long> courseIds = list.stream().map(CourseList::getId).collect(Collectors.toList());
                List<Salesman> salesmanList = ssmSalesmanService.selectList(courseIds);
                for (CourseList executives : list) {
                    ExcelCourseList excelBaseProjectType = new ExcelCourseList();
                    BeanUtils.copyProperties(executives, excelBaseProjectType);
                    excelBaseProjectType.setPayType("");
                    excelBaseProjectType.setPayType("");
                    //设置充值卡支付的账号和金额
                    List<AccountTradeRecord> collect = accountTradeRecordList.stream().filter(item ->
                            (item.getDocId() == executives.getId() || item.getDocId().toString().equals(executives.getId().toString()))
                                    && (item.getOrderStatu() == null || item.getOrderStatu()==0)&&item.getAccountType().equals("recharge_consume")).collect(Collectors.toList());
                    StringBuilder rechargePay = new StringBuilder("");

                    if(collect!=null && collect.size()>0){
                        for (AccountTradeRecord accountTradeRecord : collect) {
                            for (RechargeAccount rechargeAccount : rechargeAccountList) {
                                if(accountTradeRecord.getAccountId()==rechargeAccount.getId()
                                        || accountTradeRecord.getAccountId().toString().equals(rechargeAccount.getId().toString())){
                                    rechargePay = rechargePay.append(rechargeAccount.getRechargeTypeNum() +"-"+ accountTradeRecord.getAccountName()+"-通用金额支付："
                                            +accountTradeRecord.getAccountSpendMoney()+"元-赠送金额支付："+accountTradeRecord.getAccountGiftSpendMoney()+"元\r\n");
                                }
                            }
                        }
                    }
                    excelBaseProjectType.setRechargePay(rechargePay.toString());
                    //设置项目编码
                    BigDecimal coopAchi = BigDecimal.ZERO;
                    if (executives.getProjctId() != null) {
                        for (BaseProject baseProject : projectList) {
                            if (executives.getProjctId() == baseProject.getId() || executives.getProjctId().equals(baseProject.getId())) {
                                excelBaseProjectType.setProjectNum(baseProject.getProjectNum());
                                if(baseProject.getIsCooperation()!=null&&baseProject.getIsCooperation()==1){
                                    excelBaseProjectType.setIsCoop("是");
                                    if(baseProject.getSmokeCommissionWay()!=null && baseProject.getSmokeCommissionWay()==1){
                                        excelBaseProjectType.setChouYong("比例-"+baseProject.getBrokerage()==null?"0%": baseProject.getBrokerage().setScale(2) +"%");
                                            coopAchi = excelBaseProjectType.getCollectionCashAmount().multiply(excelBaseProjectType.getBrokerage()).divide(hundred,4,BigDecimal.ROUND_HALF_UP);
                                    }

                                    else if(baseProject.getSmokeCommissionWay()!=null && baseProject.getSmokeCommissionWay()==0) {
                                        excelBaseProjectType.setChouYong("固定-"+baseProject.getBrokerage()==null?"0元": baseProject.getBrokerage().setScale(2) +"元");
                                        coopAchi =  excelBaseProjectType.getBrokerage().divide(excelBaseProjectType.getAmount(),4,BigDecimal.ROUND_HALF_UP).multiply(excelBaseProjectType.getCollectionCashAmount());
                                    }
                                }else
                                    excelBaseProjectType.setIsCoop("否");
                            }
                        }
                    }
                    if (excelBaseProjectType.getIsCancel() == 0) {
                        excelBaseProjectType.setIsCancelNew("正常");
                    } else {
                        excelBaseProjectType.setIsCancelNew("作废");
                    }
                    //设置门店编码
                    for (BaseStore baseStore : select) {
                        if (baseStore.getId() == excelBaseProjectType.getStoreId() || baseStore.getId().equals(excelBaseProjectType.getStoreId())) {
                            excelBaseProjectType.setStoreNum(baseStore.getStoreNum());
                        }
                    }
                    //设置支付方式
                    for (PayList payList : payListList) {
                        if (payList.getDocId().equals(executives.getCourseReatmentNum())) {
                            excelBaseProjectType.setPayType(excelBaseProjectType.getPayType() + "-" + payList.getPayName() + ":" + payList.getPayMoney() + "元-");
                        }
                    }
                    //设置高管和管理层
                    List<Salesman> guanliceng = salesmanList.stream().filter(item -> {
//                    System.out.println(item.getOrderId().equals(executives.getId().toString()));
//                    System.out.println(item.getStaffType() == 1 || item.getStaffType().equals("1"));
                                if (item.getOrderId().equals(executives.getId().toString()) && (item.getStaffType() == 1 || item.getStaffType().toString().equals("1"))) {
                                    return true;
                                }
                                return false;
                            }
                    ).collect(Collectors.toList());
                    List<Salesman> gaoguan = salesmanList.stream().filter(item -> item.getOrderId().equals(executives.getId().toString()) && (item.getStaffType() == 0 || item.getStaffType().equals("0"))).collect(Collectors.toList());
                    if (guanliceng != null && guanliceng.size() > 0) {
                        for (int i = 0; i < guanliceng.size(); i++) {
                            if (i == 0) {
                                excelBaseProjectType.setSalmenOneNumber(guanliceng.get(i).getBrandNumber());
                                excelBaseProjectType.setSalmenOneName(guanliceng.get(i).getStaffName());
                                excelBaseProjectType.setSalmenOneRatio(guanliceng.get(i).getRatio().toString());

                            }
                            if (i == 1) {
                                excelBaseProjectType.setSalmenTwoNumber(guanliceng.get(i).getBrandNumber());
                                excelBaseProjectType.setSalmenTwoName(guanliceng.get(i).getStaffName());
                                excelBaseProjectType.setSalmenTwoRatio(guanliceng.get(i).getRatio().toString());
                            }
                            if (i == 2) {
                                excelBaseProjectType.setSalmenThreeNumber(guanliceng.get(i).getBrandNumber());
                                excelBaseProjectType.setSalmenThreeName(guanliceng.get(i).getStaffName());
                                excelBaseProjectType.setSalmenThreeRatio(guanliceng.get(i).getRatio().toString());
                            }
                            if (i == 3) {
                                excelBaseProjectType.setSalmenFourNumber(guanliceng.get(i).getBrandNumber());
                                excelBaseProjectType.setSalmenFourName(guanliceng.get(i).getStaffName());
                                excelBaseProjectType.setSalmenFourRatio(guanliceng.get(i).getRatio().toString());
                            }
                        }
                    }
                    if (gaoguan != null && gaoguan.size() > 0) {
                        for (int i = 0; i < gaoguan.size(); i++) {
                            if (i == 0) {
                                excelBaseProjectType.setSalmensOneNumber(gaoguan.get(i).getBrandNumber());
                                excelBaseProjectType.setSalmensOneName(gaoguan.get(i).getStaffName());
                                excelBaseProjectType.setSalmensOneRatio(gaoguan.get(i).getRatio().toString());
                            }
                            if (i == 1) {
                                excelBaseProjectType.setSalmensTwoNumber(gaoguan.get(i).getBrandNumber());
                                excelBaseProjectType.setSalmensTwoName(gaoguan.get(i).getStaffName());
                                excelBaseProjectType.setSalmensTwoRatio(gaoguan.get(i).getRatio().toString());
                            }
                            if (i == 2) {
                                excelBaseProjectType.setSalmensThreeNumber(gaoguan.get(i).getBrandNumber());
                                excelBaseProjectType.setSalmensThreeName(gaoguan.get(i).getStaffName());
                                excelBaseProjectType.setSalmensThreeRatio(gaoguan.get(i).getRatio().toString());
                            }
                            if (i == 3) {
                                excelBaseProjectType.setSalmensFourNumber(gaoguan.get(i).getBrandNumber());
                                excelBaseProjectType.setSalmensFourName(gaoguan.get(i).getStaffName());
                                excelBaseProjectType.setSalmensFourRatio(gaoguan.get(i).getRatio().toString());
                            }
                        }
                    }
                    //设置销售人员业绩和提成
                    BigDecimal achievementAmount = excelBaseProjectType.getAchievementAmount().add(excelBaseProjectType.getCardAchievementAmount()).subtract(coopAchi);
                    BigDecimal cashComm = BigDecimal.ZERO;
                    if(excelBaseProjectType.getSalesCommission().compareTo(new BigDecimal("1"))==1){
                        cashComm = excelBaseProjectType.getCommissionAmount();
                    }else cashComm = (excelBaseProjectType.getAchievementAmount().subtract(coopAchi)).multiply(excelBaseProjectType.getSalesCommission());
                    BigDecimal commissionAmount = cashComm.add(excelBaseProjectType.getCardCommissionAmount());

                    if (excelBaseProjectType.getSaleOneStaffId() != null) {
                        excelBaseProjectType.setSaleOneAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleOneRatio().divide(hundred)));
                        excelBaseProjectType.setSaleOneCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleOneRatio().divide(hundred)));
                    }
                    if (excelBaseProjectType.getSaleTwoStaffId() != null) {
                        excelBaseProjectType.setSaleTwoAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleTwoRatio().divide(hundred)));
                        excelBaseProjectType.setSaleTwoCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleTwoRatio().divide(hundred)));
                    }
                    if (excelBaseProjectType.getSaleThreeStaffId() != null) {
                        excelBaseProjectType.setSaleThreeAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleThreeRatio().divide(hundred)));
                        excelBaseProjectType.setSaleThreeCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleThreeRatio().divide(hundred)));
                    }
                    if (excelBaseProjectType.getSaleFourStaffId() != null) {
                        excelBaseProjectType.setSaleFourAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleFourRatio().divide(hundred)));
                        excelBaseProjectType.setSaleFourCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleFourRatio().divide(hundred)));
                    }
                    if (excelBaseProjectType.getSaleFiveStaffId() != null) {
                        excelBaseProjectType.setSaleFiveAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleFiveRatio().divide(hundred)));
                        excelBaseProjectType.setSaleFiveCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleFiveRatio().divide(hundred)));
                    }
                    if (excelBaseProjectType.getSaleSixStaffId() != null) {
                        excelBaseProjectType.setSaleSixAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleSixRatio().divide(hundred)));
                        excelBaseProjectType.setSaleSixCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleSixRatio().divide(hundred)));
                    }
                    if (excelBaseProjectType.getSaleSevenStaffId() != null) {
                        excelBaseProjectType.setSaleSevenAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleSevenRatio().divide(hundred)));
                        excelBaseProjectType.setSaleSevenCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleSevenRatio().divide(hundred)));
                    }
                    if (excelBaseProjectType.getSaleEightStaffId() != null) {
                        excelBaseProjectType.setSaleEightAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleEightRatio().divide(hundred)));
                        excelBaseProjectType.setSaleEightCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleEightRatio().divide(hundred)));
                    }


                    excelBaseProjectTypeList.add(excelBaseProjectType);
                }
            }
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
            //EasyExcel.write(out, LiveRoomData.class).sheet("模板").doWrite(list);
            excelWriter = EasyExcel.write(out).withTemplate(inputStream).build();
            //FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            excelWriter.fill(excelBaseProjectTypeList, writeSheet);
            out.flush();
        } catch (Exception e) {
            log.error("SsmProjectTypeController.export:",e);
        } finally {
            //destFile.delete();
            // 别忘记关闭流
            excelWriter.finish();
        }
    }

    @ApiOperation(value = "查看疗程分类",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/groupCourse")
    public void groupCourse(@RequestBody CourseListRequest courseListRequest, HttpSession session) {
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String staffPhone = SessionHelp.getLoginAccount(session);
        courseListRequest.setStoreId(storeId);
        courseListRequest.setStoreName(storeName);
        courseListRequest.setStaffPhone(staffPhone);
        courseListRequest.setSession(session);
        courseListRequest.setDate(courseListRequest.getStartTime());
        List<Long> projectTypeId = new ArrayList<>();
        //根据门店查出当前门店的所有疗程单据
        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        ExcelWriter excelWriter = null;
        OutputStream out = null;
//        courseListRequest.setStoreId(SessionHelp.getStoreId(session));
        try {
            String fileName = "projectType";
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + ".xlsx");
            out = response.getOutputStream();
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/courseList.xlsx");
//            BeanUtils.copyProperties(projectTypeRequest, baseProjectType);
            List<ExcelCourseList> excelBaseProjectTypeList = new ArrayList<>();
            courseListRequest.setIsCancel(0);
            List<CourseList> courseLists = ssmCourseService.selectGroupCourse(courseListRequest);
            AccountTradeRecordRequest accountTradeRecordRequest = new AccountTradeRecordRequest();
            accountTradeRecordRequest.setInputDate(courseListRequest.getStartTime());
            accountTradeRecordRequest.setStoreIds(courseListRequest.getStoreIds());
            accountTradeRecordRequest.setDocType("card_use");
            List<AccountTradeRecord> accountTradeRecordList = ssmAccountTradeRecordService.selectListByMonthly(accountTradeRecordRequest);
            //查询充值账户
            List<Long> collect1 = accountTradeRecordList.stream().map(item -> item.getAccountId()).collect(Collectors.toList());
            List<RechargeAccount>  rechargeAccountList = ssmRechargeAccountService.selectByIds(collect1);
            if(courseLists!=null && courseLists.size()>0) {
                //查询当前门店所有的疗程项目id
                List<Long> projectIds1 = courseLists.stream().map(item -> item.getProjctId()).collect(Collectors.toList());
                List<BaseProject> projectList = ssmProjectService.selectList(projectIds1);

                //根据传的id进行查询分类直至没有下一级为止
                BaseProjectType baseProjectType = new BaseProjectType();
                baseProjectType.setParentId(courseListRequest.getProjectType());
                projectTypeId = ssmProjectTypeService.selectByEveryId(baseProjectType);
                if (projectTypeId == null || projectTypeId.size() == 0) {
                    projectTypeId.add(courseListRequest.getProjectType());
                }
                List<Long> finalSelect = projectTypeId;
                List<Long> typeProjectId = projectList.stream().filter(item -> finalSelect.contains(item.getProjectTypeId())).map(BaseProject::getId).collect(Collectors.toList());
                List<CourseList> storeCourse = courseLists.stream().filter(item -> typeProjectId.contains(item.getProjctId())).collect(Collectors.toList());
                if (storeCourse != null && storeCourse.size()>0) {
//            salesmen = ssmSalesmanService.selectList(salesman);
                    //所有门店
                    List<BaseStore> select = ssmBaseStoreService.select(null);
                    //所有项目id
//                List<Long> projectIds = storeCourse.stream().filter(courseList -> courseList.getProjctId() != null).map(CourseList::getProjctId).collect(Collectors.toList());
                    //所有单据号
                    List<String> courseNums = storeCourse.stream().map(CourseList::getCourseReatmentNum).collect(Collectors.toList());
//                List<PayList> select1 = ssmPayService.select(null);
                    List<PayList> payListList = ssmPayService.selectList(courseNums);
                    //查询管理层和高管
                    List<Long> courseIds = storeCourse.stream().map(CourseList::getId).collect(Collectors.toList());
                    List<Salesman> salesmanList = ssmSalesmanService.selectList(courseIds);
                    for (CourseList executives : storeCourse) {
                        ExcelCourseList excelBaseProjectType = new ExcelCourseList();
                        BeanUtils.copyProperties(executives, excelBaseProjectType);
                        excelBaseProjectType.setPayType("");
                        //设置充值卡支付的账号和金额
                        List<AccountTradeRecord> collect = accountTradeRecordList.stream().filter(item ->
                                (item.getDocId() == executives.getId() || item.getDocId().toString().equals(executives.getId().toString()))
                                        && (item.getOrderStatu() == null || item.getOrderStatu()==0)&&item.getAccountType().equals("recharge_consume")).collect(Collectors.toList());
                        StringBuffer rechargePay = new StringBuffer("");

                        if(collect!=null && collect.size()>0){
                            for (AccountTradeRecord accountTradeRecord : collect) {
                                for (RechargeAccount rechargeAccount : rechargeAccountList) {
                                    if(accountTradeRecord.getAccountId()==rechargeAccount.getId() || accountTradeRecord.getAccountId().toString().equals(rechargeAccount.getId().toString())){
                                        rechargePay = rechargePay.append(rechargeAccount.getRechargeTypeNum() +"-"+ accountTradeRecord.getAccountName()+"-通用金额支付："
                                                +accountTradeRecord.getAccountSpendMoney()+"元-赠送金额支付："+accountTradeRecord.getAccountGiftSpendMoney()+"元\r\n");
                                    }
                                }
                            }
                        }
                        excelBaseProjectType.setRechargePay(rechargePay.toString());
                        //设置项目编码
                        if (executives.getProjctId() != null) {
                            for (BaseProject baseProject : projectList) {
                                if (executives.getProjctId() == baseProject.getId() || executives.getProjctId().equals(baseProject.getId())) {
                                    excelBaseProjectType.setProjectNum(baseProject.getProjectNum());
                                    if (baseProject.getIsCooperation() != null && baseProject.getIsCooperation() == 1) {
                                        excelBaseProjectType.setIsCoop("是");
                                        if (baseProject.getSmokeCommissionWay() != null && baseProject.getSmokeCommissionWay() == 1) {
                                            excelBaseProjectType.setChouYong("比例-" + baseProject.getBrokerage() == null ? "0%" : baseProject.getBrokerage().setScale(2) + "%");
                                        } else if (baseProject.getSmokeCommissionWay() != null && baseProject.getSmokeCommissionWay() == 0) {
                                            excelBaseProjectType.setChouYong("固定-" + baseProject.getBrokerage() == null ? "0元" : baseProject.getBrokerage().setScale(2) + "元");
                                        }
                                    } else
                                        excelBaseProjectType.setIsCoop("否");
                                }
                            }
                        }
                        if (excelBaseProjectType.getIsCancel() == 0) {
                            excelBaseProjectType.setIsCancelNew("正常");
                        } else {
                            excelBaseProjectType.setIsCancelNew("作废");
                        }
                        //设置门店编码
                        for (BaseStore baseStore : select) {
                            if (baseStore.getId() == excelBaseProjectType.getStoreId() || baseStore.getId().equals(excelBaseProjectType.getStoreId())) {
                                excelBaseProjectType.setStoreNum(baseStore.getStoreNum());
                            }
                        }
                        //设置支付方式
                        for (PayList payList : payListList) {
                            if (payList.getDocId().equals(executives.getCourseReatmentNum())) {
                                excelBaseProjectType.setPayType(excelBaseProjectType.getPayType() + "-" + payList.getPayName() + ":" + payList.getPayMoney() + "元-");
                            }
                        }
                        //设置高管和管理层
                        List<Salesman> guanliceng = salesmanList.stream().filter(item -> {
//                    System.out.println(item.getOrderId().equals(executives.getId().toString()));
//                    System.out.println(item.getStaffType() == 1 || item.getStaffType().equals("1"));
                                    if (item.getOrderId().equals(executives.getId().toString()) && (item.getStaffType() == 1 || item.getStaffType().toString().equals("1"))) {
                                        return true;
                                    }
                                    return false;
                                }
                        ).collect(Collectors.toList());
                        List<Salesman> gaoguan = salesmanList.stream().filter(item -> item.getOrderId().equals(executives.getId().toString()) && (item.getStaffType() == 0 || item.getStaffType().equals("0"))).collect(Collectors.toList());
                        if (guanliceng != null && guanliceng.size() > 0) {
                            for (int i = 0; i < guanliceng.size(); i++) {
                                if (i == 0) {
                                    excelBaseProjectType.setSalmenOneNumber(guanliceng.get(i).getBrandNumber());
                                    excelBaseProjectType.setSalmenOneName(guanliceng.get(i).getStaffName());
                                    excelBaseProjectType.setSalmenOneRatio(guanliceng.get(i).getRatio().toString());

                                }
                                if (i == 1) {
                                    excelBaseProjectType.setSalmenTwoNumber(guanliceng.get(i).getBrandNumber());
                                    excelBaseProjectType.setSalmenTwoName(guanliceng.get(i).getStaffName());
                                    excelBaseProjectType.setSalmenTwoRatio(guanliceng.get(i).getRatio().toString());
                                }
                                if (i == 2) {
                                    excelBaseProjectType.setSalmenThreeNumber(guanliceng.get(i).getBrandNumber());
                                    excelBaseProjectType.setSalmenThreeName(guanliceng.get(i).getStaffName());
                                    excelBaseProjectType.setSalmenThreeRatio(guanliceng.get(i).getRatio().toString());
                                }
                                if (i == 3) {
                                    excelBaseProjectType.setSalmenFourNumber(guanliceng.get(i).getBrandNumber());
                                    excelBaseProjectType.setSalmenFourName(guanliceng.get(i).getStaffName());
                                    excelBaseProjectType.setSalmenFourRatio(guanliceng.get(i).getRatio().toString());
                                }
                            }
                        }
                        if (gaoguan != null && gaoguan.size() > 0) {
                            for (int i = 0; i < gaoguan.size(); i++) {
                                if (i == 0) {
                                    excelBaseProjectType.setSalmensOneNumber(gaoguan.get(i).getBrandNumber());
                                    excelBaseProjectType.setSalmensOneName(gaoguan.get(i).getStaffName());
                                    excelBaseProjectType.setSalmensOneRatio(gaoguan.get(i).getRatio().toString());
                                }
                                if (i == 1) {
                                    excelBaseProjectType.setSalmensTwoNumber(gaoguan.get(i).getBrandNumber());
                                    excelBaseProjectType.setSalmensTwoName(gaoguan.get(i).getStaffName());
                                    excelBaseProjectType.setSalmensTwoRatio(gaoguan.get(i).getRatio().toString());
                                }
                                if (i == 2) {
                                    excelBaseProjectType.setSalmensThreeNumber(gaoguan.get(i).getBrandNumber());
                                    excelBaseProjectType.setSalmensThreeName(gaoguan.get(i).getStaffName());
                                    excelBaseProjectType.setSalmensThreeRatio(gaoguan.get(i).getRatio().toString());
                                }
                                if (i == 3) {
                                    excelBaseProjectType.setSalmensFourNumber(gaoguan.get(i).getBrandNumber());
                                    excelBaseProjectType.setSalmensFourName(gaoguan.get(i).getStaffName());
                                    excelBaseProjectType.setSalmensFourRatio(gaoguan.get(i).getRatio().toString());
                                }
                            }
                        }
                        //设置销售人员业绩和提成
                        BigDecimal achievementAmount = excelBaseProjectType.getAchievementAmount().add(excelBaseProjectType.getCardAchievementAmount());
                        BigDecimal commissionAmount = excelBaseProjectType.getCommissionAmount().add(excelBaseProjectType.getCardCommissionAmount());
                        BigDecimal hundred = new BigDecimal("100");
                        if (excelBaseProjectType.getSaleOneStaffId() != null) {
                            excelBaseProjectType.setSaleOneAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleOneRatio().divide(hundred)));
                            excelBaseProjectType.setSaleOneCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleOneRatio().divide(hundred)));
                        }
                        if (excelBaseProjectType.getSaleTwoStaffId() != null) {
                            excelBaseProjectType.setSaleTwoAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleTwoRatio().divide(hundred)));
                            excelBaseProjectType.setSaleTwoCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleTwoRatio().divide(hundred)));
                        }
                        if (excelBaseProjectType.getSaleThreeStaffId() != null) {
                            excelBaseProjectType.setSaleThreeAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleThreeRatio().divide(hundred)));
                            excelBaseProjectType.setSaleThreeCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleThreeRatio().divide(hundred)));
                        }
                        if (excelBaseProjectType.getSaleFourStaffId() != null) {
                            excelBaseProjectType.setSaleFourAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleFourRatio().divide(hundred)));
                            excelBaseProjectType.setSaleFourCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleFourRatio().divide(hundred)));
                        }
                        if (excelBaseProjectType.getSaleFiveStaffId() != null) {
                            excelBaseProjectType.setSaleFiveAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleFiveRatio().divide(hundred)));
                            excelBaseProjectType.setSaleFiveCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleFiveRatio().divide(hundred)));
                        }
                        if (excelBaseProjectType.getSaleSixStaffId() != null) {
                            excelBaseProjectType.setSaleSixAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleSixRatio().divide(hundred)));
                            excelBaseProjectType.setSaleSixCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleSixRatio().divide(hundred)));
                        }
                        if (excelBaseProjectType.getSaleSevenStaffId() != null) {
                            excelBaseProjectType.setSaleSevenAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleSevenRatio().divide(hundred)));
                            excelBaseProjectType.setSaleSevenCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleSevenRatio().divide(hundred)));
                        }
                        if (excelBaseProjectType.getSaleEightStaffId() != null) {
                            excelBaseProjectType.setSaleEightAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleEightRatio().divide(hundred)));
                            excelBaseProjectType.setSaleEightCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleEightRatio().divide(hundred)));
                        }


                        excelBaseProjectTypeList.add(excelBaseProjectType);
                    }
                }
            }
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
            //EasyExcel.write(out, LiveRoomData.class).sheet("模板").doWrite(list);
            excelWriter = EasyExcel.write(out).withTemplate(inputStream).build();
            //FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            excelWriter.fill(excelBaseProjectTypeList, writeSheet);
            out.flush();
        } catch (Exception e) {
            log.error("SsmProjectTypeController.export:", e);
        } finally {
            //destFile.delete();
            // 别忘记关闭流
            excelWriter.finish();
        }

    }
    // todo 会员初始化
    @ApiOperation(value = "多疗程添加  (门店端-疗程单-疗程多添加)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/memberInit")
//    @RequestMapping("/addListBySmsFix")
    public GenericResponse memberInit(@RequestBody CourseListRequestNew courseListRequestNew, HttpSession session) {
        //查询容差
        GenericResponse genericResponse = new GenericResponse();
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        Long storeId = SessionHelp.getStoreId(session);//265309505575694336L;//
        String storeName = SessionHelp.getStoreName(session);//"总店";//
        String staffPhone = SessionHelp.getLoginAccount(session);//"18070793360";//
        courseListRequestNew.setStoreId(storeId);
        courseListRequestNew.setStoreName(storeName);
        courseListRequestNew.setSession(session);

        courseListRequestNew.setStaffPhone(staffPhone);
//        courseListRequest.setStoreId(storeId);
//        courseListRequest.setStoreName(storeName);

        //判断所有疗程的成交总额是否跟卡付和现付是否相同

        int i = 0;
        try {
            i += ssmCourseService.memberInit(courseListRequestNew);
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmCourseController.add:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }

        return genericResponse;
    }


    @ApiOperation(value = "分页查询疗程单  (门店端-疗程单-列表分页查询疗程单)",httpMethod = "POST",response = PageResponse.class)
    @RequestMapping("/memberPage")
    public PageResponse memberPage(@RequestBody CourseListRequest courseListRequest, HttpSession session){
        PageResponse<CourseListResponse> pageResponse = new PageResponse<>();
        PageInfo<CourseListResponse> pageInfo = new PageInfo<>();
        if(SessionHelp.getStoreId(session)==null){
            pageResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return pageResponse;
        }
        Long storeId = SessionHelp.getStoreId(session);
        List<Long> listStoreId=new ArrayList<>();
        if(null == courseListRequest.getStoreList()|| courseListRequest.getStoreList().size()==0){
            courseListRequest.setSelectType(1);
            courseListRequest.setStoreId(storeId);
            listStoreId.add(storeId);
            courseListRequest.setStoreList(listStoreId);
        }else{
            courseListRequest.setSelectType(0);
        }
        try {
            pageInfo = ssmCourseService.memberPage(courseListRequest);
        }catch (SmsException e){
            pageResponse.setCodeAndMsg(e);
            return pageResponse;
        }catch (Exception e){
            log.error("SsmCourseController.selectPage:",e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }

    @ApiOperation(value = "疗程单详情  (门店端-疗程单-疗程单作废)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/selectCourseMemberInit")
    public GenericResponse selectCourseMemberInit(@RequestBody CourseListRequest courseListRequest){
        GenericResponse genericResponse = new GenericResponse();
        try {
            CourseVo courseVo = ssmCourseService.selectCourseMemberInit(courseListRequest);
            genericResponse.setData(courseVo);
        }catch (Exception e){
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }

    @ApiOperation(value = "疗程单作废  (门店端-疗程单-疗程单作废)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/memberInitCancel")
    @Transactional(rollbackFor = Exception.class)
    public GenericResponse memberInitCancel(@RequestBody CourseListRequest courseListRequest, HttpSession session) {

        GenericResponse genericResponse = new GenericResponse();
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        CourseList courseList = new CourseList();
        courseList.setCourseReatmentNum(courseListRequest.getCourseReatmentNum());
        courseList.setDate(courseListRequest.getDate());
        List<CourseList> courseLists = ssmCourseService.selectMemberInitList(courseList);
        int i = 0;
        for (CourseList list : courseLists) {
            Long storeId = SessionHelp.getStoreId(session);
            BeanUtils.copyProperties(list,courseListRequest);
            String storeName = SessionHelp.getStoreName(session);
            String staffPhone = SessionHelp.getLoginAccount(session);
            courseListRequest.setStoreId(storeId);
            courseListRequest.setStoreName(storeName);
            courseListRequest.setStaffPhone(staffPhone);
            try {
                i += ssmCourseService.memberInitCancel(courseListRequest);
                genericResponse.setCodeAndMsg(ResponseCode.OK);
            }catch (SmsException e){
                genericResponse.setCodeAndMsg(e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return genericResponse;
            }catch (Exception e){
                log.error("SsmCourseController.cancel:",e);
                genericResponse.setCodeAndMsg(ResponseCode.FAILED);
                return genericResponse;
            }
            if (i > 0){
                genericResponse.setCodeAndMsg(ResponseCode.OK);
            }
        }
        return genericResponse;
    }

    @ApiOperation(value = "疗程单修改业务员  (门店端-疗程单-疗程单修改业务员)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/updateMemberInitStaff")
    public GenericResponse updateMemberInitStaff(@RequestBody CourseListRequest courseListRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        String storeName = SessionHelp.getStoreName(session);
        String staffPhone = SessionHelp.getLoginAccount(session);
        courseListRequest.setStoreId(storeId);
        courseListRequest.setStoreName(storeName);
        courseListRequest.setStaffPhone(staffPhone);
        courseListRequest.setSession(session);
        int i = 0;
        try {
            i = ssmCourseService.updateMemberInitStaff(courseListRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmCourseController.updateStaff:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0){
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }
    @ApiOperation(value = "单据导出", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/courseListMemberInit/exportachis")
    public void courseListMemberInit(@RequestBody CourseListRequest courseListRequest, HttpSession session) {
        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        ExcelWriter excelWriter = null;
        OutputStream out = null;
//        courseListRequest.setStoreId(SessionHelp.getStoreId(session));
        try {
            String fileName = "projectType";
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + ".xlsx");
            out = response.getOutputStream();
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/courseList.xlsx");
//            BeanUtils.copyProperties(projectTypeRequest, baseProjectType);
            List<ExcelCourseList> excelBaseProjectTypeList = new ArrayList<>();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
            String format = dateFormat.format(courseListRequest.getDate());
            courseListRequest.setMemberInitList(format);
            List<CourseList> list = ssmCourseService.selectListByMemberInitList(courseListRequest);
            if(list!=null && list.size()>0) {
                AccountTradeRecordRequest accountTradeRecordRequest = new AccountTradeRecordRequest();
                accountTradeRecordRequest.setInputDate(courseListRequest.getDate());
                accountTradeRecordRequest.setStoreIds(courseListRequest.getStoreIds());
                accountTradeRecordRequest.setDocType("card_use");
                List<AccountTradeRecord> accountTradeRecordList = ssmAccountTradeRecordService.selectListByMonthly(accountTradeRecordRequest);
                //查询充值账户
                List<Long> collect1 = accountTradeRecordList.stream().map(item -> item.getAccountId()).collect(Collectors.toList());
                List<RechargeAccount> rechargeAccountList = ssmRechargeAccountService.selectByIds(collect1);
                if (list != null) {
//            salesmen = ssmSalesmanService.selectList(salesman);
                    //所有门店
                    List<BaseStore> select = ssmBaseStoreService.select(null);
                    //所有项目id
                    List<Long> projectIds = list.stream().filter(courseList -> courseList.getProjctId() != null).map(CourseList::getProjctId).collect(Collectors.toList());
                    List<BaseProject> projectList = ssmProjectService.selectList(projectIds);
                    //所有单据号
                    List<String> courseNums = list.stream().map(CourseList::getCourseReatmentNum).collect(Collectors.toList());
//                List<PayList> select1 = ssmPayService.select(null);
                    List<PayList> payListList = ssmPayService.selectList(courseNums);
                    //查询管理层和高管
                    List<Long> courseIds = list.stream().map(CourseList::getId).collect(Collectors.toList());
                    List<Salesman> salesmanList = ssmSalesmanService.selectList(courseIds);
                    for (CourseList executives : list) {
                        ExcelCourseList excelBaseProjectType = new ExcelCourseList();
                        BeanUtils.copyProperties(executives, excelBaseProjectType);
                        excelBaseProjectType.setPayType("");
                        excelBaseProjectType.setPayType("");
                        //设置充值卡支付的账号和金额
                        List<AccountTradeRecord> collect = accountTradeRecordList.stream().filter(item ->
                                (item.getDocId() == executives.getId() || item.getDocId().toString().equals(executives.getId().toString()))
                                        && (item.getOrderStatu() == null || item.getOrderStatu() == 0) && item.getAccountType().equals("recharge_consume")).collect(Collectors.toList());
                        StringBuilder rechargePay = new StringBuilder("");

                        if (collect != null && collect.size() > 0) {
                            for (AccountTradeRecord accountTradeRecord : collect) {
                                for (RechargeAccount rechargeAccount : rechargeAccountList) {
                                    if (accountTradeRecord.getAccountId() == rechargeAccount.getId()
                                            || accountTradeRecord.getAccountId().toString().equals(rechargeAccount.getId().toString())) {
                                        rechargePay = rechargePay.append(rechargeAccount.getRechargeTypeNum() + "-" + accountTradeRecord.getAccountName() + "-通用金额支付："
                                                + accountTradeRecord.getAccountSpendMoney() + "元-赠送金额支付：" + accountTradeRecord.getAccountGiftSpendMoney() + "元\r\n");
                                    }
                                }
                            }
                        }
                        excelBaseProjectType.setRechargePay(rechargePay.toString());
                        //设置项目编码
                        if (executives.getProjctId() != null) {
                            for (BaseProject baseProject : projectList) {
                                if (executives.getProjctId() == baseProject.getId() || executives.getProjctId().equals(baseProject.getId())) {
                                    excelBaseProjectType.setProjectNum(baseProject.getProjectNum());
                                    if (baseProject.getIsCooperation() != null && baseProject.getIsCooperation() == 1) {
                                        excelBaseProjectType.setIsCoop("是");
                                        if (baseProject.getSmokeCommissionWay() != null && baseProject.getSmokeCommissionWay() == 1) {
                                            excelBaseProjectType.setChouYong("比例-" + baseProject.getBrokerage() == null ? "0%" : baseProject.getBrokerage().setScale(2) + "%");
                                        } else if (baseProject.getSmokeCommissionWay() != null && baseProject.getSmokeCommissionWay() == 0) {
                                            excelBaseProjectType.setChouYong("固定-" + baseProject.getBrokerage() == null ? "0元" : baseProject.getBrokerage().setScale(2) + "元");
                                        }
                                    } else
                                        excelBaseProjectType.setIsCoop("否");
                                }
                            }
                        }
                        if (excelBaseProjectType.getIsCancel() == 0) {
                            excelBaseProjectType.setIsCancelNew("正常");
                        } else {
                            excelBaseProjectType.setIsCancelNew("作废");
                        }
                        //设置门店编码
                        for (BaseStore baseStore : select) {
                            if (baseStore.getId() == excelBaseProjectType.getStoreId() || baseStore.getId().equals(excelBaseProjectType.getStoreId())) {
                                excelBaseProjectType.setStoreNum(baseStore.getStoreNum());
                            }
                        }
                        //设置支付方式
                        for (PayList payList : payListList) {
                            if (payList.getDocId().equals(executives.getCourseReatmentNum())) {
                                excelBaseProjectType.setPayType(excelBaseProjectType.getPayType() + "-" + payList.getPayName() + ":" + payList.getPayMoney() + "元-");
                            }
                        }
                        //设置高管和管理层
                        List<Salesman> guanliceng = salesmanList.stream().filter(item -> {
//                    System.out.println(item.getOrderId().equals(executives.getId().toString()));
//                    System.out.println(item.getStaffType() == 1 || item.getStaffType().equals("1"));
                                    if (item.getOrderId().equals(executives.getId().toString()) && (item.getStaffType() == 1 || item.getStaffType().toString().equals("1"))) {
                                        return true;
                                    }
                                    return false;
                                }
                        ).collect(Collectors.toList());
                        List<Salesman> gaoguan = salesmanList.stream().filter(item -> item.getOrderId().equals(executives.getId().toString()) && (item.getStaffType() == 0 || item.getStaffType().equals("0"))).collect(Collectors.toList());
                        if (guanliceng != null && guanliceng.size() > 0) {
                            for (int i = 0; i < guanliceng.size(); i++) {
                                if (i == 0) {
                                    excelBaseProjectType.setSalmenOneNumber(guanliceng.get(i).getBrandNumber());
                                    excelBaseProjectType.setSalmenOneName(guanliceng.get(i).getStaffName());
                                    excelBaseProjectType.setSalmenOneRatio(guanliceng.get(i).getRatio().toString());

                                }
                                if (i == 1) {
                                    excelBaseProjectType.setSalmenTwoNumber(guanliceng.get(i).getBrandNumber());
                                    excelBaseProjectType.setSalmenTwoName(guanliceng.get(i).getStaffName());
                                    excelBaseProjectType.setSalmenTwoRatio(guanliceng.get(i).getRatio().toString());
                                }
                                if (i == 2) {
                                    excelBaseProjectType.setSalmenThreeNumber(guanliceng.get(i).getBrandNumber());
                                    excelBaseProjectType.setSalmenThreeName(guanliceng.get(i).getStaffName());
                                    excelBaseProjectType.setSalmenThreeRatio(guanliceng.get(i).getRatio().toString());
                                }
                                if (i == 3) {
                                    excelBaseProjectType.setSalmenFourNumber(guanliceng.get(i).getBrandNumber());
                                    excelBaseProjectType.setSalmenFourName(guanliceng.get(i).getStaffName());
                                    excelBaseProjectType.setSalmenFourRatio(guanliceng.get(i).getRatio().toString());
                                }
                            }
                        }
                        if (gaoguan != null && gaoguan.size() > 0) {
                            for (int i = 0; i < gaoguan.size(); i++) {
                                if (i == 0) {
                                    excelBaseProjectType.setSalmensOneNumber(gaoguan.get(i).getBrandNumber());
                                    excelBaseProjectType.setSalmensOneName(gaoguan.get(i).getStaffName());
                                    excelBaseProjectType.setSalmensOneRatio(gaoguan.get(i).getRatio().toString());
                                }
                                if (i == 1) {
                                    excelBaseProjectType.setSalmensTwoNumber(gaoguan.get(i).getBrandNumber());
                                    excelBaseProjectType.setSalmensTwoName(gaoguan.get(i).getStaffName());
                                    excelBaseProjectType.setSalmensTwoRatio(gaoguan.get(i).getRatio().toString());
                                }
                                if (i == 2) {
                                    excelBaseProjectType.setSalmensThreeNumber(gaoguan.get(i).getBrandNumber());
                                    excelBaseProjectType.setSalmensThreeName(gaoguan.get(i).getStaffName());
                                    excelBaseProjectType.setSalmensThreeRatio(gaoguan.get(i).getRatio().toString());
                                }
                                if (i == 3) {
                                    excelBaseProjectType.setSalmensFourNumber(gaoguan.get(i).getBrandNumber());
                                    excelBaseProjectType.setSalmensFourName(gaoguan.get(i).getStaffName());
                                    excelBaseProjectType.setSalmensFourRatio(gaoguan.get(i).getRatio().toString());
                                }
                            }
                        }
                        //设置销售人员业绩和提成
                        BigDecimal achievementAmount = excelBaseProjectType.getAchievementAmount().add(excelBaseProjectType.getCardAchievementAmount());
                        BigDecimal commissionAmount = excelBaseProjectType.getCommissionAmount().add(excelBaseProjectType.getCardCommissionAmount());
                        BigDecimal hundred = new BigDecimal("100");
                        if (excelBaseProjectType.getSaleOneStaffId() != null) {
                            excelBaseProjectType.setSaleOneAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleOneRatio().divide(hundred)));
                            excelBaseProjectType.setSaleOneCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleOneRatio().divide(hundred)));
                        }
                        if (excelBaseProjectType.getSaleTwoStaffId() != null) {
                            excelBaseProjectType.setSaleTwoAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleTwoRatio().divide(hundred)));
                            excelBaseProjectType.setSaleTwoCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleTwoRatio().divide(hundred)));
                        }
                        if (excelBaseProjectType.getSaleThreeStaffId() != null) {
                            excelBaseProjectType.setSaleThreeAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleThreeRatio().divide(hundred)));
                            excelBaseProjectType.setSaleThreeCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleThreeRatio().divide(hundred)));
                        }
                        if (excelBaseProjectType.getSaleFourStaffId() != null) {
                            excelBaseProjectType.setSaleFourAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleFourRatio().divide(hundred)));
                            excelBaseProjectType.setSaleFourCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleFourRatio().divide(hundred)));
                        }
                        if (excelBaseProjectType.getSaleFiveStaffId() != null) {
                            excelBaseProjectType.setSaleFiveAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleFiveRatio().divide(hundred)));
                            excelBaseProjectType.setSaleFiveCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleFiveRatio().divide(hundred)));
                        }
                        if (excelBaseProjectType.getSaleSixStaffId() != null) {
                            excelBaseProjectType.setSaleSixAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleSixRatio().divide(hundred)));
                            excelBaseProjectType.setSaleSixCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleSixRatio().divide(hundred)));
                        }
                        if (excelBaseProjectType.getSaleSevenStaffId() != null) {
                            excelBaseProjectType.setSaleSevenAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleSevenRatio().divide(hundred)));
                            excelBaseProjectType.setSaleSevenCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleSevenRatio().divide(hundred)));
                        }
                        if (excelBaseProjectType.getSaleEightStaffId() != null) {
                            excelBaseProjectType.setSaleEightAchievementAmount(achievementAmount.multiply(excelBaseProjectType.getSaleEightRatio().divide(hundred)));
                            excelBaseProjectType.setSaleEightCommissionAmount(commissionAmount.multiply(excelBaseProjectType.getSaleEightRatio().divide(hundred)));
                        }


                        excelBaseProjectTypeList.add(excelBaseProjectType);
                    }
                }
                WriteCellStyle headWriteCellStyle = new WriteCellStyle();
                // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
                excelWriter = EasyExcel.write(out).withTemplate(inputStream).build();
                WriteSheet writeSheet = EasyExcel.writerSheet().build();
                excelWriter.fill(excelBaseProjectTypeList, writeSheet);
                out.flush();
            }
        } catch (Exception e) {
            log.error("SsmProjectTypeController.export:",e);
        } finally {
            //destFile.delete();
            // 别忘记关闭流
            excelWriter.finish();
        }
    }



}
