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.ChuangLanBeanSmsUtil;
import com.ssm.manage.entity.*;
import com.ssm.manage.excelEntity.ExcelRechargeList;
import com.ssm.manage.query.RechargeListRequest;
import com.ssm.manage.query.StoreRequest;
import com.ssm.manage.response.RechargeListResponse;
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.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.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Api(value="门店充值controller",tags={"门店充值相关接口"})
@RestController
@RequestMapping("/demay/ssm/rec")
@Slf4j
public class SsmRechargeController {

    @Autowired
    private ChuangLanBeanSmsUtil chuangLanBeanSmsUtil;

    @Autowired
    private SsmRechargeService ssmRechargeService;

    @Autowired
    private SsmDebtService ssmDebtService;

    @Autowired
    private SmsFixService smsFixService;

    @Autowired
    private SsmRechargeAccountService ssmRechargeAccountService;

    @Autowired
    private SsmRechargeTypeSevice ssmRechargeTypeSevice;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmPayService ssmPayService;

    @Autowired
    private SsmSalesmanService ssmSalesmanService;

    @ApiOperation(value = "分页查询充值单  (门店端-充值单-列表分页查询充值单)",httpMethod = "POST",response = PageResponse.class)
    @RequestMapping("/page")
    public PageResponse selectPage(@RequestBody RechargeListRequest rechargeListRequest, HttpSession session){
        PageResponse<RechargeListResponse> pageResponse = new PageResponse<>();
        PageInfo<RechargeListResponse> pageInfo = new PageInfo<>();
        Long storeId = SessionHelp.getStoreId(session);

        rechargeListRequest.setStoreId(storeId);
        try {
            pageInfo = ssmRechargeService.selectPage(rechargeListRequest);
        }catch (SmsException e){
            pageResponse.setCodeAndMsg(e);
            return pageResponse;
        }catch (Exception e){
            log.error("SsmRechargeController.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 RechargeListRequest rechargeListRequest, HttpSession session){
        PageResponse<RechargeListResponse> pageResponse = new PageResponse<>();
        PageInfo<RechargeListResponse> pageInfo = new PageInfo<>();

        Long storeId = SessionHelp.getStoreId(session);
        List<Long> listStoreId=new ArrayList<>();
        if(null == rechargeListRequest.getStoreList() || rechargeListRequest.getStoreList().size() == 0){
            //自动查询
            rechargeListRequest.setSelectType(1);
            rechargeListRequest.setStoreId(storeId);
            listStoreId.add(storeId);
            rechargeListRequest.setStoreList(listStoreId);
        }else{
            //指定查询
            rechargeListRequest.setSelectType(0);
        }

        try {
            pageInfo = ssmRechargeService.selectPageNew(rechargeListRequest);
        }catch (SmsException e){
            pageResponse.setCodeAndMsg(e);
            return pageResponse;
        }catch (Exception e){
            log.error("SsmRechargeController.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 RechargeListRequest rechargeListRequest, HttpSession session){
        PageResponse<RechargeListResponse> pageResponse = new PageResponse<>();
        PageInfo<RechargeListResponse> pageInfo = new PageInfo<>();
        try {
            pageInfo = ssmRechargeService.pageDetail(rechargeListRequest);
        }catch (SmsException e){
            pageResponse.setCodeAndMsg(e);
            return pageResponse;
        }catch (Exception e){
            log.error("SsmRechargeController.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("/addBySmsFix")
//    @RequestMapping("/add")
    public GenericResponse addBySmsFix(@RequestBody RechargeListRequest rechargeListRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        if(rechargeListRequest.getRechargeTypeName()==null||rechargeListRequest.getRechargeTypeName().equals("")){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"错误操作,请选择充值的类型");
            return genericResponse;
        }
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String staffPhone = SessionHelp.getLoginAccount(session);
        if(storeId==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请重新登录");
            return genericResponse;
        }
        rechargeListRequest.setStoreId(storeId);
        rechargeListRequest.setStoreName(storeName);
        rechargeListRequest.setStaffPhone(staffPhone);
        //添加高管的当前单据门店信息
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(SessionHelp.getStoreId(session));
        BaseStore baseStore1 = ssmBaseStoreService.selectOne(storeRequest);
        List<Salesman> salesmens = rechargeListRequest.getSalesmens();
        for (Salesman salesmen : salesmens) {
            salesmen.setStoreNum(baseStore1.getStoreNum());
            salesmen.setStoreName(baseStore1.getStoreName());
            salesmen.setStoreIdOrder(baseStore1.getId());
        }

        int i = 0;
        try {
            i = ssmRechargeService.addRecharge(rechargeListRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmRechargeController.add:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if(rechargeListRequest.getIsSendSms()==1){


            if (i > 0){
                //genericResponse.setCodeAndMsg(ResponseCode.OK);
                BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(rechargeListRequest.getStoreId());
                //设置短信账户 发送 否则不发送
                if (StringUtils.isNotBlank(baseStore.getSmsAccount()) && null != baseStore.getMessagingPlatform()) {
                    try {
                        if(rechargeListRequest.getIsAddition()==1){
                            //chuangLanBeanSmsUtil.sendRechargeSms(baseStore, rechargeListRequest.getMobilePhone(), rechargeListRequest.getCollectionAmount(),rechargeListRequest.getAdditionDate());
                        }else{
                            SmsFix smsFix = new SmsFix();
                            if(baseStore.getParentId()==null){
                                smsFix.setStoreId(baseStore.getId());
                            }
                            else smsFix.setStoreId(baseStore.getParentId());

                            List<Integer> types = new ArrayList<>();
                            types.add(1);
                            smsFix.setTypes(types);

                            List<SmsFix> smsFixList = smsFixService.selectByTypeAndStoreId(smsFix);
                            if(smsFixList==null || smsFixList.size()==0){
                                genericResponse.setCodeAndMsg(ResponseCode.MSG,"充值开卡未配置短信模板!");
                                return genericResponse;
                            }
                            RechargeAccount rechargeAccount = new RechargeAccount();
                            rechargeAccount.setMemberId(rechargeListRequest.getMemberId());
                            rechargeAccount.setRechargeTypeId(rechargeListRequest.getRechargeTypeId());
                            rechargeAccount = ssmRechargeAccountService.selectOne(rechargeAccount);
                            RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeListRequest.getRechargeTypeId());
                            chuangLanBeanSmsUtil.sendRechargeSmsNewBySmsFix(baseStore,
                                    rechargeListRequest.getMobilePhone(),
                                    rechargeAccount,
                                    rechargeListRequest.getCollectionAmount(),
                                    rechargeType.getGiftMoney()==null? BigDecimal.ZERO:rechargeType.getGiftMoney(),smsFixList.get(0));
//                        chuangLanBeanSmsUtil.sendRechargeSms(baseStore, rechargeListRequest.getMobilePhone(), rechargeListRequest.getCollectionAmount());
                        }
                        genericResponse.setCodeAndMsg(ResponseCode.OK);
                    } catch (IOException e) {
                        log.error("SsmRechargeController.add:", e);
                    } catch (SmsException e) {
                        genericResponse.setCodeAndMsg(ResponseCode.SMS_SEND_OK_EXCEPTION);
                        log.error("短信发送失败SsmRechargeController.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")
//    @RequestMapping("/retransmissionNew")
    public GenericResponse retransmission(@RequestBody RechargeListRequest rechargeListRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String staffPhone = SessionHelp.getLoginAccount(session);
        rechargeListRequest.setStoreId(storeId);
        rechargeListRequest.setStoreName(storeName);
        rechargeListRequest.setStaffPhone(staffPhone);
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(rechargeListRequest.getStoreId());
        //设置短信账户 发送 否则不发送
        if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
            try {
                //if(rechargeListRequest.getIsAddition()==1){
                RechargeAccount rechargeAccount1 = ssmRechargeAccountService.selectByPrimaryKey(rechargeListRequest.getRechargeAccountId());
                RechargeAccount rechargeAccount = new RechargeAccount();
                rechargeAccount.setMemberId(rechargeAccount1.getMemberId());
                List<RechargeAccount> select = ssmRechargeAccountService.select(rechargeAccount);
                rechargeAccount = select.get(0);
                rechargeAccount.setCardRestMoney(select.stream().map(RechargeAccount::getCardRestMoney).reduce(BigDecimal.ZERO,BigDecimal::add));
                rechargeAccount.setCardGiftMoney(select.stream().map(RechargeAccount::getCardGiftMoney).reduce(BigDecimal.ZERO,BigDecimal::add));

                BigDecimal gifMoney = rechargeListRequest.getGiftAfterMoney().subtract(rechargeListRequest.getGiftBeforeMoney());
                chuangLanBeanSmsUtil.sendRechargeSmsNew(baseStore,rechargeListRequest.getMobilePhone(),rechargeAccount,  rechargeListRequest.getCollectionAmount(),gifMoney);
//                    chuangLanBeanSmsUtil.sendRechargeSms(baseStore, rechargeListRequest.getMobilePhone(), rechargeListRequest.getCollectionAmount(),rechargeListRequest.getAdditionDate());
                //}
                genericResponse.setCodeAndMsg(ResponseCode.OK);
            } catch (SmsException e) {
                log.error("SsmRechargeController.add:", e);
                genericResponse.setCodeAndMsg(e);
            }
        }
        return genericResponse;
    }

    @ApiOperation(value = "充值补单短信重发",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/retransmissionNew")
//    @RequestMapping("/retransmission")
    public GenericResponse retransmissionNew(@RequestBody RechargeListRequest rechargeListRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String staffPhone = SessionHelp.getLoginAccount(session);
        rechargeListRequest.setStoreId(storeId);
        rechargeListRequest.setStoreName(storeName);
        rechargeListRequest.setStaffPhone(staffPhone);
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(rechargeListRequest.getStoreId());
        //设置短信账户 发送 否则不发送
        if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
            try {
                SmsFix smsFix = new SmsFix();
                if(baseStore.getParentId()==null){
                    smsFix.setStoreId(baseStore.getId());
                }
                else smsFix.setStoreId(baseStore.getParentId());

                List<Integer> types = new ArrayList<>();
                types.add(1);
                smsFix.setTypes(types);

                List<SmsFix> smsFixList = smsFixService.selectByTypeAndStoreId(smsFix);
                if(smsFixList==null || smsFixList.size()==0){
                    genericResponse.setCodeAndMsg(ResponseCode.MSG,"充值开卡未配置短信模板!");
                    return genericResponse;
                }

                //if(rechargeListRequest.getIsAddition()==1){
                RechargeAccount rechargeAccount = ssmRechargeAccountService.selectByPrimaryKey(rechargeListRequest.getRechargeAccountId());
                RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeListRequest.getRechargeTypeId());
                BigDecimal gifMoney = rechargeListRequest.getGiftAfterMoney().subtract(rechargeListRequest.getGiftBeforeMoney());
                chuangLanBeanSmsUtil.sendRechargeSmsNewBySmsFix(baseStore,
                        rechargeListRequest.getMobilePhone(),
                        rechargeAccount,
                        rechargeListRequest.getCollectionAmount(),
                        rechargeType.getGiftMoney()==null? BigDecimal.ZERO:rechargeType.getGiftMoney(),smsFixList.get(0));
//                chuangLanBeanSmsUtil.sendRechargeSmsNew(baseStore,rechargeListRequest.getMobilePhone(),rechargeAccount,  rechargeListRequest.getCollectionAmount(),gifMoney);
//                    chuangLanBeanSmsUtil.sendRechargeSms(baseStore, rechargeListRequest.getMobilePhone(), rechargeListRequest.getCollectionAmount(),rechargeListRequest.getAdditionDate());
                //}
                genericResponse.setCodeAndMsg(ResponseCode.OK);
            } catch (IOException e) {
                log.error("SsmRechargeController.add:", e);
            } catch (SmsException e) {
                log.error("SsmRechargeController.add:", e);
                genericResponse.setCodeAndMsg(e);
            }
        }
        return genericResponse;
    }
//    @ApiOperation(value = "充值单作废  (门店端-充值单-单据记录-充值单作废)",httpMethod = "POST",response = GenericResponse.class)
//    @RequestMapping("/cancel")
//    public GenericResponse cancel(@RequestBody List<RechargeListRequest> rechargeListRequests,HttpSession session) {
//        GenericResponse genericResponse = new GenericResponse();
//        Long storeId = SessionHelp.getStoreId(session);
//        String storeName = SessionHelp.getStoreName(session);
//        String staffPhone = SessionHelp.getLoginAccount(session);
//        int i = 0;
//        try {
//        for (RechargeListRequest rechargeListRequest : rechargeListRequests) {
//            if(rechargeListRequest.getStoreId()==null||rechargeListRequest.getStoreName()==null){
//                rechargeListRequest.setStoreId(storeId);
//                rechargeListRequest.setStoreName(storeName);
//            }
//            rechargeListRequest.setStaffPhone(staffPhone);
//            i += ssmRechargeService.cancel(rechargeListRequest);
//        }
//
//
//        }catch (SmsException e){
//            genericResponse.setCodeAndMsg(e);
//            return genericResponse;
//        }catch (Exception e){
//            log.error("SsmRechargeController.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 RechargeListRequest rechargeListRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String staffPhone = SessionHelp.getLoginAccount(session);
        rechargeListRequest.setStoreId(storeId);
        rechargeListRequest.setStoreName(storeName);
        rechargeListRequest.setStaffPhone(staffPhone);
        int i = 0;
        try {
            i = ssmRechargeService.updateStaff(rechargeListRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmRechargeController.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("/addUpgrade")
    public GenericResponse addUpgrade(@RequestBody RechargeListRequest rechargeListRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String staffPhone = SessionHelp.getLoginAccount(session);
        rechargeListRequest.setStoreId(storeId);
        rechargeListRequest.setStoreName(storeName);
        rechargeListRequest.setStaffPhone(staffPhone);
        int i = 0;
        try {
            i = ssmRechargeService.addRecharges(rechargeListRequest);

        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmRechargeController.add:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if(rechargeListRequest.getIsSendSms()==1) {
            if (i > 0) {
                genericResponse.setCodeAndMsg(ResponseCode.OK);
                BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(rechargeListRequest.getStoreId());
                //设置短信账户 发送 否则不发送
                if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
                    try {
                        RechargeAccount rechargeAccount = new RechargeAccount();
                        rechargeAccount.setMemberId(rechargeListRequest.getMemberId());
                      List<RechargeAccount> select = ssmRechargeAccountService.select(rechargeAccount);
                            rechargeAccount = select.get(0);
                            rechargeAccount.setCardRestMoney(select.stream().map(RechargeAccount::getCardRestMoney).reduce(BigDecimal.ZERO,BigDecimal::add));
                            rechargeAccount.setCardGiftMoney(select.stream().map(RechargeAccount::getCardGiftMoney).reduce(BigDecimal.ZERO,BigDecimal::add));
                        RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeListRequest.getRechargeTypeId());
                        BigDecimal giftMoney = new BigDecimal("0");
                        if(rechargeType.getDonateType()!=null) {
                            if (rechargeType.getDonateType() == 0) {
                                giftMoney = rechargeType.getGiftMoney() == null ? BigDecimal.ZERO : rechargeType.getGiftMoney();
                            }
                            if (rechargeType.getDonateType() == 1) {
                                giftMoney = rechargeType.getRechargeMoney().multiply(rechargeType.getGiftMoney() == null ? BigDecimal.ZERO : rechargeType.getGiftMoney()).divide(new BigDecimal("100"));
                            }
                        }
                        chuangLanBeanSmsUtil.sendRechargeSmsNew(baseStore, rechargeListRequest.getMobilePhone(),rechargeAccount,rechargeListRequest.getCollectionAmount(),
                                giftMoney);
//                        chuangLanBeanSmsUtil.sendRechargeSms(baseStore, rechargeListRequest.getMobilePhone(), rechargeListRequest.getCollectionAmount());
                    } catch (SmsException e) {
                        log.error("SsmRechargeController.add:", e);
                    }
                }
            }
        }else {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }




    @ApiOperation(value = "单据导出", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/rechargeList/exportachis")
    public void exportachis(@RequestBody RechargeListRequest rechargeListRequest, 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/rechargeList.xlsx");
//            BeanUtils.copyProperties(projectTypeRequest, baseProjectType);
            List<ExcelRechargeList> excelBaseProjectTypeList = new ArrayList<>();
            List<RechargeList> list = ssmRechargeService.selectList(rechargeListRequest);
            if(list!=null && list.size()>0) {


//            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(RechargeList::getRechargeNum).collect(Collectors.toList());
                List<PayList> payListList = ssmPayService.selectList(courseNums);
                //查询管理层和高管
                List<Long> courseIds = list.stream().map(RechargeList::getId).collect(Collectors.toList());
                List<Salesman> salesmanList = ssmSalesmanService.selectList(courseIds);
                for (RechargeList executives : list) {
                    ExcelRechargeList excelBaseProjectType = new ExcelRechargeList();
                    BeanUtils.copyProperties(executives, excelBaseProjectType);
                    excelBaseProjectType.setPayType("");
                    if (excelBaseProjectType.getIsCancel() == 0) {
                        excelBaseProjectType.setIsCancelNew("正常");
                    } else {
                        excelBaseProjectType.setIsCancelNew("作废");
                    }
                    //设置赠送金额
                    RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(excelBaseProjectType.getRechargeTypeId());
                    excelBaseProjectType.setGiftMoney(rechargeType.getGiftMoney());
                    //设置到账赠送金额
                    excelBaseProjectType.setGiftAmount(excelBaseProjectType.getGiftAfterMoney().subtract(excelBaseProjectType.getGiftBeforeMoney()));
                    //设置门店编码
                    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.getRechargeNum())) {
                            excelBaseProjectType.setPayType(excelBaseProjectType.getPayType() + "-" + payList.getPayName() + ":" + payList.getPayMoney() + "元-");
                        }
                    }
                    //设置高管和管理层
                    List<Salesman> guanliceng = salesmanList.stream().filter(item -> (item.getOrderId().equals(executives.getId().toString())) && (item.getStaffType() == 1 || item.getStaffType().equals("1"))).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.getSaleAchievement();
                    BigDecimal commissionAmount = excelBaseProjectType.getSaleCommission();
                    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();
            // 别忘记关闭流
            if(excelWriter!=null) {
                excelWriter.finish();
            }
        }
    }



    //todo 买单
    @ApiOperation(value = "充值单添加  (门店端-充值单-充值单添加)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/add")
//    @RequestMapping("/addPromotionRecharge")
//    @RequestMapping("/addBySmsFix")
    public GenericResponse add(@RequestBody RechargeListRequest rechargeListRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        if(rechargeListRequest.getRechargeTypeName()==null||rechargeListRequest.getRechargeTypeName().equals("")){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"错误操作,请选择充值的类型");
            return genericResponse;
        }
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String staffPhone = SessionHelp.getLoginAccount(session);
        if(storeId==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请重新登录");
            return genericResponse;
        }
        rechargeListRequest.setStoreId(storeId);
        rechargeListRequest.setStoreName(storeName);
        rechargeListRequest.setStaffPhone(staffPhone);
        //添加高管的当前单据门店信息
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(SessionHelp.getStoreId(session));
        BaseStore baseStore1 = ssmBaseStoreService.selectOne(storeRequest);
        List<Salesman> salesmens = rechargeListRequest.getSalesmens();
        for (Salesman salesmen : salesmens) {
            salesmen.setStoreNum(baseStore1.getStoreNum());
            salesmen.setStoreName(baseStore1.getStoreName());
            salesmen.setStoreIdOrder(baseStore1.getId());
        }

        int i = 0;
        try {
            i = ssmRechargeService.addRecharge(rechargeListRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmRechargeController.add:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if(rechargeListRequest.getIsSendSms()==1){


            if (i > 0){
                //genericResponse.setCodeAndMsg(ResponseCode.OK);
                BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(rechargeListRequest.getStoreId());
                //设置短信账户 发送 否则不发送
                if (StringUtils.isNotBlank(baseStore.getSmsAccount()) && null != baseStore.getMessagingPlatform()) {
                    try {
                        if(rechargeListRequest.getIsAddition()==1){
                            //chuangLanBeanSmsUtil.sendRechargeSms(baseStore, rechargeListRequest.getMobilePhone(), rechargeListRequest.getCollectionAmount(),rechargeListRequest.getAdditionDate());
                        }else{
                            RechargeAccount rechargeAccount = new RechargeAccount();
                            rechargeAccount.setMemberId(rechargeListRequest.getMemberId());
//                            rechargeAccount.setRechargeTypeId(rechargeListRequest.getRechargeTypeId());
                            List<RechargeAccount> select = ssmRechargeAccountService.select(rechargeAccount);
                            rechargeAccount = select.get(0);
                            rechargeAccount.setCardRestMoney(select.stream().map(RechargeAccount::getCardRestMoney).reduce(BigDecimal.ZERO,BigDecimal::add));
                            rechargeAccount.setCardGiftMoney(select.stream().map(RechargeAccount::getCardGiftMoney).reduce(BigDecimal.ZERO,BigDecimal::add));
                            RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeListRequest.getRechargeTypeId());
                            BigDecimal giftMoney = new BigDecimal("0");
                            if(rechargeType.getDonateType()!=null) {
                                if (rechargeType.getDonateType() == 0) {
                                    giftMoney = rechargeType.getGiftMoney() == null ? BigDecimal.ZERO : rechargeType.getGiftMoney();
                                }
                                if (rechargeType.getDonateType() == 1) {
                                    giftMoney = rechargeType.getRechargeMoney().multiply(rechargeType.getGiftMoney() == null ? BigDecimal.ZERO : rechargeType.getGiftMoney()).divide(new BigDecimal("100"));
                                }
                            }
                            chuangLanBeanSmsUtil.sendRechargeSmsNew(baseStore, rechargeListRequest.getMobilePhone(),rechargeAccount,rechargeListRequest.getCollectionAmount(),
                                    giftMoney);
//                            chuangLanBeanSmsUtil.sendRechargeSmsNew(baseStore, rechargeListRequest.getMobilePhone(),rechargeAccount,rechargeListRequest.getCollectionAmount(),
//                                    giftMoney);
                        }
                        genericResponse.setCodeAndMsg(ResponseCode.OK);
                    } catch (SmsException e) {
                        genericResponse.setCodeAndMsg(ResponseCode.SMS_SEND_OK_EXCEPTION);
                        log.error("SsmRechargeController.add:", e);
                    }
                }else {
                    genericResponse.setCodeAndMsg(ResponseCode.SMS_NO_OK);
                }

            }
        }else {

            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "充值单添加  (门店端-充值单-充值单添加)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/addPromotionRecharge")
//    @RequestMapping("/add")
    public GenericResponse addPromotionRecharge(@RequestBody RechargeListRequest rechargeListRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        if(rechargeListRequest.getRechargeTypeName()==null||rechargeListRequest.getRechargeTypeName().equals("")){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"错误操作,请选择充值的类型");
            return genericResponse;
        }
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String staffPhone = SessionHelp.getLoginAccount(session);
        if(storeId==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请重新登录");
            return genericResponse;
        }
        rechargeListRequest.setStoreId(storeId);
        rechargeListRequest.setStoreName(storeName);
        rechargeListRequest.setStaffPhone(staffPhone);
        //添加高管的当前单据门店信息
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(SessionHelp.getStoreId(session));
        BaseStore baseStore1 = ssmBaseStoreService.selectOne(storeRequest);
        List<Salesman> salesmens = rechargeListRequest.getSalesmens();
        for (Salesman salesmen : salesmens) {
            salesmen.setStoreNum(baseStore1.getStoreNum());
            salesmen.setStoreName(baseStore1.getStoreName());
            salesmen.setStoreIdOrder(baseStore1.getId());
        }

        int i = 0;
        try {
            i = ssmRechargeService.addPromotionRecharge(rechargeListRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmRechargeController.add:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if(rechargeListRequest.getIsSendSms()==1){


            if (i > 0){
                //genericResponse.setCodeAndMsg(ResponseCode.OK);
                BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(rechargeListRequest.getStoreId());
                //设置短信账户 发送 否则不发送
                if (StringUtils.isNotBlank(baseStore.getSmsAccount()) && null != baseStore.getMessagingPlatform()) {
                    try {
                        if(rechargeListRequest.getIsAddition()==1){
                            //chuangLanBeanSmsUtil.sendRechargeSms(baseStore, rechargeListRequest.getMobilePhone(), rechargeListRequest.getCollectionAmount(),rechargeListRequest.getAdditionDate());
                        }else{
                            RechargeAccount rechargeAccount = new RechargeAccount();
                            rechargeAccount.setMemberId(rechargeListRequest.getMemberId());
                            rechargeAccount.setRechargeTypeId(rechargeListRequest.getRechargeTypeId());
                            rechargeAccount = ssmRechargeAccountService.selectOne(rechargeAccount);
                            RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeListRequest.getRechargeTypeId());
                            chuangLanBeanSmsUtil.sendRechargeSmsNew(baseStore, rechargeListRequest.getMobilePhone(),rechargeAccount,rechargeListRequest.getCollectionAmount(),
                                    rechargeType.getGiftMoney()==null? BigDecimal.ZERO:rechargeType.getGiftMoney());
//                        chuangLanBeanSmsUtil.sendRechargeSms(baseStore, rechargeListRequest.getMobilePhone(), rechargeListRequest.getCollectionAmount());
                        }
                        genericResponse.setCodeAndMsg(ResponseCode.OK);
                    } catch (SmsException e) {
                        genericResponse.setCodeAndMsg(ResponseCode.SMS_SEND_OK_EXCEPTION);
                        log.error("SsmRechargeController.add:", e);
                    }
                }else {
                    genericResponse.setCodeAndMsg(ResponseCode.SMS_NO_OK);
                }

            }
        }else {

            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }


    @ApiOperation(value = "充值单作废  (门店端-充值单-单据记录-充值单作废)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/cancel")
//    @RequestMapping("/cancelPromotionCourse")
    public GenericResponse cancel(@RequestBody RechargeListRequest rechargeListRequest,HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String staffPhone = SessionHelp.getLoginAccount(session);
        if(rechargeListRequest.getStoreId()==null||rechargeListRequest.getStoreName()==null){
            rechargeListRequest.setStoreId(storeId);
            rechargeListRequest.setStoreName(storeName);
        }


        rechargeListRequest.setStaffPhone(staffPhone);
        int i = 0;
        try {
            i = ssmRechargeService.cancel(rechargeListRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmRechargeController.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("/cancel")
    @RequestMapping("/cancelPromotionCourse")
    public GenericResponse cancelPromotionCourse(@RequestBody RechargeListRequest rechargeListRequest,HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String staffPhone = SessionHelp.getLoginAccount(session);
        if(rechargeListRequest.getStoreId()==null||rechargeListRequest.getStoreName()==null){
            rechargeListRequest.setStoreId(storeId);
            rechargeListRequest.setStoreName(storeName);
        }


        rechargeListRequest.setStaffPhone(staffPhone);
        int i = 0;
        try {
            i = ssmRechargeService.cancelPromotionCourse(rechargeListRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmRechargeController.cancel:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0){
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }
}
