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.manage.entity.*;
import com.ssm.manage.excelEntity.ExcelCardChange;
import com.ssm.manage.query.*;
import com.ssm.manage.response.CardChangeInProjectResponse;
import com.ssm.manage.response.CardChangeOutProjectResponse;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
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.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Api(value = "加价Controller",tags = {"加价相关接口"})
@RestController
@RequestMapping("/demay/ssm/cardChange")
@Slf4j
public class SsmCardChangeController {
    @Autowired
    private SsmCardChangeService ssmCardChangeService;

    @Autowired
    private SsmCardChangeInProjectService ssmCardChangeInProjectService;

    @Autowired
    private SsmPayService ssmPayService;

    @Autowired
    private SsmSalesmanService ssmSalesmanService;

    @Autowired
    private SsmCardChangeOutProjectService ssmCardChangeOutProjectService;

    @Autowired
    private SsmProjectService ssmProjectService;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @ApiOperation(value = "加价转疗程分页列表查询 门店端-加价-加价转疗程分页列表查询",httpMethod = "POST", response = PageResponse.class)
    @RequestMapping("/page")
    public PageResponse selectPage(@RequestBody CardChangeListRequest cardChangeListRequest, HttpSession session) {
        PageResponse<CardChangeList> pageResponse = new PageResponse<>();
        PageInfo<CardChangeList> pageInfo = new PageInfo<>();
        cardChangeListRequest.setStoreId(SessionHelp.getStoreId(session));
        try {
            pageInfo = ssmCardChangeService.selectPage(cardChangeListRequest);
        } catch (Exception e) {
            log.error("SsmCardChangeController.selectPage", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }
    @Autowired
    private SsmSysRoleStoreService ssmSysRoleStoreService;
    @ApiOperation(value = "加价转疗程分页列表查询 门店端-加价-加价转疗程分页列表查询",httpMethod = "POST", response = PageResponse.class)
    @RequestMapping("/pageNew")
    public PageResponse selectPageNew(@RequestBody CardChangeListRequest cardChangeListRequest, HttpSession session) {
        PageResponse<CardChangeList> pageResponse = new PageResponse<>();
        PageInfo<CardChangeList> pageInfo = new PageInfo<>();
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(SessionHelp.getStoreId(session));
        if(baseStore.getParentId()==null) {
            if (null == cardChangeListRequest.getStoreList() || cardChangeListRequest.getStoreList().size() == 0) {
                cardChangeListRequest.setSelectType(0);
                SysRoleStoreRequest sysStoreRole = new SysRoleStoreRequest();
                sysStoreRole.setRoleId(cardChangeListRequest.getRoleId());
                PageInfo<SysRoleStore> sysRoleStorePageInfo = ssmSysRoleStoreService.selectPage(sysStoreRole);
                List<Long> collect = sysRoleStorePageInfo.getList().stream().map(item -> item.getStoreId()).collect(Collectors.toList());
                cardChangeListRequest.setStoreList(collect);
//            cardChangeListRequest.setStoreId(SessionHelp.getStoreId(session));
            }else {
                cardChangeListRequest.setSelectType(0);
                cardChangeListRequest.setStoreId(SessionHelp.getStoreId(session));
            }
        }else {
            cardChangeListRequest.setSelectType(1);
            cardChangeListRequest.setStoreId(SessionHelp.getStoreId(session));
        }
        try {
            cardChangeListRequest.setCourseType(1);
            pageInfo = ssmCardChangeService.selectPageNew(cardChangeListRequest);
//            List<CardChangeList> list = pageInfo.getList();
//            List<CardChangeList> zlc = list.stream().filter(item -> item.getDocNum().startsWith("ZLC")).collect(Collectors.toList());
//            pageInfo.setList(zlc);
        } catch (Exception e) {
            log.error("SsmCardChangeController.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("/pageNewLCNT")
    public PageResponse pageNewLCNT(@RequestBody CardChangeListRequest cardChangeListRequest, HttpSession session) {
        PageResponse<CardChangeList> pageResponse = new PageResponse<>();
        PageInfo<CardChangeList> pageInfo = new PageInfo<>();
        if(null == cardChangeListRequest.getStoreList()|| cardChangeListRequest.getStoreList().size()==0){
            cardChangeListRequest.setSelectType(1);
            cardChangeListRequest.setStoreId(SessionHelp.getStoreId(session));
        }else{
            cardChangeListRequest.setSelectType(0);
        }

        try {
            cardChangeListRequest.setCourseType(0);
            pageInfo = ssmCardChangeService.selectPageNew(cardChangeListRequest);
//            List<CardChangeList> list = pageInfo.getList();
//            List<CardChangeList> zlc = list.stream().filter(item -> item.getDocNum().startsWith("LCNT")).collect(Collectors.toList());
//            pageInfo.setList(zlc);
        } catch (Exception e) {
            log.error("SsmCardChangeController.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("/pageDetail")
    public PageResponse pageDetail(@RequestBody CardChangeListRequest cardChangeListRequest, HttpSession session) {
        PageResponse<CardChangeList> pageResponse = new PageResponse<>();
        PageInfo<CardChangeList> pageInfo = new PageInfo<>();
        try {
            pageInfo = ssmCardChangeService.pageDetail(cardChangeListRequest);
        } catch (Exception e) {
            log.error("SsmCardChangeController.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("/inPro")
    public GenericResponse inPro(@RequestBody CardChangeListRequest cardChangeListRequest, HttpSession session){
        GenericResponse<CardChangeInProjectResponse> genericResponse = new GenericResponse<>();
        List<CardChangeInProjectResponse> list = new ArrayList<>();
        cardChangeListRequest.setStoreId(SessionHelp.getStoreId(session));
        try {
            list = ssmCardChangeInProjectService.selectList(cardChangeListRequest);
        } catch (Exception e) {
            log.error("SsmCardChangeController.inPro", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setRows(list);
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }

    @ApiOperation(value = "加价转疗程转出疗程明细查询 门店端-加价-加价转疗程转出疗程明细查询",httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/outPro")
    public GenericResponse outPro(@RequestBody CardChangeOutProjectRequest cardChangeOutProjectRequest, HttpSession session){
        /*GenericResponse<CardChangeOutProject> genericResponse = new GenericResponse<>();
        List<CardChangeOutProject> list = new ArrayList<>();
        //cardChangeOutProjectRequest.setStoreId(SessionHelp.getStoreId(session));
        try {
            list = ssmCardChangeOutProjectService.selectList(cardChangeOutProjectRequest);
        } catch (Exception e) {
            log.error("SsmCardChangeController.outPro", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setRows(list);
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;*/
        GenericResponse<CardChangeOutProjectResponse> genericResponse = new GenericResponse<>();
        List<CardChangeOutProjectResponse> list = new ArrayList<>();
        //cardChangeOutProjectRequest.setStoreId(SessionHelp.getStoreId(session));
        try {
            list = ssmCardChangeOutProjectService.selectList1(cardChangeOutProjectRequest);
        } catch (Exception e) {
            log.error("SsmCardChangeController.outPro", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setRows(list);
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }

    @ApiOperation(value = "加价转疗程单据添加 门店端-加价-加价转疗程单据添加",httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/addNew")
    public GenericResponse addNew(@RequestBody CardChangeListRequest cardChangeListRequest, HttpSession session){
        GenericResponse genericResponse = new GenericResponse();
        if(0==cardChangeListRequest.getCardChangeOutProjectRequests().size()){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"未选择转出项目");
            return genericResponse;
        }

        int i = 0;
        if(cardChangeListRequest.getStoreId()==null){
            cardChangeListRequest.setStoreId(SessionHelp.getStoreId(session));
            cardChangeListRequest.setStoreName(SessionHelp.getStoreName(session));
        }


        cardChangeListRequest.setStaffPhone(SessionHelp.getLoginAccount(session));
        List<Salesman> salesmens = cardChangeListRequest.getCardChangeInProjectRequest().getSalesmens();
        StoreRequest storeRequest = new StoreRequest();
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        storeRequest.setId(SessionHelp.getStoreId(session));
        BaseStore baseStore1 = ssmBaseStoreService.selectOne(storeRequest);
        for (Salesman salesmen : salesmens) {
            salesmen.setStoreNum(baseStore1.getStoreNum());
            salesmen.setStoreName(baseStore1.getStoreName());
            salesmen.setStoreIdOrder(baseStore1.getId());
        }
        try {
            if(cardChangeListRequest.getChangeOutMoney().longValue()<0||cardChangeListRequest.getChangeInPayMoney().longValue()<0){
                throw new SmsException("010000","操作失败，不能输入负数");
            }
            i = ssmCardChangeService.addNew(cardChangeListRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmCardChangeController.add", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
            //TODO 加价短信模板还未申请 暂不处理
//            //发送短信
//            BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(SessionHelp.getStoreId(session));
//            //设置短信账户 发送 否则不发送
//            if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
//                try {
//                    ChuangLanSmsUtil.sendCourseSms(baseStore, cardChangeListRequest.getMobilePhone(), cardChangeListRequest.getCardChangeInProjectRequest().getProjectName());
//                } catch (IOException e) {
//                    log.error("SsmCardChangeController.add:", e);
//                } catch (SmsException e) {
//                    log.error("SsmCardChangeController.add:", e);
//                }
//            }
        }
        return genericResponse;
    }
    @ApiOperation(value = "疗程内调 门店端-加价-加价转疗程单据添加",httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/courseNT")
    public GenericResponse courseNT(@RequestBody CardChangeListRequest cardChangeListRequest, HttpSession session){
        GenericResponse genericResponse = new GenericResponse();
        if(0==cardChangeListRequest.getCardChangeOutProjectRequests().size()){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"未选择转出项目");
            return genericResponse;
        }

        int i = 0;
        if(cardChangeListRequest.getStoreId()==null){
            if(SessionHelp.getStoreId(session)==null){
                genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
                return genericResponse;
            }
            cardChangeListRequest.setStoreId(SessionHelp.getStoreId(session));
            cardChangeListRequest.setStoreName(SessionHelp.getStoreName(session));
        }


        cardChangeListRequest.setStaffPhone(SessionHelp.getLoginAccount(session));
        List<Salesman> salesmens = cardChangeListRequest.getCardChangeInProjectRequest().getSalesmens();
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(SessionHelp.getStoreId(session));
        BaseStore baseStore1 = ssmBaseStoreService.selectOne(storeRequest);
        for (Salesman salesmen : salesmens) {
            salesmen.setStoreNum(baseStore1.getStoreNum());
            salesmen.setStoreName(baseStore1.getStoreName());
            salesmen.setStoreIdOrder(baseStore1.getId());
        }
        try {
            if(cardChangeListRequest.getChangeOutMoney().longValue()<0||cardChangeListRequest.getChangeInPayMoney().longValue()<0){
                throw new SmsException("010000","操作失败，不能输入负数");
            }
            i = ssmCardChangeService.add(cardChangeListRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmCardChangeController.add", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
            //TODO 加价短信模板还未申请 暂不处理
//            //发送短信
//            BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(SessionHelp.getStoreId(session));
//            //设置短信账户 发送 否则不发送
//            if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
//                try {
//                    ChuangLanSmsUtil.sendCourseSms(baseStore, cardChangeListRequest.getMobilePhone(), cardChangeListRequest.getCardChangeInProjectRequest().getProjectName());
//                } catch (IOException e) {
//                    log.error("SsmCardChangeController.add:", e);
//                } catch (SmsException e) {
//                    log.error("SsmCardChangeController.add:", e);
//                }
//            }
        }
        return genericResponse;
    }
//

    @ApiOperation(value = "加价转疗程单据添加 门店端-加价-加价转疗程单据添加",httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/add")
    public GenericResponse add(@RequestBody CardChangeListRequest cardChangeListRequest, HttpSession session){
        GenericResponse genericResponse = new GenericResponse();
        if(0==cardChangeListRequest.getCardChangeOutProjectRequests().size()){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"未选择转出项目");
            return genericResponse;
        }

        int i = 0;
        if(cardChangeListRequest.getStoreId()==null){
            if(SessionHelp.getStoreId(session)==null){
                genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
                return genericResponse;
            }
            cardChangeListRequest.setStoreId(SessionHelp.getStoreId(session));
            cardChangeListRequest.setStoreName(SessionHelp.getStoreName(session));
        }


        cardChangeListRequest.setStaffPhone(SessionHelp.getLoginAccount(session));
        List<Salesman> salesmens = cardChangeListRequest.getCardChangeInProjectRequest().getSalesmens();
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(SessionHelp.getStoreId(session));
        BaseStore baseStore1 = ssmBaseStoreService.selectOne(storeRequest);
        for (Salesman salesmen : salesmens) {
            salesmen.setStoreNum(baseStore1.getStoreNum());
            salesmen.setStoreName(baseStore1.getStoreName());
            salesmen.setStoreIdOrder(baseStore1.getId());
        }
        try {
            if(cardChangeListRequest.getChangeOutMoney().longValue()<0||cardChangeListRequest.getChangeInPayMoney().longValue()<0){
                throw new SmsException("010000","操作失败，不能输入负数");
            }
            i = ssmCardChangeService.add(cardChangeListRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmCardChangeController.add", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
            //TODO 加价短信模板还未申请 暂不处理
//            //发送短信
//            BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(SessionHelp.getStoreId(session));
//            //设置短信账户 发送 否则不发送
//            if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
//                try {
//                    ChuangLanSmsUtil.sendCourseSms(baseStore, cardChangeListRequest.getMobilePhone(), cardChangeListRequest.getCardChangeInProjectRequest().getProjectName());
//                } catch (IOException e) {
//                    log.error("SsmCardChangeController.add:", e);
//                } catch (SmsException e) {
//                    log.error("SsmCardChangeController.add:", e);
//                }
//            }
        }
        return genericResponse;
    }
//
//    @ApiOperation(value = "加价转疗程单据添加 门店端-加价-加价转疗程单据添加",httpMethod = "POST", response = GenericResponse.class)
//    @RequestMapping("/add")
//    public GenericResponse add(@RequestBody CardChangeListRequest cardChangeListRequest, HttpSession session){
//        GenericResponse genericResponse = new GenericResponse();
//        if(0==cardChangeListRequest.getCardChangeOutProjectRequests().size()){
//            genericResponse.setCodeAndMsg(ResponseCode.MSG,"未选择转出项目");
//            return genericResponse;
//        }
//
//        int i = 0;
//        if(cardChangeListRequest.getStoreId()==null){
//            cardChangeListRequest.setStoreId(SessionHelp.getStoreId(session));
//            cardChangeListRequest.setStoreName(SessionHelp.getStoreName(session));
//        }
//
//
//        cardChangeListRequest.setStaffPhone(SessionHelp.getLoginAccount(session));
//        List<Salesman> salesmens = cardChangeListRequest.getCardChangeInProjectRequest().getSalesmens();
//        StoreRequest storeRequest = new StoreRequest();
//        storeRequest.setId(SessionHelp.getStoreId(session));
//        BaseStore baseStore1 = ssmBaseStoreService.selectOne(storeRequest);
//        for (Salesman salesmen : salesmens) {
//            salesmen.setStoreNum(baseStore1.getStoreNum());
//            salesmen.setStoreName(baseStore1.getStoreName());
//            salesmen.setStoreIdOrder(baseStore1.getId());
//        }
//        try {
//            if(cardChangeListRequest.getChangeOutMoney().longValue()<0||cardChangeListRequest.getChangeInPayMoney().longValue()<0){
//                throw new SmsException("010000","操作失败，不能输入负数");
//            }
//            i = ssmCardChangeService.addNew(cardChangeListRequest);
//        }catch (SmsException e){
//            genericResponse.setCodeAndMsg(e);
//            return genericResponse;
//        }catch (Exception e){
//            log.error("SsmCardChangeController.add", e);
//            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
//            return genericResponse;
//        }
//        if (i > 0) {
//            genericResponse.setCodeAndMsg(ResponseCode.OK);
//            //TODO 加价短信模板还未申请 暂不处理
////            //发送短信
////            BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(SessionHelp.getStoreId(session));
////            //设置短信账户 发送 否则不发送
////            if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
////                try {
////                    ChuangLanSmsUtil.sendCourseSms(baseStore, cardChangeListRequest.getMobilePhone(), cardChangeListRequest.getCardChangeInProjectRequest().getProjectName());
////                } catch (IOException e) {
////                    log.error("SsmCardChangeController.add:", e);
////                } catch (SmsException e) {
////                    log.error("SsmCardChangeController.add:", e);
////                }
////            }
//        }
//        return genericResponse;
//    }

    @ApiOperation(value = "加价转疗程单据业务员修改 门店端-加价-加价转疗程单据业务员修改",httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/updateStaff")
    public GenericResponse updateStaff(@RequestBody CardChangeListRequest cardChangeListRequest, HttpSession session){
        GenericResponse genericResponse = new GenericResponse();
        int i = 0;
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        cardChangeListRequest.setStoreId(SessionHelp.getStoreId(session));
        cardChangeListRequest.getCardChangeInProjectRequest().setStoreId(SessionHelp.getStoreId(session));
        try {
            i = ssmCardChangeService.updateStaff(cardChangeListRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmCardChangeController.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("/cancel")
    public GenericResponse cancel(@RequestBody CardChangeListRequest cardChangeListRequest, HttpSession session){
        GenericResponse genericResponse = new GenericResponse();
        int i = 0;
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        cardChangeListRequest.setStoreId(SessionHelp.getStoreId(session));
        cardChangeListRequest.setStoreName(SessionHelp.getStoreName(session));
        cardChangeListRequest.setStaffPhone(SessionHelp.getLoginAccount(session));
        try {
            i = ssmCardChangeService.cancel(cardChangeListRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmCardChangeController.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("/NTAdd")
    public GenericResponse NTAdd(@RequestBody CardChangeListRequest cardChangeListRequest, HttpSession session){
        GenericResponse genericResponse = new GenericResponse();
        int i = 0;
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        cardChangeListRequest.setStoreId(SessionHelp.getStoreId(session));
        cardChangeListRequest.setStoreName(SessionHelp.getStoreName(session));
        cardChangeListRequest.setStaffPhone(SessionHelp.getLoginAccount(session));
        try {
            i = ssmCardChangeService.NTAdd(cardChangeListRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmCardChangeController.NTAdd", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
            //TODO 内调短信模板还未申请 暂不处理
//            //发送短信
//            BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(SessionHelp.getStoreId(session));
//            //设置短信账户 发送 否则不发送
//            if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
//                try {
//                    ChuangLanSmsUtil.sendCourseSms(baseStore, cardChangeListRequest.getMobilePhone(), cardChangeListRequest.getCardChangeInProjectRequest().getProjectName());
//                } catch (IOException e) {
//                    log.error("SsmCardChangeController.add:", e);
//                } catch (SmsException e) {
//                    log.error("SsmCardChangeController.add:", e);
//                }
//            }
        }
        return genericResponse;
    }


    @ApiOperation(value = "内调单据送审 门店端-内调-内调单据送审",httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/sendAudit")
    public GenericResponse sendAudit(@RequestBody CardChangeListRequest cardChangeListRequest, HttpSession session){
        GenericResponse genericResponse = new GenericResponse();
        int i = 0;
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        cardChangeListRequest.setStoreId(SessionHelp.getStoreId(session));
        cardChangeListRequest.setStoreName(SessionHelp.getStoreName(session));
        try {
            i = ssmCardChangeService.sendAudit(cardChangeListRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmCardChangeController.sendAudit", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "内调单据回收 门店端-内调-内调单据回收",httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/revoke")
    public GenericResponse revoke(@RequestBody CardChangeListRequest cardChangeListRequest, HttpSession session){
        GenericResponse genericResponse = new GenericResponse();
        int i = 0;
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        cardChangeListRequest.setStoreId(SessionHelp.getStoreId(session));
        cardChangeListRequest.setStoreName(SessionHelp.getStoreName(session));
        try {
            i = ssmCardChangeService.revoke(cardChangeListRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmCardChangeController.revoke", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "内调单据审核 门店端-内调-内调单据审核",httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/audit")
    public GenericResponse audit(@RequestBody CardChangeListRequest cardChangeListRequest, HttpSession session){
        GenericResponse genericResponse = new GenericResponse();
        int i = 0;
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        cardChangeListRequest.setStoreId(SessionHelp.getStoreId(session));
        cardChangeListRequest.setStoreName(SessionHelp.getStoreName(session));
        cardChangeListRequest.setStaffPhone(SessionHelp.getLoginAccount(session));
        try {
            i = ssmCardChangeService.audit(cardChangeListRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmCardChangeController.audit", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "内调单据反审核 门店端-内调-内调单据反审核",httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/unAudit")
    public GenericResponse unAudit(@RequestBody CardChangeListRequest cardChangeListRequest, HttpSession session){
        GenericResponse genericResponse = new GenericResponse();
        int i = 0;
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        cardChangeListRequest.setStoreId(SessionHelp.getStoreId(session));
        cardChangeListRequest.setStoreName(SessionHelp.getStoreName(session));
        cardChangeListRequest.setStaffPhone(SessionHelp.getLoginAccount(session));
        try {
            i = ssmCardChangeService.unAudit(cardChangeListRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmCardChangeController.unAudit", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "加价转疗程状态修改",httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/updateState")
    public GenericResponse updateState(@RequestBody CardChangeListRequest cardChangeListRequest, HttpSession session){
        GenericResponse genericResponse = new GenericResponse();
        int i = 0;
        String loginAccount = SessionHelp.getLoginAccount(session);
        try {
            i = ssmCardChangeService.updateState(cardChangeListRequest,loginAccount);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmCardChangeController.unAudit", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }
    @ApiOperation(value = "单据导出", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/cardChange/exportachis")
    public void exportachis(@RequestBody CardChangeListRequest cardChangeListRequest, 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/cardChangeList.xlsx");
//            BeanUtils.copyProperties(projectTypeRequest, baseProjectType);
            List<ExcelCardChange> excelBaseProjectTypeList = new ArrayList<>();
            //查询所有转入的疗程信息
            List<CardChangeInProject> list = ssmCardChangeInProjectService.selectListNew(cardChangeListRequest);
            if(list!=null && list.size()>0) {
                List<CardChangeList> cardChangeLists = ssmCardChangeService.selectNew(cardChangeListRequest);
                List<CardChangeOutProject> cardChangeOutProjects = ssmCardChangeOutProjectService.selectNew(cardChangeListRequest);
//            salesmen = ssmSalesmanService.selectList(salesman);
                //所有门店
                List<BaseStore> select = ssmBaseStoreService.select(null);
                //所有项目id
                List<Long> projectIds = list.stream().filter(cardChangeInProject -> cardChangeInProject.getProjectId() != null).map(CardChangeInProject::getProjectId).collect(Collectors.toList());
                projectIds.addAll(cardChangeOutProjects.stream().filter(cardChangeInProject -> cardChangeInProject.getCourseProjectId() != null).map(CardChangeOutProject::getCourseProjectId).collect(Collectors.toList()));
                List<BaseProject> projectList = ssmProjectService.selectList(projectIds);
                //所有单据号
                List<String> courseNums = list.stream().map(CardChangeInProject::getDocNum).collect(Collectors.toList());
                List<PayList> payListList = ssmPayService.selectList(courseNums);
                //查询管理层和高管
                List<Long> courseIds = list.stream().map(CardChangeInProject::getId).collect(Collectors.toList());
                List<Salesman> salesmanList = ssmSalesmanService.selectList(courseIds);
                for (CardChangeInProject executives : list) {
                    ExcelCardChange excelBaseProjectType = new ExcelCardChange();
                    BeanUtils.copyProperties(executives, excelBaseProjectType);
                    excelBaseProjectType.setPayType("");
                    CardChangeList cardChangeList = null;
                    List<CardChangeOutProject> collect = cardChangeOutProjects.stream().filter(item -> item.getDocNum().equals(executives.getDocNum())).collect(Collectors.toList());
                    Map<String, CardChangeOutProject> projectMap = new HashMap<>();
                    if (collect != null && collect.size() > 0) {
                        for (CardChangeOutProject cardChangeOutProject : collect) {
                            for (BaseProject baseProject : projectList) {
                                if (cardChangeOutProject.getCourseProjectId() == baseProject.getId() || cardChangeOutProject.getCourseProjectId().toString().equals(baseProject.getId().toString())) {
                                    projectMap.put(baseProject.getProjectNum(), cardChangeOutProject);
                                }
                            }
                        }
                    }
                    Iterator<Map.Entry<String, CardChangeOutProject>> iterator = projectMap.entrySet().iterator();
                    String changeOutProject = "";
                    while (iterator.hasNext()) {
                        Map.Entry<String, CardChangeOutProject> next = iterator.next();
                        changeOutProject = changeOutProject + next.getKey() + "-";
                        changeOutProject = changeOutProject + next.getValue().getCourseProjectName() + "-";
                        changeOutProject = changeOutProject + next.getValue().getChangeOutTime() + "次-";
                    }
                    for (CardChangeList changeList : cardChangeLists) {
                        if (changeList.getDocNum().equals(executives.getDocNum())) {
                            cardChangeList = changeList;
                        }
                    }
                    excelBaseProjectType.setChangeOutProject(changeOutProject);
                    BigDecimal coopAchi = BigDecimal.ZERO;
                    if (executives.getProjectId() != null) {
                        for (BaseProject baseProject : projectList) {
                            if (executives.getProjectId().compareTo(baseProject.getId())==0 || executives.getProjectId().equals(baseProject.getId())) {
                                if(baseProject.getIsCooperation()!=null&&baseProject.getIsCooperation()==1){
                                    //判断转入的疗程项目是否是合作项目
                                    if(baseProject.getSmokeCommissionWay()!=null && baseProject.getSmokeCommissionWay()==1){

                                        coopAchi = cardChangeList.getChangeInPayMoney().multiply(baseProject.getBrokerage()).divide(new BigDecimal("100"),4,BigDecimal.ROUND_HALF_UP);
                                    }

                                    else if(baseProject.getSmokeCommissionWay()!=null && baseProject.getSmokeCommissionWay()==0) {
                                        coopAchi =  baseProject.getBrokerage().divide(excelBaseProjectType.getChangeInMoney(),4,BigDecimal.ROUND_HALF_UP).multiply(cardChangeList.getChangeInPayMoney());
                                    }
                                }
                                excelBaseProjectType.setProjectNum(baseProject.getProjectNum());
                            }
                        }
                    }

                    //是否欠款
                    if (excelBaseProjectType.getDebtMoney().compareTo(BigDecimal.ZERO) == 1) {
                        excelBaseProjectType.setIsDebtNew("是");
                    } else excelBaseProjectType.setIsDebtNew("否");
                    //状态
                    if (cardChangeList != null) {
                        switch (cardChangeList.getState()) {
                            case 0:
                                excelBaseProjectType.setStateNew("新建");
                                break;
                            case 1:
                                excelBaseProjectType.setStateNew("送审");
                                break;
                            case 2:
                                excelBaseProjectType.setStateNew("回收");
                                break;
                            case 3:
                                excelBaseProjectType.setStateNew("已审核");
                                break;
                            case 4:
                                excelBaseProjectType.setStateNew("反审核");
                                break;
                        }
                    }
                    //设置赠送金额
                    //设置门店编码
                    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.getDocNum())) {
                            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());
                            }
                        }
                    }
                    //设置销售人员业绩和提成
                    excelBaseProjectType.setChangeInPayMoney(cardChangeList.getChangeInPayMoney());
                    excelBaseProjectType.setChangeOutMoney(cardChangeList.getChangeOutMoney());

                    BigDecimal achievementAmount = excelBaseProjectType.getChangeInPayMoney().subtract(coopAchi).multiply(excelBaseProjectType.getSalesAchievement());
                    BigDecimal commissionAmount = achievementAmount.multiply(excelBaseProjectType.getSalesCommission());
                    excelBaseProjectType.setAchievementAmount(achievementAmount);
                    excelBaseProjectType.setCommissionAmount(commissionAmount);
                    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();
        }
    }
}
