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.core.util.StrComparatorUtils;
import com.ssm.core.utils.AESUtils;
import com.ssm.core.utils.ChuangLanBeanSmsUtil;
import com.ssm.core.utils.StoreParaUtils;
import com.ssm.manage.entity.*;
import com.ssm.manage.excelEntity.ExcelDepart;
import com.ssm.manage.excelEntity.ExcelStaffAchi;
import com.ssm.manage.excelEntity.ExcelStaffOrder;
import com.ssm.manage.extendEntity.AchiCommEntity;
import com.ssm.manage.extendEntity.StaffStatistic;
import com.ssm.manage.query.*;
import com.ssm.manage.response.*;
import com.ssm.manage.service.*;
import com.ssm.manage.utils.Constant;
import com.ssm.manage.utils.SessionHelp;
import com.ssm.util.RedisClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ObjectUtils;
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.RequestMethod;
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.*;
import java.util.concurrent.TimeUnit;

@Api(value="员工controller",tags={"员工相关接口"})
@RestController
@RequestMapping("/demay/ssm/staff")
@Slf4j
public class SsmStaffController {
    @Autowired
    private SsmBaseStaffService ssmBaseStaffService;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmStaffSalaryService ssmStaffSalaryService;

    @Autowired
    private SsmMemberLoginService ssmMemberLoginService;

    @Autowired
    private SsmStoreStatisticService ssmStoreStatisticService;

    @Autowired
    private SsmStoreMemberService ssmStoreMemberService;

    @Autowired
    private ChuangLanBeanSmsUtil chuangLanBeanSmsUtil;

    @Autowired
    private RedisClient<StaffResponse> redisClient;
    @Autowired
    private RedisClient<String> stringRedisClient;

    @ApiOperation(value = "分页查询员工信息  门店端-员工-分页查询员工信息",httpMethod = "POST",notes = "",response = PageResponse.class)
    @RequestMapping("/page")
    public PageResponse selectPage(@RequestBody StaffRequest staffRequest,HttpSession session){
        PageResponse<StaffResponse> pageResponse = new PageResponse<>();
        PageInfo<StaffResponse> pageInfo = new PageInfo<>();
        if(null == staffRequest.getStoreId()){
            staffRequest.setStoreId(SessionHelp.getStoreId(session));
        }
        try {
            pageInfo = ssmBaseStaffService.selectPage(staffRequest);
        }catch (Exception e){
            log.error("SsmStaffController.selectPage", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setPageInfo(pageInfo);
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;
    }

    @ApiOperation(value = "分页查询员工信息  门店端-员工-分页查询员工信息",httpMethod = "POST",notes = "",response = PageResponse.class)
    @RequestMapping("/pageNew")
    public PageResponse selectPageNew(@RequestBody StaffRequest staffRequest,HttpSession session){
        PageResponse<StaffResponse> pageResponse = new PageResponse<>();
        PageInfo<StaffResponse> pageInfo = new PageInfo<>();
        if(null == staffRequest.getStoreId()){
            staffRequest.setStoreId(SessionHelp.getStoreId(session));
        }
        try {
            pageInfo = ssmBaseStaffService.selectPageNew(staffRequest);
        }catch (Exception e){
            log.error("SsmStaffController.selectPage", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setPageInfo(pageInfo);
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;
    }

    @ApiOperation(value = "新增角色或者删除角色  门店端-员工-分页查询员工信息",httpMethod = "POST",notes = "",response = PageResponse.class)
    @RequestMapping("/staffAddRole")
    //修改角色
    public PageResponse staffAddRole(@RequestBody StaffRequest staffRequest,HttpSession session){
        PageResponse<StaffResponse> pageResponse = new PageResponse<>();
        if(null == staffRequest.getStoreId()){
            staffRequest.setStoreId(SessionHelp.getStoreId(session));
        }
        try {
              ssmBaseStaffService.staffAddRole(staffRequest);
        }catch (Exception e){
            log.error("SsmStaffController.selectPage", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;
    }

    @ApiOperation(value = "分页查询员工信息  门店端-员工-分页查询员工信息",httpMethod = "POST",notes = "",response = PageResponse.class)
    @RequestMapping("/parentsStaff")
    public PageResponse parentsStaff(@RequestBody StaffRequest staffRequest,HttpSession session){
        PageResponse<StaffResponse> pageResponse = new PageResponse<>();
        PageInfo<StaffResponse> pageInfo = new PageInfo<>();
        if(null == staffRequest.getStoreId()){
            staffRequest.setStoreId(SessionHelp.getStoreId(session));
        }
        try {
            pageInfo = ssmBaseStaffService.parentsStaff(staffRequest);
        }catch (Exception e){
            log.error("SsmStaffController.selectPage", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setPageInfo(pageInfo);
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;
    }


    @ApiOperation(value = "查询员工明细  门店端-员工-查询员工明细", httpMethod = "POST", response = GenericResponse.class, notes = "")
    @RequestMapping("/selectOne")
    public GenericResponse selectOne(@RequestBody StaffRequest staffRequest) {
        GenericResponse<BaseStaff> genericResponse = new GenericResponse();
        BaseStaff baseStaff = new BaseStaff();
        try {
            baseStaff = ssmBaseStaffService.selectOne(staffRequest);
        } catch (Exception e) {
            log.error("SsmStaffController.selectOne:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }

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

    @ApiOperation(value = "添加员工  门店端-员工-添加员工", httpMethod = "POST", response = GenericResponse.class, notes = "")
    @RequestMapping("/add")
    //todo 新增员工
    public GenericResponse add(@RequestBody StaffRequest staffRequest, HttpSession session) {
        GenericResponse<BaseStaff> genericResponse = new GenericResponse();
//        if (StringUtils.isBlank(staffRequest.getMobilePhone())) {
//            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "手机号码");
//            return genericResponse;
//        }
//        if (!CommonUtils.isMobile(staffRequest.getMobilePhone())) {
//            genericResponse.setCodeAndMsg(ResponseCode.NOT_MEET_REQUIREMENTS_S, "手机号码");
//            return genericResponse;
//        }
//        if (StringUtils.isBlank(staffRequest.getIdentityCard())) {
//            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "身份证号");
//            return genericResponse;
//        }
//        if (!CommonUtils.isIdentityCard(staffRequest.getIdentityCard())) {
//            genericResponse.setCodeAndMsg(ResponseCode.NOT_MEET_REQUIREMENTS_S, "身份证号");
//            return genericResponse;
//        }
        String password = ObjectUtils.toString((int)((Math.random()*9+1)*1000));
        staffRequest.setPassword(AESUtils.encrypt(password));
        Long storeId = SessionHelp.getStoreId(session);
        Long storeIds = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String phone = SessionHelp.getLoginAccount(session);
        staffRequest.setStoreName(storeName);
        staffRequest.setStoreId(storeId);
        if(staffRequest.getBaseSalary()==null){
            staffRequest.setBaseSalary(new BigDecimal("0"));
        }

        int i = 0;
        try {
            i = ssmBaseStaffService.addStaff(staffRequest,phone);
            StoreRequest storeRequest = new StoreRequest();
            storeRequest.setId(storeId);
            List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
            for (BaseStores pagesorganization : pagesorganizations) {
                if(null == pagesorganization.getParentId()){
                    storeIds =pagesorganization.getId();
                }
            }
            StoreParament parament = StoreParaUtils.getStorePara(storeIds, Constant.Employees_SMS);
            if(null == parament){
                throw new SmsException(ResponseCode.MSG,"员工是否发送短信参数未设置");
            }
            if(null == parament.getParamentValue()){
                throw new SmsException(ResponseCode.MSG,"员工是否发送短信参数未设置");
            }
        } catch (SmsException e){
            log.error("SsmStaffController.add:",e);
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e) {
            log.error("SsmStaffController.add:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
            BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(staffRequest.getStoreId());
            //设置短信账户 发送 否则不发送
            if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
                StoreParament parament = StoreParaUtils.getStorePara(storeIds, Constant.Employees_SMS);
                if(parament.getParamentValue().equals("0")){
                    try {
                        chuangLanBeanSmsUtil.sendStaffInitPwdSms(baseStore, staffRequest.getMobilePhone(), Integer.parseInt(password));
                    } catch (IOException e) {
                        log.error("SsmStaffController.add:", e);
                    } catch (SmsException e) {
                        log.error("SsmStaffController.add:", e);
                    }
                }

            }
        } else {
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
        }
        return genericResponse;
    }

    @ApiOperation(value = "员工修改   门店端-员工-员工修改", httpMethod = "POST", response = GenericResponse.class, notes = "")
    @RequestMapping("/update")
    public GenericResponse update(@RequestBody StaffRequest staffRequest,HttpSession session) {
        GenericResponse<BaseStaff> genericResponse = new GenericResponse();
//        if (StringUtils.isBlank(staffRequest.getMobilePhone())) {
//            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "手机号码");
//            return genericResponse;
//        }
//        if (!CommonUtils.isMobile(staffRequest.getMobilePhone())) {
//            genericResponse.setCodeAndMsg(ResponseCode.NOT_MEET_REQUIREMENTS_S, "手机号码");
//            return genericResponse;
//        }
        staffRequest.setStoreId(SessionHelp.getStoreId(session));
        int i = 0;
        try {
            i = ssmBaseStaffService.updateStaff(staffRequest,SessionHelp.getLoginAccount(session));
        } catch (SmsException e){
            log.error("SsmStaffController.update:",e);
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e) {
            log.error("SsmStaffController.update:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        } else {
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
        }
        return genericResponse;
    }


    @ApiOperation(value = "员工月度任务   门店端-员工-员工月度任务", httpMethod = "POST", response = GenericResponse.class, notes = "")
    @RequestMapping("/monthJob")
    public GenericResponse monthJob(@RequestBody StaffRequest staffRequest,HttpSession session) {
        GenericResponse<BaseStaff> genericResponse = new GenericResponse();
        staffRequest.setStoreId(SessionHelp.getStoreId(session));
        int i = 0;
        try {
            i = ssmBaseStaffService.setMonthjob(staffRequest);
        } catch (Exception e) {
            log.error("SsmStaffController.monthJob:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        } else {
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
        }
        return genericResponse;
    }

    @ApiOperation(value = "员工离职  门店端-员工-员工离职", httpMethod = "POST", response = GenericResponse.class, notes = "")
    @RequestMapping("/leave")
    public GenericResponse leave(@RequestBody StaffRequest staffRequest,HttpSession session) {
        GenericResponse<BaseStaff> genericResponse = new GenericResponse();
        staffRequest.setStoreId(SessionHelp.getStoreId(session));
        int i = 0;
        try {
            i = ssmBaseStaffService.staffLeave(staffRequest);
        } catch (Exception e) {
            log.error("SsmStaffController.add:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        } else {
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
        }
        return genericResponse;
    }

    @ApiOperation(value = "员工停用  门店端-员工-员工停用", httpMethod = "POST", response = GenericResponse.class, notes = "")
    @RequestMapping("/stop")
    public GenericResponse stop(@RequestBody StaffRequest staffRequest,HttpSession session) {
        GenericResponse<BaseStaff> genericResponse = new GenericResponse();
        staffRequest.setStoreId(SessionHelp.getStoreId(session));
        int i = 0;
        try {
            i = ssmBaseStaffService.staffStop(staffRequest);
        } catch (Exception e) {
            log.error("SsmStaffController.add:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        } else {
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
        }
        return genericResponse;
    }

    @ApiOperation(value = "员工复职  门店端-员工-员工复职", httpMethod = "POST", response = GenericResponse.class, notes = "")
    @RequestMapping("/reinstated")
    public GenericResponse reinstated(@RequestBody StaffRequest staffRequest,HttpSession session) {
        GenericResponse<BaseStaff> genericResponse = new GenericResponse();
//        if (StringUtils.isBlank(staffRequest.getMobilePhone())) {
//            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "手机号码");
//            return genericResponse;
//        }
        staffRequest.setStoreId(SessionHelp.getStoreId(session));
        int i = 0;
        try {
            i = ssmBaseStaffService.staffReinstated(staffRequest);
        } catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e) {
            log.error("SsmStaffController.reinstated:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        } else {
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
        }
        return genericResponse;
    }

    @ApiOperation(value = "员工跟进会员统计信息分页查询  门店端-员工会员统计表-员工跟进会员统计信息分页查询" ,httpMethod = "POST",notes = "",response = PageResponse.class)
    @RequestMapping("/staffMemberPage")
    public PageResponse staffMemberPage(@RequestBody StaffRequest staffRequest,HttpSession session){
        PageResponse<StaffResponse> pageResponse = new PageResponse<>();
        PageInfo<StaffResponse> pageInfo = new PageInfo<>();
        staffRequest.setStoreId(SessionHelp.getStoreId(session));
        try {
            pageInfo = ssmBaseStaffService.staffMemberPage(staffRequest);
        }catch (Exception e){
            log.error("SsmStaffController.staffMemberPage", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setPageInfo(pageInfo);
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;
    }


    @ApiOperation(value = "查询当前门店所有在职员工  门店端-员工作品-查询当前门店所有在职员工", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/selectList")
    public GenericResponse selectList(@RequestBody StaffRequest staffRequest, HttpSession session) {
        GenericResponse<BaseStaff> genericResponse = new GenericResponse();
        if(null == staffRequest.getStoreId()){
            staffRequest.setStoreId(SessionHelp.getStoreId(session));
        }
        List<BaseStaff> list = new ArrayList<>();
        try {
            list = ssmBaseStaffService.selectList(staffRequest);
            if(list!=null && list.size()>0) {
                Collections.sort(list, new StrComparatorUtils<>("brandNumber", false));
            }
        } catch (Exception e) {
            log.error("SsmStaffController.selectList:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }

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

    @ApiOperation(value = "查询人员占比信息", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/selectRatioInfo")
    public GenericResponse selectPersonZB(@RequestBody CourseAccountRequest request) {
        GenericResponse<PersonZBResponse> genericResponse = new GenericResponse();

        List<PersonZBResponse> list = new ArrayList<>();
        try {
            list = ssmBaseStaffService.selectPersonZB(request);
        } catch (Exception e) {
            log.error("SsmStaffController.selectRatioInfo:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }

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



    @ApiOperation(value = "查询当前门店所有在职员工  门店端-员工作品-查询当前门店所有在职员工(type:0=高管，type:1=普通员工)", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/selectListType")
    public GenericResponse selectListtype(@RequestBody StaffRequest staffRequest, HttpSession session) {
        GenericResponse<BaseStaff> genericResponse = new GenericResponse();
        if(null == staffRequest.getStoreId()){
            staffRequest.setStoreId(SessionHelp.getStoreId(session));
        }

        List<BaseStaff> list = new ArrayList<>();
        try {
            list = ssmBaseStaffService.selectListtype(staffRequest);
        } catch (Exception e) {
            log.error("SsmStaffController.selectList:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }

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

    @ApiOperation(value = "门店员工启用  门店端-员工列表-门店员工启用", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/start")
    public GenericResponse start(@RequestBody StaffRequest staffRequest, HttpSession session) {
        GenericResponse<BaseStaff> genericResponse = new GenericResponse();
//        if (StringUtils.isBlank(staffRequest.getMobilePhone())) {
//            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "手机号码");
//            return genericResponse;
//        }
        staffRequest.setStoreId(SessionHelp.getStoreId(session));
        int i = 0;
        try {
            i = ssmBaseStaffService.start(staffRequest);
        } catch (Exception e) {
            log.error("SsmStaffController.start:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }


//    @ApiOperation(value = "门店员工模板下载  门店端-员工列表-门店员工模板下载", httpMethod = "POST", response = GenericResponse.class)
//    @RequestMapping("/download")
//    public void download(HttpSession session, HttpServletResponse response) {
//
////        FtpUtils ftpUtils = new FtpUtils();
////        InputStream is = null;
////        OutputStream os = null;
////        String fileName = "staff.xlsx";
////        try {
////            byte[] b =  ftpUtils.download(Constant.filePath, fileName);
////
////            if (response != null) {
////                os = response.getOutputStream();
////                // 设置响应头
////                // 文件编码 处理文件名中的 '+'、' ' 特殊字符
////                String encoderName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20").replace("%2B", "+");
////                response.setHeader("Content-Disposition", "attachment;filename=\"" + encoderName + "\"");
////                response.setContentType("application/octet-stream;charset=UTF-8");
////                response.setHeader("Accept-Ranges", "bytes");
////
////            }
////            is = new ByteArrayInputStream(b);
////            byte[] buffer = new byte[1024 * 5];
////            int len = 0;
////            while ((len = is.read(buffer)) > 0) {
////                os.write(buffer, 0, len);
////            }
////            os.flush();
////        } catch (Exception e) {
////            log.error("SsmStaffController.download:", e);
////        }finally {
////            // 关闭流
////            IOUtils.close(is);
////            IOUtils.close(os);
////        }
//
//        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
//        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
//        ExcelWriter excelWriter = null;
//        OutputStream out = null;
//        try {
//            String fileName = "staff";
//            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();
//            //ClassPathResource classPathResource = new ClassPathResource("static/live_room_data3.xls");
//            //InputStream inputStream = classPathResource.getInputStream();
//            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/staff.xlsx");
//
//            List<BaseStaff> list = new ArrayList<>();
//            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(list, writeSheet);
//            out.flush();
//        } catch (Exception e) {
//            log.error("SsmStaffController.download:",e);
//        } finally {
//            //destFile.delete();
//            // 别忘记关闭流
//            excelWriter.finish();
//        }
//    }
//
    //todo  员工导出接口
//    @ApiOperation(value = "门店员工批量导出  门店端-员工列表-门店员工批量导出", httpMethod = "POST", response = GenericResponse.class)
//    @RequestMapping("/export")
//    public void export(@RequestBody StaffRequest staffRequest, HttpSession session) {
//        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
//        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
//        ExcelWriter excelWriter = null;
//        OutputStream out = null;
//        if((staffRequest.getStoreIds()==null || staffRequest.getStoreIds().size()==0) && staffRequest.getStoreId()==null){
//            List<Long> ids = new ArrayList<>();
//            ids.add(SessionHelp.getStoreId(session));
//            staffRequest.setStoreIds(ids);
//        }
//        staffRequest.setStoreName(SessionHelp.getStoreName(session));
//        BaseStaff baseStaff = new BaseStaff();
//        try {
//            String fileName = "staff";
//            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();
//            //ClassPathResource classPathResource = new ClassPathResource("static/live_room_data3.xls");
//            //InputStream inputStream = classPathResource.getInputStream();
//            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/staff.xlsx");
////            BeanUtils.copyProperties(staffRequest, baseStaff);
//
//            List<BaseStaff> list = ssmBaseStaffService.staffExport(staffRequest);
//            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(list, writeSheet);
//            out.flush();
//        } catch (Exception e) {
//            log.error("SsmStaffController.export:",e);
//        } finally {
//            //destFile.delete();
//            // 别忘记关闭流
//            excelWriter.finish();
//        }
//    }
//
//
//    @ApiOperation(value = "门店员工批量导入  门店端-员工列表-门店员工批量导入", httpMethod = "POST", response = GenericResponse.class)
//    @RequestMapping("/import")
//    public GenericResponse staffImport(MultipartFile multipartFile, HttpSession session) {
//        GenericResponse genericResponse = new GenericResponse();
//        Long storeId = SessionHelp.getStoreId(session);
//        String storeName = SessionHelp.getStoreName(session);
//        List<BaseStaff> list = null;
//        try {
//            list = EasyExcelUtil.simpleWrite(multipartFile, BaseStaff.class);
//        } catch (SmsException e) {
//            log.error("SsmStaffController.staffImport:",e);
//            genericResponse.setCodeAndMsg(e);
//            return genericResponse;
//        }
//
//        for (BaseStaff baseStaff : list) {
//            baseStaff.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
//            baseStaff.setMobilePhone(AESUtils.encrypt(baseStaff.getMobilePhone()));
//            baseStaff.setPassword(AESUtils.encrypt(baseStaff.getPassword()));
//            baseStaff.setStoreId(storeId);
//            baseStaff.setStoreName(storeName);
//        }
//
////        //根据手机号去重
////        list = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()
////                -> new TreeSet<>(Comparator.comparing(BaseStaff::getMobilePhone))), ArrayList::new));
////
////        //手机号重复计数情况
////        Map<Object, Long> collect2 = list.stream().collect(
////                Collectors.groupingBy( BaseStaff::getMobilePhone , Collectors.counting()));
////        System.out.println("姓名重复计数情况："+collect2);
////        //筛出有重复的手机号
////        List<Object> collect3 = collect2.keySet().stream().
////                filter(key -> collect2.get(key) > 1).collect(Collectors.toList());
//
//
//        int count = ssmBaseStaffService.insertBatch(list);
//        if (list.size() != count) {
//            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
//            return genericResponse;
//        }
//        genericResponse.setCodeAndMsg(ResponseCode.OK);
//        return genericResponse;
//
//    }

    @ApiOperation(value = "分页查询门店高管列表（总店员工）",httpMethod = "POST",notes = "",response = PageResponse.class)
    @RequestMapping("/QuerCompetent")
    public PageResponse QuerCompetent(@RequestBody StaffRequest staffRequest,HttpSession session){
        PageResponse<StaffResponse> pageResponse = new PageResponse<>();
        PageInfo<StaffResponse> pageInfo = new PageInfo<>();
        Long storeId = SessionHelp.getStoreId(session);
        staffRequest.setStoreId(storeId);

        //查询总店
        //先查询总店
        StoreRequest storeRequest = new StoreRequest();
        Long storeIds = null;
        storeRequest.setId(storeId);
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            if(pagesorganization.getParentId()==null){
                storeIds = pagesorganization.getId();
            }
        }
        staffRequest.setStoreId(storeIds);
        staffRequest.setType(0);
        try {
            //报空指针
            pageInfo = ssmBaseStaffService.selectPage(staffRequest);
        }catch (Exception e){
            log.error("SsmStaffController.selectPage", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setPageInfo(pageInfo);
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;
    }

    @ApiOperation(value = "分页查询普通员工信息  门店端-员工-分页查询员工信息(type传0=查询管理者，1=普通员工)",httpMethod = "POST",notes = "",response = PageResponse.class)
    @RequestMapping("/pageStaff")
    public PageResponse selectPagestaff(@RequestBody StaffRequest staffRequest,HttpSession session){
        PageResponse<StaffResponse> pageResponse = new PageResponse<>();
        PageInfo<StaffResponse> pageInfo = new PageInfo<>();
        Long storeId = SessionHelp.getStoreId(session);
        staffRequest.setStoreId(storeId);
        try {
            pageInfo = ssmBaseStaffService.selectPagestaff(staffRequest);
        }catch (Exception e){
            log.error("SsmStaffController.selectPage", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setPageInfo(pageInfo);
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;
    }

    @ApiOperation(value = "门店员工业绩提成分类统计列表  门店端-员工-门店员工业绩提成分类统计列表",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/achiCommClassifyList")
    public GenericResponse achiCommClassifyList(@RequestBody StaffStatistic staffStatistic,HttpSession session){
        GenericResponse<StaffStatistic> genericResponse = new GenericResponse();
        List<StaffStatistic> totalList = new ArrayList<>();
        if(null == staffStatistic.getStoreId()||"".equals(staffStatistic.getStoreId())){
            staffStatistic.setStoreId(SessionHelp.getStoreId(session));
        }
        List<StaffStatistic> list = new ArrayList<>();
        try {
            staffStatistic.setClassify("0");
            list = ssmStoreStatisticService.achiCommList(staffStatistic);
            totalList.addAll(list);
            staffStatistic.setClassify("1");
            list = ssmStoreStatisticService.achiCommList(staffStatistic);
            totalList.addAll(list);
            staffStatistic.setClassify("2");
            list = ssmStoreStatisticService.achiCommList(staffStatistic);
            totalList.addAll(list);
            staffStatistic.setClassify("3");
            list = ssmStoreStatisticService.achiCommListRepay(staffStatistic);
            totalList.addAll(list);
            staffStatistic.setClassify("4");
            list = ssmStoreStatisticService.achiCommList(staffStatistic);
            totalList.addAll(list);
            staffStatistic.setClassify("5");
            list = ssmStoreStatisticService.achiCommList(staffStatistic);
            totalList.addAll(list);
            staffStatistic.setClassify("6");
            list = ssmStoreStatisticService.achiCommList(staffStatistic);
            totalList.addAll(list);

            staffStatistic.setClassify("7");
            list = ssmStoreStatisticService.achiCommList(staffStatistic);
            totalList.addAll(list);
            staffStatistic.setClassify("8");
            list = ssmStoreStatisticService.achiCommList(staffStatistic);
            totalList.addAll(list);
            staffStatistic.setClassify("9");
            list = ssmStoreStatisticService.achiCommList(staffStatistic);
            totalList.addAll(list);
            staffStatistic.setClassify("10");
            list = ssmStoreStatisticService.achiCommList(staffStatistic);
            totalList.addAll(list);
            staffStatistic.setClassify("11");
            list = ssmStoreStatisticService.achiCommList(staffStatistic);
            totalList.addAll(list);

        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStaffController.achiCommList",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setRows(totalList);
        return genericResponse;
    }

    @ApiOperation(value = "门店员工业绩提成分类统计列表  门店端-员工-门店员工业绩提成分类统计列表(升级后)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/achiCommClassifyLists")
    public GenericResponse achiCommClassifyLists(@RequestBody StaffStatistic staffStatistic,HttpSession session){
        GenericResponse<List<AchiCommEntity>> genericResponse = new GenericResponse();
        List<List<AchiCommEntity>> totalList = new ArrayList<>();
        if(null == staffStatistic.getStoreId()||"".equals(staffStatistic.getStoreId())){
            staffStatistic.setStoreId(SessionHelp.getStoreId(session));
        }
        List<List<AchiCommEntity>> list = new ArrayList<>();
        try {
            staffStatistic.setClassify("0");
            list = ssmStoreStatisticService.achiCommListupgrade(staffStatistic);
            totalList.addAll(list);
            staffStatistic.setClassify("1");
            list = ssmStoreStatisticService.achiCommListupgrade(staffStatistic);
            totalList.addAll(list);
            staffStatistic.setClassify("2");
            list = ssmStoreStatisticService.achiCommListupgrade(staffStatistic);
            totalList.addAll(list);
            staffStatistic.setClassify("3");
            list = ssmStoreStatisticService.achiCommListupgrade(staffStatistic);
            totalList.addAll(list);
            staffStatistic.setClassify("4");
            list = ssmStoreStatisticService.achiCommListupgrade(staffStatistic);
            totalList.addAll(list);
            staffStatistic.setClassify("5");
            list = ssmStoreStatisticService.achiCommListupgrade(staffStatistic);
            totalList.addAll(list);
            staffStatistic.setClassify("6");
            list = ssmStoreStatisticService.achiCommListupgrade(staffStatistic);
            totalList.addAll(list);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStaffController.achiCommList",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setRows(totalList);
        return genericResponse;
    }

    @ApiOperation(value = "门店员工业绩提成明细统计列表  门店端-员工-门店员工业绩提成明细统计列表",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/achiCommDetailList")
    public GenericResponse achiCommDetailList(@RequestBody StaffStatistic staffStatistic,HttpSession session){
        GenericResponse<AchiCommEntity> genericResponse = new GenericResponse();
        if(null == staffStatistic.getStoreId()||"".equals(staffStatistic.getStoreId())){
            staffStatistic.setStoreId(SessionHelp.getStoreId(session));
        }
        List<AchiCommEntity> list = new ArrayList<>();
        try {
            list = ssmStoreStatisticService.achiCommDetailList(staffStatistic);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStaffController.achiCommDetailList",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setRows(list);
        return genericResponse;
    }

    @ApiOperation(value = "部门业绩 单据明细",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/departmentPerformance3")
    public GenericResponse departmentPerformance3(@RequestBody StaffStatistic staffStatistic,HttpSession session){
        GenericResponse<AchiCommEntity> genericResponse = new GenericResponse();
        if(null == staffStatistic.getStoreId()||"".equals(staffStatistic.getStoreId())){
            staffStatistic.setStoreId(SessionHelp.getStoreId(session));
        }
        List<AchiCommEntity> list = new ArrayList<>();
        try {
            list = ssmStoreStatisticService.departmentPerformance3(staffStatistic);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStaffController.achiCommDetailList",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setRows(list);
        return genericResponse;
    }

    @ApiOperation(value = "门店员工业绩提成统计列表  门店端-员工-门店员工业绩提成统计列表",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/achiCommList")
    public GenericResponse achiCommList(@RequestBody StaffStatistic staffStatistic,HttpSession session){
        GenericResponse<StaffStatistic> genericResponse = new GenericResponse();
        if(null == staffStatistic.getStoreId()||"".equals(staffStatistic.getStoreId())){
            staffStatistic.setStoreId(SessionHelp.getStoreId(session));
        }
        List<StaffStatistic> list = new ArrayList<>();
        try {
            list = ssmStoreStatisticService.achiCommList(staffStatistic);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStaffController.achiCommList",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setRows(list);
        return genericResponse;
    }

    @ApiOperation(value = "门店员工业绩提成统计列表  门店端-员工-门店员工业绩提成统计列表（升级后）",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/achiCommLists")
    public GenericResponse achiCommLists(@RequestBody StaffStatistic staffStatistic,HttpSession session){
        GenericResponse<StaffStatistic> genericResponse = new GenericResponse();
        if(null == staffStatistic.getStoreId()||"".equals(staffStatistic.getStoreId())){
            staffStatistic.setStoreId(SessionHelp.getStoreId(session));
        }
        List<StaffStatistic> list = new ArrayList<>();
        try {
            list = ssmStoreStatisticService.achiCommLists(staffStatistic);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStaffController.achiCommList",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setRows(list);
        return genericResponse;
    }

    @ApiOperation(value = "门店员工业绩提成统计列表  门店端-员工-门店员工业绩提成统计列表汇总（升级后）",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/achiCommListsgroup")
    public GenericResponse achiCommListsgroup(@RequestBody StaffStatistic staffStatistic,HttpSession session){
        GenericResponse<StaffStatistic> genericResponse = new GenericResponse();
        if(null == staffStatistic.getStoreId()||"".equals(staffStatistic.getStoreId())){
            staffStatistic.setStoreId(SessionHelp.getStoreId(session));
        }
        List<StaffStatistic> list = new ArrayList<>();
        try {
//            list = ssmStoreStatisticService.achiCommListsgroup(staffStatistic);
            list = ssmStoreStatisticService.achiCommListsgroupByStoreList(staffStatistic);
//            list.sort(Comparator.comparing(StaffStatistic::getZyj).reversed());

            list.sort(Comparator.comparing(item->item.getBrandNumber()==null?"":item.getBrandNumber()));
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStaffController.achiCommList",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setRows(list);
        return genericResponse;
    }

    @ApiOperation(value = "部门业绩提成统计列表  门店端-美容部，美发部业绩",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/departmentPerformance")
    public GenericResponse departmentPerformance(@RequestBody StaffStatistic staffStatistic,HttpSession session){
        GenericResponse<StaffStatistic> genericResponse = new GenericResponse();
        if(null == staffStatistic.getStoreId()||"".equals(staffStatistic.getStoreId())){
            staffStatistic.setStoreId(SessionHelp.getStoreId(session));
        }
        List<StaffStatistic> list = new ArrayList<>();
        try {
//            list = ssmStoreStatisticService.departmentPerformance(staffStatistic);
            list = ssmStoreStatisticService.departmentPerformanceByStoreList(staffStatistic);
//            list.sort(Comparator.comparing(StaffStatistic::getDeptName).reversed());
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStaffController.achiCommList",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setRows(list);
        return genericResponse;
    }

    @ApiOperation(value = "部门业绩提成统计列表  门店端-美容部，美发部业绩",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/departmentPerformance/exportachi")
    public void departmentPerformanceExportachi(@RequestBody StaffStatistic staffStatistic,HttpSession session){
        if(null == staffStatistic.getStoreId()||"".equals(staffStatistic.getStoreId())){
            staffStatistic.setStoreId(SessionHelp.getStoreId(session));
        }
        ExcelWriter excelWriter = null;
        OutputStream out = null;
        if(null == staffStatistic.getStoreId()||"".equals(staffStatistic.getStoreId())){
            staffStatistic.setStoreId(SessionHelp.getStoreId(session));
        }
        List<StaffStatistic> list = new ArrayList<>();
        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();
            //ClassPathResource classPathResource = new ClassPathResource("static/live_room_data3.xls");
            //InputStream inputStream = classPathResource.getInputStream();
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/departAchi.xlsx");
//            BeanUtils.copyProperties(projectTypeRequest, baseProjectType);
            List<ExcelDepart> excelBaseProjectTypeList = new ArrayList<>();
//            list = ssmStoreStatisticService.departmentPerformance(staffStatistic);
            list = ssmStoreStatisticService.departmentPerformanceByStoreList(staffStatistic);
//            list.sort(Comparator.comparing(StaffStatistic::getDeptName).reversed());
            for (StaffStatistic projectType : list) {
                ExcelDepart excelDepart = new ExcelDepart();
                //部门名字
                excelDepart.setDeptNames(projectType.getDeptNames());
                //充值总业绩
                excelDepart.setAllRechergeAchi(projectType.getRecharge());
                //充值业绩
                excelDepart.setCashRechergeAchi(projectType.getRechargecar());
                //充值还款
                excelDepart.setRepayRechergeAchi(projectType.getRepaymentRecharge());
                //疗程总业绩
                excelDepart.setAllCourseAchi(projectType.getCourseSum());
                //疗程充值卡付业绩
                excelDepart.setRechargeCourseAchi(projectType.getCourseCard());
                //疗程充值卡付合作方业绩
                excelDepart.setRechargeCoopCourseAchi(projectType.getCooperationCardAmount());
                //疗程业绩
                excelDepart.setCashCourseAchi(projectType.getCourse());
                //疗程合作方业绩
                excelDepart.setCashCoopCourseAchi(projectType.getCooperationAchi());
                //疗程还款业绩
                excelDepart.setRepayCourseAchi(projectType.getCourseRepay());
                //疗程还款合作方业绩
                excelDepart.setRepayCoopCourseAchi(projectType.getHkCooperationAmount());
                //服务现金业绩
                excelDepart.setCashCashAchi(projectType.getCashierCash());
                //服务充值卡业绩
                excelDepart.setRechargeCashAchi(projectType.getCashierRecharge());
                //服务疗程卡付业绩
                excelDepart.setCourseCashAchi(projectType.getCashierCard());
                //充值退款
                excelDepart.setRefundRechargeAchi(projectType.getRefundRechagre());
                //疗程退款
                excelDepart.setRefundCourseAchi(projectType.getRefundCourse());
                //消费退款
                excelDepart.setRefundCashAchi(projectType.getRefundCash());
                //总现金业绩
                excelDepart.setAllCashAchi((projectType.getRecharge().add(projectType.getCourseSum()).add(projectType.getCashierCash())).setScale(2,BigDecimal.ROUND_HALF_UP));
                //实业绩
                excelDepart.setRealAllCashAchi(excelDepart.getAllCashAchi().subtract(excelDepart.getCashCoopCourseAchi().add(excelDepart.getRepayCoopCourseAchi())));
                //需业绩
                excelDepart.setCoopAllCashAchi(excelDepart.getAllCashAchi().subtract(excelDepart.getRealAllCashAchi()));
                excelBaseProjectTypeList.add(excelDepart);

            }
            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 (SmsException e){
            log.error("SsmStaffController.achiCommList",e);
        }catch (Exception e){
            log.error("SsmStaffController.achiCommList",e);
        }finally {
            //destFile.delete();
            // 别忘记关闭流
            excelWriter.finish();
        }
    }

    @ApiOperation(value = "门店员工业绩提成统计列表  门店端-美容部，美发部业绩",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/departmentPerformance2")
    public GenericResponse departmentPerformance2(@RequestBody StaffStatistic staffStatistic,HttpSession session){
        GenericResponse<StaffStatistic> genericResponse = new GenericResponse();
        if(null == staffStatistic.getStoreId()||"".equals(staffStatistic.getStoreId())){
            staffStatistic.setStoreId(SessionHelp.getStoreId(session));
        }
        List<StaffStatistic> list = new ArrayList<>();
        try {
            list = ssmStoreStatisticService.departmentPerformance2(staffStatistic);
            list.sort(Comparator.comparing(StaffStatistic::getDate).reversed());
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStaffController.achiCommList",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setRows(list);
        return genericResponse;
    }

    @ApiOperation(value = "员工个人查询工资  门店端-员工个人查询工资", httpMethod = "POST", response = GenericResponse.class, notes = "")
    @RequestMapping("/salaryByStaff")
    public GenericResponse selectSalaryByStaff(@RequestBody StaffSalaryRequest staffSalaryRequest,HttpSession session) {
        GenericResponse<StaffSalaryResponse> genericResponse = new GenericResponse();
        StaffSalaryResponse staffSalaryResponse = new StaffSalaryResponse();
        if(null == staffSalaryRequest.getStoreId()||"".equals(staffSalaryRequest.getStoreId())){
            staffSalaryRequest.setStoreId(SessionHelp.getStoreId(session));
        }
        try {
            staffSalaryResponse = ssmStaffSalaryService.selectSalaryByStaff(staffSalaryRequest);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        } catch (Exception e) {
            log.error("SsmStaffController.selectSalaryByStaff:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setData(staffSalaryResponse);
        return genericResponse;
    }

    @ApiOperation(value = "添加员工  门店端-员工-添加员工(转店)", httpMethod = "POST", response = GenericResponse.class, notes = "")
    @RequestMapping("/transition")
    public GenericResponse transition(@RequestBody StaffRequest staffRequest, HttpSession session) {
        GenericResponse<BaseStaff> genericResponse = new GenericResponse();
        String password = ObjectUtils.toString((int)((Math.random()*9+1)*1000));
        staffRequest.setPassword(AESUtils.encrypt(password));
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        staffRequest.setStoreName(storeName);
        staffRequest.setStoreId(storeId);
        int i = 0;
        try {
            i = ssmBaseStaffService.addStaffTransition(staffRequest);
        } catch (SmsException e){
            log.error("SsmStaffController.add:",e);
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e) {
            log.error("SsmStaffController.add:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        } else {
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
        }
        return genericResponse;
    }

    @ApiOperation(value = "查询异常单",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/selectAbnormalOrder")
    public GenericResponse selectAbnormalOrder(@RequestBody StaffStatistic staffStatistic,HttpSession session){
        GenericResponse<PaegList> genericResponse = new GenericResponse();
        if(null == staffStatistic.getStoreId()||"".equals(staffStatistic.getStoreId())){
            staffStatistic.setStoreId(SessionHelp.getStoreId(session));
        }
        PaegList list = new PaegList();
        try {
            list = ssmStoreStatisticService.selectAbnormalOrder(staffStatistic);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStaffController.achiCommDetailList",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setData(list);
        return genericResponse;
    }

    @ApiOperation(value = "查询异常单",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/selectAbnormalOrderNew")
    public GenericResponse selectAbnormalOrderNew(@RequestBody StaffStatistic staffStatistic,HttpSession session){
        GenericResponse<PaegList> genericResponse = new GenericResponse();
        List<Long> listStoreId=new ArrayList<>();
        if(null == staffStatistic.getStoreList() || staffStatistic.getStoreList().size() == 0){
            //自动查询
            staffStatistic.setSelectType(1);
            staffStatistic.setStoreId(SessionHelp.getStoreId(session));
            listStoreId.add(SessionHelp.getStoreId(session));
            staffStatistic.setStoreList(listStoreId);
        }else{
            //指定查询
            staffStatistic.setSelectType(0);
        }
        PaegList list = new PaegList();
        try {
            list = ssmStoreStatisticService.selectAbnormalOrderNew(staffStatistic);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStaffController.achiCommDetailList",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setData(list);
        return genericResponse;
    }

    @ApiOperation(value = "门店员工导出", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/achiCommListsgroup/exportachi")
    public void exportachi(@RequestBody StaffStatistic staffStatistic, HttpSession session) {
        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        StoreRequest storeRequest = new StoreRequest();
        if(null == staffStatistic.getStoreId() ||"".equals(staffStatistic.getStoreId())){
            storeRequest.setId(SessionHelp.getStoreId(session));
        }else{
            storeRequest.setId(staffStatistic.getStoreId());
        }

        BaseStore baseStore = ssmBaseStoreService.selectOne(storeRequest);

        ExcelWriter excelWriter = null;
        OutputStream out = null;
        if(null == staffStatistic.getStoreId()||"".equals(staffStatistic.getStoreId())){
            staffStatistic.setStoreId(SessionHelp.getStoreId(session));
        }
        List<StaffStatistic> list = new ArrayList<>();
        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();
            //ClassPathResource classPathResource = new ClassPathResource("static/live_room_data3.xls");
            //InputStream inputStream = classPathResource.getInputStream();
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/staffachisX.xlsx");
//            BeanUtils.copyProperties(projectTypeRequest, baseProjectType);
            List<ExcelStaffAchi> excelBaseProjectTypeList = new ArrayList<>();
//            List<BaseProjectType> list = ssmProjectTypeService.select(baseProjectType);
//            list = ssmStoreStatisticService.achiCommListsgroup(staffStatistic);
            list = ssmStoreStatisticService.achiCommListsgroupByStoreList(staffStatistic);

//            list.sort(Comparator.comparing(StaffStatistic::getZyj).reversed());
            list.sort(Comparator.comparing(StaffStatistic::getBrandNumber));
            for (StaffStatistic projectType : list) {
                ExcelStaffAchi excelBaseProjectType = new ExcelStaffAchi();
                BeanUtils.copyProperties(projectType, excelBaseProjectType);
                excelBaseProjectType.setStartDate(staffStatistic.getStartDate());
                excelBaseProjectType.setEndDate(staffStatistic.getEndDate());
//                excelBaseProjectType.setStoreName(baseStore.getStoreName());
//                excelBaseProjectType.setStoreNum(baseStore.getStoreNum());
                //疗程充值总销卡
                excelBaseProjectType.setSyRechargeCourse(excelBaseProjectType.getSyczkfyj().add(excelBaseProjectType.getSylcxkyj()));
                //充值疗程总业绩
                excelBaseProjectType.setRechargeCourse(excelBaseProjectType.getRechargeyj().add(excelBaseProjectType.getCourseOfTreatmentYJ()
//                        .add(projectType.getCashcxyj())
                        ));
//                excelBaseProjectType.setKjhyj(excelBaseProjectType.getKjhyj().add(projectType.getCashcxyj()==null?BigDecimal.ZERO:projectType.getCashcxyj()));
//                excelBaseProjectType.setZyj(excelBaseProjectType.getZyj().add(projectType.getCashcxyj()==null?BigDecimal.ZERO:projectType.getCashcxyj()));
                excelBaseProjectTypeList.add(excelBaseProjectType);
            }
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
            //EasyExcel.write(out, LiveRoomData.class).sheet("模板").doWrite(list);
            excelWriter = EasyExcel.write(out).withTemplate(inputStream).build();
            //FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            excelWriter.fill(excelBaseProjectTypeList, writeSheet);
            out.flush();
        } catch (Exception e) {
            log.error("SsmProjectTypeController.export:",e);
        } finally {
            //destFile.delete();
            // 别忘记关闭流
            excelWriter.finish();
        }
    }

    @ApiOperation(value = "门店员工业绩第二层导出", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/achiCommLists/exportachi")
    public void exportachis(@RequestBody StaffStatistic staffStatistic, HttpSession session) {
        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(SessionHelp.getStoreId(session));
        BaseStore baseStore = ssmBaseStoreService.selectOne(storeRequest);

        ExcelWriter excelWriter = null;
        OutputStream out = null;
        if(null == staffStatistic.getStoreId()||"".equals(staffStatistic.getStoreId())){
            staffStatistic.setStoreId(SessionHelp.getStoreId(session));
        }
        List<StaffStatistic> list = new ArrayList<>();
        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();
            //ClassPathResource classPathResource = new ClassPathResource("static/live_room_data3.xls");
            //InputStream inputStream = classPathResource.getInputStream();
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/staffachis.xlsx");
//            BeanUtils.copyProperties(projectTypeRequest, baseProjectType);
            List<ExcelStaffAchi> excelBaseProjectTypeList = new ArrayList<>();
//            List<BaseProjectType> list = ssmProjectTypeService.select(baseProjectType);
            list = ssmStoreStatisticService.achiCommLists(staffStatistic);
            list.sort(Comparator.comparing(StaffStatistic::getZyj).reversed());
            for (StaffStatistic projectType : list) {
                ExcelStaffAchi excelBaseProjectType = new ExcelStaffAchi();
                BeanUtils.copyProperties(projectType, excelBaseProjectType);
                excelBaseProjectType.setStartDate(staffStatistic.getStartDate());
                excelBaseProjectType.setEndDate(staffStatistic.getEndDate());
                excelBaseProjectType.setStoreName(baseStore.getStoreName());
                excelBaseProjectType.setStoreNum(baseStore.getStoreNum());
                excelBaseProjectType.setDate(projectType.getDate());

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

    @ApiOperation(value = "门店员工业绩明细导出（全员工）", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/achiCommLists/exportachiwhole")
    public void exportachiswhole(@RequestBody StaffStatistic staffStatistic, HttpSession session) {
        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(SessionHelp.getStoreId(session));
        //BaseStore baseStore = ssmBaseStoreService.selectOne(storeRequest);

        ExcelWriter excelWriter = null;
        OutputStream out = null;
        if(null == staffStatistic.getStoreId()||"".equals(staffStatistic.getStoreId())){
            staffStatistic.setStoreId(SessionHelp.getStoreId(session));
        }
        List<AchiCommEntity> list = new ArrayList<>();
        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();
            //ClassPathResource classPathResource = new ClassPathResource("static/live_room_data3.xls");
            //InputStream inputStream = classPathResource.getInputStream();
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/staffachisMX.xlsx");
//            BeanUtils.copyProperties(projectTypeRequest, baseProjectType);
            List<ExcelStaffOrder> excelBaseProjectTypeList = new ArrayList<>();
//            List<BaseProjectType> list = ssmProjectTypeService.select(baseProjectType);
            list = ssmStoreStatisticService.achiCommDetailLists(staffStatistic);
            list.sort(Comparator.comparing(AchiCommEntity::getDocDate).reversed());
            for (AchiCommEntity projectType : list) {
                ExcelStaffOrder excelBaseProjectType = new ExcelStaffOrder();
                BeanUtils.copyProperties(projectType, excelBaseProjectType);
                excelBaseProjectType.setStaffName(projectType.getSaleStaffName());
                if(null != projectType.getMemberNum() && !projectType.getMemberNum().equals("null")){
                    StoreMemberList storeMemberList = new StoreMemberList();
                    storeMemberList.setId(Long.valueOf(projectType.getMemberNum()));
                    StoreMemberList storeMemberList1 = ssmStoreMemberService.selectOne(storeMemberList);
                    excelBaseProjectType.setMemberNum(storeMemberList1.getMemberNum());
                }
                excelBaseProjectType.setCourseCard(BigDecimal.ZERO);
                if("card_recharge".equals(projectType.getDocType())){
                    excelBaseProjectType.setDocType("充值还款");
                }else if("card_change".equals(projectType.getDocType())){
                    excelBaseProjectType.setDocType("加价转疗程");
                }else if("card_use".equals(projectType.getDocType())){
                    excelBaseProjectType.setDocType("疗程开卡");
                }else if("store_cash".equals(projectType.getDocType())){
                    excelBaseProjectType.setDocType("收银");
                    if("card".equals(projectType.getOrderType())){
                        excelBaseProjectType.setCourseCard(projectType.getMoney());
                    }
                }else if("card_repay".equals(projectType.getDocType())){
                    excelBaseProjectType.setDocType("充值还款");
                }else if("refund_recharge".equals(projectType.getDocType())){
                    excelBaseProjectType.setDocType("充值退款");
                }else if("refund_course".equals(projectType.getDocType())){
                    excelBaseProjectType.setDocType("疗程退款");
                }else if("refund_cash".equals(projectType.getDocType())){
                    excelBaseProjectType.setDocType("消费退款");
                }else if("promotion".equals(projectType.getDocType())){
                    excelBaseProjectType.setDocType("促销活动");
                }else if("recharge_roll_course".equals(projectType.getDocType())){
                    excelBaseProjectType.setDocType("疗程转充值");
                }
                if(excelBaseProjectType.getTotalPerformance()==null){
                    excelBaseProjectType.setTotalPerformance(BigDecimal.ZERO);
                }
                if(excelBaseProjectType.getCooperationAchi()==null){
                    excelBaseProjectType.setCooperationAchi(BigDecimal.ZERO);
                }
                if(excelBaseProjectType.getMemberNum()!=null && excelBaseProjectType.getMemberNum().equals("null")){
                    excelBaseProjectType.setMemberNum("");
                }
                excelBaseProjectType.setTotalAchi(excelBaseProjectType.getTotalPerformance().add(excelBaseProjectType.getCooperationAchi()));
                excelBaseProjectTypeList.add(excelBaseProjectType);
            }
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
            //EasyExcel.write(out, LiveRoomData.class).sheet("模板").doWrite(list);
            excelWriter = EasyExcel.write(out).withTemplate(inputStream).build();
            //FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            excelWriter.fill(excelBaseProjectTypeList, writeSheet);
            out.flush();
        } catch (Exception e) {
            log.error("SsmProjectTypeController.export:",e);
        } finally {
            //destFile.delete();
            // 别忘记关闭流
            excelWriter.finish();
        }
    }

    @ApiOperation(value = "门店员工业绩提成重算（升级后）",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/ResultsRecalculation")
    public GenericResponse ResultsRecalculation(@RequestBody StaffStatistic staffStatistic,HttpSession session){
        GenericResponse<StaffStatistic> genericResponse = new GenericResponse();
        if(null == staffStatistic.getStoreId()||"".equals(staffStatistic.getStoreId())){
            staffStatistic.setStoreId(SessionHelp.getStoreId(session));
        }
        int i;
        try {
            i = ssmStoreStatisticService.ResultsRecalculation(staffStatistic);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStaffController.achiCommList",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);

        return genericResponse;
    }

    @ApiOperation(value = "查询疗程单品贡献率：传selectType:0=查询公司，1=查询门店",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/rateContribution")
    public PageResponse selectRateContribution(@RequestBody RateContribution rateContribution, HttpSession session) {
        PageResponse<RateContribution> pageResponse = new PageResponse<>();
        PageInfo<RateContribution> pageInfo = new PageInfo<>();
        rateContribution.setStoreId(SessionHelp.getStoreId(session));
        try{
            pageInfo = ssmStoreStatisticService.selectRateContribution(rateContribution);
        }catch(Exception e){
            log.error("SsmStaffController.achiCommList",e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }

    @ApiOperation(value = "查询疗程单品贡献率：storeIdType:0=总店项目，1=分店项目",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/rateContributionMx")
    public PageResponse rateContributionMx(@RequestBody RateContribution rateContribution, HttpSession session) {
        PageResponse<RateContribution> pageResponse = new PageResponse<>();
        PageInfo<RateContribution> pageInfo = new PageInfo<>();
        rateContribution.setStoreId(SessionHelp.getStoreId(session));
        try{
            pageInfo = ssmStoreStatisticService.selectRateContributionMx(rateContribution);
        }catch(Exception e){
            log.error("SsmStaffController.achiCommList",e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }

    @ApiOperation(value = "查询疗程单品贡献率：storeIdType:0=总店项目，1=分店项目",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/rateContributionMxs")
    public PageResponse rateContributionMxs(@RequestBody RateContribution rateContribution, HttpSession session) {
        PageResponse<RateContribution> pageResponse = new PageResponse<>();
        PageInfo<RateContribution> pageInfo = new PageInfo<>();
        try{
            pageInfo = ssmStoreStatisticService.selectRateContributionMxs(rateContribution);
        }catch(Exception e){
            log.error("SsmStaffController.achiCommList",e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }

    @ApiOperation(value = "查询疗程单品贡献率第四层明细",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/rateContributionMxOrder")
    public PageResponse rateContributionMxOrder(@RequestBody RateContribution rateContribution, HttpSession session) {
        PageResponse<RateContributionMx> pageResponse = new PageResponse<>();
        PageInfo<RateContributionMx> pageInfo = new PageInfo<>();
        try{
            pageInfo = ssmStoreStatisticService.rateContributionMxOrder(rateContribution);
        }catch(Exception e){
            log.error("SsmStaffController.achiCommList",e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }

    @ApiOperation(value = "收银疗程单品贡献率：传selectType:0=查询公司，1=查询门店",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/selectCashRateContribution")
    public PageResponse selectCashRateContribution(@RequestBody RateContribution rateContribution, HttpSession session) {
        PageResponse<RateContribution> pageResponse = new PageResponse<>();
        PageInfo<RateContribution> pageInfo = new PageInfo<>();
        rateContribution.setStoreId(SessionHelp.getStoreId(session));
        try{
            pageInfo = ssmStoreStatisticService.selectCashRateContribution(rateContribution);
        }catch(Exception e){
            log.error("SsmStaffController.achiCommList",e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }


    @ApiOperation(value = "查询疗程单品贡献率：storeIdType:0=总店项目，1=分店项目",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/selectCashRateContributionMx")
    public PageResponse selectCashRateContributionMx(@RequestBody RateContribution rateContribution, HttpSession session) {
        PageResponse<RateContribution> pageResponse = new PageResponse<>();
        PageInfo<RateContribution> pageInfo = new PageInfo<>();
        rateContribution.setStoreId(SessionHelp.getStoreId(session));
        try{
            pageInfo = ssmStoreStatisticService.selectCashRateContributionMx(rateContribution);
        }catch(Exception e){
            log.error("SsmStaffController.achiCommList",e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }

    @ApiOperation(value = "查询疗程单品贡献率：storeIdType:0=总店项目，1=分店项目",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/selectCashRateContributionMxs")
    public PageResponse selectCashRateContributionMxs(@RequestBody RateContribution rateContribution, HttpSession session) {
        PageResponse<RateContribution> pageResponse = new PageResponse<>();
        PageInfo<RateContribution> pageInfo = new PageInfo<>();
        try{
            pageInfo = ssmStoreStatisticService.selectCashRateContributionMxs(rateContribution);
        }catch(Exception e){
            log.error("SsmStaffController.achiCommList",e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }

    @ApiOperation(value = "查询疗程单品贡献率第四层明细",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/selectCashRateContributionMxOrder")
    public PageResponse CashrateContributionMxOrder(@RequestBody RateContribution rateContribution, HttpSession session) {
        PageResponse<RateContributionMx> pageResponse = new PageResponse<>();
        PageInfo<RateContributionMx> pageInfo = new PageInfo<>();
        try{
            pageInfo = ssmStoreStatisticService.CashrateContributionMxOrder(rateContribution);
        }catch(Exception e){
            log.error("SsmStaffController.achiCommList",e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        pageResponse.setPageInfo(pageInfo);
        return pageResponse;
    }

    @ApiOperation(value = "部门业绩提成统计列表  门店端-美容部，美发部业绩",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/departmentPerformanceNew")
    public GenericResponse departmentPerformanceNew(@RequestBody StaffStatistic staffStatistic,HttpSession session){
        GenericResponse<StaffStatistic> genericResponse = new GenericResponse();
        if(null == staffStatistic.getStoreId()||"".equals(staffStatistic.getStoreId())){
            staffStatistic.setStoreId(SessionHelp.getStoreId(session));
        }
        List<StaffStatistic> list = new ArrayList<>();
        try {
            list = ssmStoreStatisticService.departmentPerformanceNew(staffStatistic);
//            list.sort(Comparator.comparing(StaffStatistic::getDeptName).reversed());
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStaffController.achiCommList",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setRows(list);
        return genericResponse;
    }

    @ApiOperation(value = "门店员工业绩提成统计列表  门店端-员工-门店员工业绩提成统计列表汇总（升级后）",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/memberInitStaff")
    public GenericResponse memberInitStaff(@RequestBody StaffStatistic staffStatistic,HttpSession session){
        GenericResponse<StaffStatistic> genericResponse = new GenericResponse();
        if(null == staffStatistic.getStoreId()||"".equals(staffStatistic.getStoreId())){
            staffStatistic.setStoreId(SessionHelp.getStoreId(session));
        }
        List<StaffStatistic> list = new ArrayList<>();
        try {
            list = ssmStoreStatisticService.memberInitStaff(staffStatistic);
            list.sort(Comparator.comparing(item->item.getBrandNumber()==null?"":item.getBrandNumber()));
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmStaffController.achiCommList",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setRows(list);
        return genericResponse;
    }

    //TODO 小程序新增
    @ApiOperation(value = "员工新增接口",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/staffAddByWeChat")
    public GenericResponse staffAddByWeChat( @RequestBody StaffRequest staffRequest){
        GenericResponse<StaffTemporaryVo> genericResponse = new GenericResponse();
//        staffRequest.setStoreId(storeId);
        StaffTemporaryVo response = null;
        String mobilePhone = staffRequest.getMobilePhone();
        if(mobilePhone!=null) {
            String cash = stringRedisClient.get( "renli-" + mobilePhone);

            if (cash != null) {
                genericResponse.setCodeAndMsg(ResponseCode.MSG, "请勿重复提交");
                return genericResponse;
            }
            String uuid = UUID.randomUUID().toString();
//            stringRedisClient.set( "cash-" + mobilePhone, uuid, 60L, TimeUnit.SECONDS);
            stringRedisClient.waitingSet( "cash-" + mobilePhone, uuid, 60L, TimeUnit.SECONDS);
//            stringRedisClient.waitingSetValueWithExpirationAt( "cash-" + mobilePhone, uuid, );
        }
//        if (StringUtils.isNotBlank(staffRequest.getIdentityCard())){
//            genericResponse.setCodeAndMsg(ResponseCode.MSG, "请填写身份证");
//            return genericResponse;
//        }
        try {
//            response = ssmBaseStaffService.staffAddByWeChat(staffRequest);
            response = ssmBaseStaffService.staffLoginAndAddByWeChat(staffRequest);
        } catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }
//        catch (Exception e){
//            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
//            return genericResponse;
//        }
        genericResponse.setData(response);
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }

    @ApiOperation(value = "员工新增接口",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/staffAddByPc")
    public GenericResponse staffAddByPc( @RequestBody StaffRequest staffRequest){
        GenericResponse<StaffTemporaryVo> genericResponse = new GenericResponse();
//        staffRequest.setStoreId(storeId);
        StaffTemporaryVo response = null;
        try {
//            response = ssmBaseStaffService.staffAddByWeChat(staffRequest);
            response = ssmBaseStaffService.staffAddByPc(staffRequest);
        } catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setData(response);
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }

    @ApiOperation(value = "员工新增接口",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/addStaff")
    public GenericResponse staffAddByWeChatNew( @RequestBody StaffRequest staffRequest){
        GenericResponse<StaffTemporaryVo> genericResponse = new GenericResponse();
//        staffRequest.setStoreId(storeId);
        StaffTemporaryVo response = null;
        String mobilePhone = staffRequest.getMobilePhone();
        if(mobilePhone!=null) {
            String cash = stringRedisClient.get( "renli-" + mobilePhone);

            if (cash != null) {
                genericResponse.setCodeAndMsg(ResponseCode.MSG, "该员工已有记录，请勿重复提交");
                return genericResponse;
            }
            String uuid = UUID.randomUUID().toString();
//            stringRedisClient.set( "cash-" + mobilePhone, uuid, 60L, TimeUnit.SECONDS);
            stringRedisClient.waitingSet( "cash-" + mobilePhone, uuid, 60L, TimeUnit.SECONDS);
//            stringRedisClient.waitingSetValueWithExpirationAt( "cash-" + mobilePhone, uuid, );
        }
        try {
//            response = ssmBaseStaffService.staffAddByWeChat(staffRequest);
            response = ssmBaseStaffService.staffAddByWeChatNew(staffRequest);
        } catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setData(response);
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }


    @ApiOperation(value = "员工新增接口",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/staffLogin")
    public GenericResponse staffLogin( @RequestBody StaffRequest staffRequest){
        GenericResponse<StaffTemporaryVo> genericResponse = new GenericResponse();
//        staffRequest.setStoreId(storeId);
        StaffTemporaryVo response = null;
        try {
            response = ssmBaseStaffService.staffLogin(staffRequest);
        } catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }
        genericResponse.setData(response);
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;

    }


    //todo 获取验证码
    @ApiOperation(value = "手机端会员获取手机短信验证码接口", notes = "会员获取手机短信验证码接口", response = GenericResponse.class)
    @RequestMapping(path="/getSmsCode", method= RequestMethod.POST)
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "mobilePhone",value = "会员手机号",required = true),
            }
    )
    public GenericResponse getSmsCode(@RequestBody MemberRequest memberRequest) {
        GenericResponse<MemberResponse> genericResponse = new GenericResponse<>();
        MemberResponse memberResponse = null;
        try{
            memberResponse = ssmMemberLoginService.getStaffCode(memberRequest);
        }catch (SmsException e){
            log.error("SsmMemberLoginController.getSmsCode:", e);
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmMemberLoginController.getSmsCode:", e);
            genericResponse.setCodeAndMsg(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            return genericResponse;
        }
        if (memberResponse == null){
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setData(memberResponse);
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }
    //todo 验证码登录 小程序登录接口
    @ApiOperation(value = "手机端会员手机验证码登陆获取token接口", notes = "获取登录接口生成的token 使用接口前必须获取一次。作为参数传入", response = GenericResponse.class)
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "mobilePhone",value = "会员手机号",required = true),
                    @ApiImplicitParam(name = "passCode",value = "验证码",required = true)
            }
    )
    @RequestMapping(path="/phoneLogin", method= RequestMethod.POST)
    public GenericResponse phoneLogin(@RequestBody MemberRequest memberRequest,HttpSession session) {
        GenericResponse<StaffTemporaryVo> genericResponse = new GenericResponse<>();

        StaffTemporaryVo staffTemporaryVo = null;
        try{
//            staffTemporaryVo = ssmBaseStaffService.uniPhoneLogin(memberRequest);
            staffTemporaryVo = ssmBaseStaffService.uniPhoneLoginNew(memberRequest);
            staffTemporaryVo.setFacesInformation(null);
        }catch (SmsException e){
            log.error("SsmMemberLoginController.phoneLogin:", e);
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmMemberLoginController.phoneLogin:", e);
            genericResponse.setCodeAndMsg(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            return genericResponse;
        }
        if (staffTemporaryVo == null){
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setData(staffTemporaryVo);
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }


    @ApiOperation(value = "员工新增接口",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/staffSelect")
    public GenericResponse staffSelect( @RequestBody StaffRequest staffRequest){
        GenericResponse<Boolean> genericResponse = new GenericResponse();
//        staffRequest.setStoreId(storeId);
        Boolean response = null;
        response = ssmBaseStaffService.staffSelect(staffRequest);
        genericResponse.setData(response);
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;

    }
}
