package com.ssm.controller;

import cn.hutool.core.text.StrBuilder;
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.utils.AESUtils;
import com.ssm.manage.excelEntity.ExcelCourseList;
import com.ssm.manage.response.GenericResponse;
import com.ssm.manage.response.PageResponse;
import com.ssm.manage.service.SsmBaseStoreService;
import com.ssm.manage.service.SsmProjectService;
import com.ssm.manage.service.SsmStoreMemberService;
import com.ssm.manage.utils.SessionHelp;
import com.ssm.manage.entity.*;
import com.ssm.manage.query.CourseAccountRequest;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.service.SsmCourseAccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
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.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Api(value="疗程账户controller",tags={"疗程账户相关接口"})
@RestController
@RequestMapping("/demay/ssm/couAccount")
@Slf4j
public class SsmCourseAccountController {
    @Autowired
    private SsmCourseAccountService ssmCourseAccountService;

    @Autowired
    private SsmProjectService ssmProjectService;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmStoreMemberService ssmStoreMemberService;


    @ApiOperation(value = "疗程账户查询  (门店端-预约叫号-开单疗程账户查询)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/list")
    public GenericResponse list(@RequestBody CourseAccountRequest courseAccountRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
//        if (null == courseAccountRequest.getStoreId()){
//            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "门店ID");
//            return genericResponse;
//        }

        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        if(null==courseAccountRequest.getStoreId()){
            courseAccountRequest.setStoreId(SessionHelp.getStoreId(session));
        }
        courseAccountRequest.setIfstorid(courseAccountRequest.getStoreId());



        if (null == courseAccountRequest.getMemberId()){
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"会员ID");
            return genericResponse;
        }
        List<CourseAccount> list = new ArrayList<>();
        try {
            list = ssmCourseAccountService.selectList(courseAccountRequest);
            for (CourseAccount courseAccount : list) {
                if(courseAccount.getCourseNum()!=null) {
                    if(courseAccount.getCourseNum().startsWith("A")){
                        String substring = courseAccount.getCourseNum().substring(courseAccount.getCourseNum().length() - 12, courseAccount.getCourseNum().length() - 3);
                        StrBuilder strBuilder = new StrBuilder(substring);
                        StrBuilder insert = strBuilder.insert(6, "-").insert(4, "-");
                        courseAccount.setKaiKaDate(String.valueOf(insert));
                    }else {
                        String substring = courseAccount.getCourseNum().substring(courseAccount.getCourseNum().length() - 11, courseAccount.getCourseNum().length() - 3);
                        StrBuilder strBuilder = new StrBuilder(substring);
                        StrBuilder insert = strBuilder.insert(6, "-").insert(4, "-");
                        courseAccount.setKaiKaDate(String.valueOf(insert));
                    }
                }
            }
        }catch (Exception e){
            log.error("SsmCourseAccountController.list:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }

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

    @ApiOperation(value = "疗程账户查询  (门店端-预约叫号-开单疗程账户查询)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/listByJZ")
    public GenericResponse listByJZ(@RequestBody CourseAccountRequest courseAccountRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
//        if (null == courseAccountRequest.getStoreId()){
//            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "门店ID");
//            return genericResponse;
//        }
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        if(null==courseAccountRequest.getStoreId()){
            courseAccountRequest.setStoreId(SessionHelp.getStoreId(session));
        }
        courseAccountRequest.setIfstorid(courseAccountRequest.getStoreId());



        if (null == courseAccountRequest.getMemberId()){
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"会员ID");
            return genericResponse;
        }
        List<CourseAccount> list = new ArrayList<>();
        try {
            list = ssmCourseAccountService.selectListByJZ(courseAccountRequest);
        }catch (Exception e){
            log.error("SsmCourseAccountController.list:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }

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

    @ApiOperation(value = "疗程账户查询  (门店端-预约叫号-开单疗程账户查询)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/listdeal")
    public GenericResponse listjy(@RequestBody CourseAccountRequest courseAccountRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
//        if (null == courseAccountRequest.getStoreId()){
//            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "门店ID");
//            return genericResponse;
//        }
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        if(null==courseAccountRequest.getStoreId()){
            courseAccountRequest.setStoreId(SessionHelp.getStoreId(session));
        }


        if (null == courseAccountRequest.getMemberId()){
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"会员ID");
            return genericResponse;
        }
        List<CourseAccount> list = new ArrayList<>();
        try {
            list = ssmCourseAccountService.selectListdeal(courseAccountRequest);
            for (CourseAccount courseAccount : list) {

            }
        }catch (Exception e){
            log.error("SsmCourseAccountController.list:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }

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

    @ApiOperation(value = "疗程账户查询  (会员交易)不过期的",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/listdeals")
    public GenericResponse listjys(@RequestBody CourseAccountRequest courseAccountRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
//        if (null == courseAccountRequest.getStoreId()){
//            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "门店ID");
//            return genericResponse;
//        }
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        if(null==courseAccountRequest.getStoreId()){
            courseAccountRequest.setStoreId(SessionHelp.getStoreId(session));
        }


        if (null == courseAccountRequest.getMemberId()){
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"会员ID");
            return genericResponse;
        }
        List<CourseAccount> list = new ArrayList<>();
        try {
            list = ssmCourseAccountService.selectListdeals(courseAccountRequest);
            for (CourseAccount courseAccount : list) {

            }
        }catch (Exception e){
            log.error("SsmCourseAccountController.list:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }

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

    @ApiOperation(value = "疗程账户查询全部  剩余次数为0",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/listdealsalls")
    public GenericResponse listdealsall(@RequestBody CourseAccountRequest courseAccountRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
//        if (null == courseAccountRequest.getStoreId()){
//            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "门店ID");
//            return genericResponse;
//        }
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        if(null==courseAccountRequest.getStoreId()){
            courseAccountRequest.setStoreId(SessionHelp.getStoreId(session));
        }


        if (null == courseAccountRequest.getMemberId()){
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"会员ID");
            return genericResponse;
        }
        List<CourseAccount> list = new ArrayList<>();
        try {
            list = ssmCourseAccountService.selectListdealsalls(courseAccountRequest);
            for (CourseAccount courseAccount : list) {

            }
        }catch (Exception e){
            log.error("SsmCourseAccountController.list:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }

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


    @ApiOperation(value = "疗程账户延迟查询  过期的",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/delay")
    public GenericResponse delay(@RequestBody CourseAccountRequest courseAccountRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
//        if (null == courseAccountRequest.getStoreId()){
//            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "门店ID");
//            return genericResponse;
//        }
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        if(null==courseAccountRequest.getStoreId()){
            courseAccountRequest.setStoreId(SessionHelp.getStoreId(session));
        }


        if (null == courseAccountRequest.getMemberId()){
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"会员ID");
            return genericResponse;
        }
        List<CourseAccount> list = new ArrayList<>();
        try {
            list = ssmCourseAccountService.selectListdelay(courseAccountRequest);
            for (CourseAccount courseAccount : list) {

            }
        }catch (Exception e){
            log.error("SsmCourseAccountController.list:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }

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




    @ApiOperation(value = "疗程账户查询  (会员交易)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/listjysall")
    public GenericResponse listjysall(@RequestBody CourseAccountRequest courseAccountRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
//        if (null == courseAccountRequest.getStoreId()){
//            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "门店ID");
//            return genericResponse;
//        }
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        if(null==courseAccountRequest.getStoreId()){
            courseAccountRequest.setStoreId(SessionHelp.getStoreId(session));
        }


        if (null == courseAccountRequest.getMemberId()){
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"会员ID");
            return genericResponse;
        }
        List<CourseAccount> list = new ArrayList<>();
        try {
            list = ssmCourseAccountService.selectListdealsall(courseAccountRequest);
            for (CourseAccount courseAccount : list) {

            }
        }catch (Exception e){
            log.error("SsmCourseAccountController.list:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }

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

    @ApiOperation(value = "疗程账户查询  (门店端-预约叫号-开单疗程账户查询不可用账户（有剩余次数，可用次数=0）)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/listDisable")
    public GenericResponse listDisable(@RequestBody CourseAccountRequest courseAccountRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
//        if (null == courseAccountRequest.getStoreId()){
//            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "门店ID");
//            return genericResponse;
//        }
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        if(null==courseAccountRequest.getStoreId()){
            courseAccountRequest.setStoreId(SessionHelp.getStoreId(session));
        }


        if (null == courseAccountRequest.getMemberId()){
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"会员ID");
            return genericResponse;
        }
        List<CourseAccount> list = new ArrayList<>();
        try {
            list = ssmCourseAccountService.selectListDisable(courseAccountRequest);
            for (CourseAccount courseAccount : list) {

            }
        }catch (Exception e){
            log.error("SsmCourseAccountController.list:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }

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

    @ApiOperation(value = "疗程退页面疗程账户查询  (门店端-疗程退-疗程退页面疗程账户查询)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/refundList")
    public GenericResponse refundList(@RequestBody CourseAccountRequest courseAccountRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        courseAccountRequest.setStoreId(SessionHelp.getStoreId(session));
        if (null == courseAccountRequest.getMemberId()){
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"会员ID");
            return genericResponse;
        }
        List<CourseAccount> list = new ArrayList<>();
        try {
//            22/07/25,更改促销购买的疗程，不允许退，如果需要分开，去掉sql查询条件：and course_type not in (1,2)
            list = ssmCourseAccountService.selectRefundListone(courseAccountRequest);
        }catch (Exception e){
            log.error("SsmCourseAccountController.refundList:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }

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

    @ApiOperation(value = "单个疗程账户查询  (门店端-单个疗程账户查询)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/one")
    public GenericResponse one(@RequestBody CourseAccountRequest courseAccountRequest) {
        GenericResponse genericResponse = new GenericResponse();

        CourseAccount courseAccount = new CourseAccount();
        try {
            courseAccount = ssmCourseAccountService.selectByPrimaryKey(courseAccountRequest.getId());
        }catch (Exception e){
            log.error("SsmCourseAccountController.one:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }

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


    @ApiOperation(value = "疗程账户修改  (门店端-疗程单明细-疗程账户修改)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/update")
    public GenericResponse update(@RequestBody CourseAccountRequest courseAccountRequest, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        if(SessionHelp.getStoreId(session)==null){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"登录失效，请退出重新登录！");
            return genericResponse;
        }
        if (null == courseAccountRequest.getId()){
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "账户ID");
            return genericResponse;
        }
        String phone = SessionHelp.getLoginAccount(session);
        courseAccountRequest.setStoreId(SessionHelp.getStoreId(session));
        int i = 0;
        try {
            i = ssmCourseAccountService.update(courseAccountRequest, phone);
        }catch (Exception e){
            log.error("SsmCourseAccountController.update:",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) {
//
//        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
//        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
//        ExcelWriter excelWriter = null;
//        OutputStream out = null;
//        try {
//            String fileName = "courseAccount";
//            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/courseAccount.xlsx");
//
//            List<CourseAccount> 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("SsmCourseAccountController.download:",e);
//        } finally {
//            //destFile.delete();
//            // 别忘记关闭流
//            excelWriter.finish();
//        }
//    }
//
//    @ApiOperation(value = "疗程账户批量导出  门店端-疗程-疗程账户批量导出", httpMethod = "POST", response = GenericResponse.class)
//    @RequestMapping("/export")
//    public void export(@RequestBody CourseAccountRequest courseAccountRequest, HttpSession session) {
//        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
//        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
//        ExcelWriter excelWriter = null;
//        OutputStream out = null;
//        courseAccountRequest.setStoreId(SessionHelp.getStoreId(session));
//        courseAccountRequest.setStoreName(SessionHelp.getStoreName(session));
//        CourseAccount courseAccount = new CourseAccount();
//        try {
//            String fileName = "courseAccount";
//            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/courseAccount.xlsx");
//            BeanUtils.copyProperties(courseAccountRequest, courseAccount);
//            List<CourseAccount> list = ssmCourseAccountService.select(courseAccount);
//            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("SsmCourseAccountController.export:",e);
//        } finally {
//            //destFile.delete();
//            // 别忘记关闭流
//            excelWriter.finish();
//        }
//    }
//
//
//    @ApiOperation(value = "疗程账户批量导入  门店端-疗程-疗程账户批量导入", httpMethod = "POST", response = GenericResponse.class)
//    @RequestMapping("/import")
//    public GenericResponse courseAccountImport(MultipartFile multipartFile, HttpSession session) {
//        GenericResponse genericResponse = new GenericResponse();
//        Long storeId = SessionHelp.getStoreId(session);
//        String storeName = SessionHelp.getStoreName(session);
//        List<CourseAccount> list = null;
//        try {
//            list = EasyExcelUtil.simpleWrite(multipartFile, CourseAccount.class);
//        } catch (SmsException e) {
//            log.error("SsmCourseAccountController.courseAccountImport:",e);
//            return genericResponse;
//        }
//
//        int count = ssmCourseAccountService.insertBatch(list,storeId, storeName);
//        if (list.size() != count) {
//            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
//            return genericResponse;
//        }
//        genericResponse.setCodeAndMsg(ResponseCode.OK);
//        return genericResponse;
//
//    }

    @ApiOperation(value = "部门业绩提成统计列表  门店端-美容部，美发部业绩",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/exportachi/courseAcount")
    public void departmentPerformanceExportachi(@RequestBody CourseAccountRequest courseAccountRequest, HttpSession session){
        ExcelWriter excelWriter = null;
        OutputStream out = null;
        List<CourseAccount> 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();
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/courseAccountNew.xlsx");
            List<ExcelCourseList> excelBaseProjectTypeList = new ArrayList<>();
            list = ssmCourseAccountService.exportachi(courseAccountRequest);
            //查询项目编码
            if(!CollectionUtils.isEmpty(list)) {
                List<Long> projectId = list.stream().map(CourseAccount::getCourseProjectId).collect(Collectors.toList());
                List<Long> memberId = list.stream().map(CourseAccount::getMemberId).collect(Collectors.toList());
//                List<Long> storeId = list.stream().map(CourseAccount::getStoreId).collect(Collectors.toList());
                List<BaseProject> projectList = ssmProjectService.selectList(projectId);
                List<BaseStore> baseStores = ssmBaseStoreService.selectAll();
                List<StoreMemberList> storeMemberLists = ssmStoreMemberService.selectList(memberId);
                for (CourseAccount courseAccount : list) {
                    ExcelCourseList courseList = new ExcelCourseList();
                    for (BaseStore baseStore : baseStores) {
                        if(courseAccount.getStoreId().compareTo(baseStore.getId())==0){
                            courseList.setStoreNum(baseStore.getStoreNum());
                            courseList.setStoreName(baseStore.getStoreName());
                        }
                    }
                    setCourseType(courseList,courseAccount.getCourseType()==null?"":courseAccount.getCourseType());
                    for (StoreMemberList storeMemberList : storeMemberLists) {
                        if(courseAccount.getMemberId().compareTo(storeMemberList.getId())==0){
                            courseList.setMobilePhone(AESUtils.decrypt(storeMemberList.getMobilePhone()).replaceAll("\u0000",""));
                            courseList.setMemberName(storeMemberList.getMemberName());
                            courseList.setMemberNum(storeMemberList.getMemberNum());
                        }
                    }
                    courseList.setCourseReatmentNum(courseAccount.getCourseNum());
                    for (BaseProject baseProject : projectList) {
                        if(baseProject.getId().compareTo(courseAccount.getCourseProjectId())==0){
                            courseList.setProjectNum(baseProject.getProjectNum());
                            courseList.setProjectName(baseProject.getProjectName());
                        }
                    }
                    courseList.setCourseCount(courseAccount.getCourseCount());
                    courseList.setCourseProjectMoney(courseAccount.getCourseProjectMoney());
                    courseList.setCourseStandardMoney(courseAccount.getCourseStandardMoney());
                    courseList.setCourseStandardCount(courseAccount.getCourseStandardCount());
                    courseList.setState("已锁定");
                    if (courseAccount.getState()==1){
                        courseList.setState("正常");
                    }
                    courseList.setLastConsumeDate(courseAccount.getLastConsumeTime());
                    courseList.setCourseRestCount(courseAccount.getCourseRestCount());
                    courseList.setCourseConsumeCount(courseAccount.getCourseConsumeCount());
                    excelBaseProjectTypeList.add(courseList);
                }
            }

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

    @ApiOperation(value = "部门业绩提成统计列表  门店端-美容部，美发部业绩",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/courseAcount/list")
    public PageResponse<ExcelCourseList> courseAccountList(@RequestBody CourseAccountRequest courseAccountRequest, HttpSession session) {
        PageResponse<ExcelCourseList> pageResponse = new PageResponse<>();
        PageInfo<CourseAccount> list;
            List<ExcelCourseList> excelBaseProjectTypeList = new ArrayList<>();
            list = ssmCourseAccountService.exportachiByPage(courseAccountRequest);
            //查询项目编码
            List<CourseAccount> list1 = list.getList();
            if (!CollectionUtils.isEmpty(list1)) {
                List<Long> projectId = list1.stream().map(CourseAccount::getCourseProjectId).collect(Collectors.toList());
                List<Long> memberId = list1.stream().map(CourseAccount::getMemberId).collect(Collectors.toList());
//                List<Long> storeId = list1.stream().map(CourseAccount::getStoreId).collect(Collectors.toList());
                List<BaseProject> projectList = ssmProjectService.selectList(projectId);
                List<BaseStore> baseStores = ssmBaseStoreService.selectAll();
                List<StoreMemberList> storeMemberLists = ssmStoreMemberService.selectList(memberId);
                for (CourseAccount courseAccount : list1) {
                    ExcelCourseList courseList = new ExcelCourseList();
                    for (BaseStore baseStore : baseStores) {
                        if (courseAccount.getStoreId().compareTo(baseStore.getId()) == 0) {
                            courseList.setStoreNum(baseStore.getStoreNum());
                            courseList.setStoreName(baseStore.getStoreName());
                        }
                    }
                    setCourseType(courseList,courseAccount.getCourseType()==null?"":courseAccount.getCourseType());
                    for (StoreMemberList storeMemberList : storeMemberLists) {
                        if (courseAccount.getMemberId().compareTo(storeMemberList.getId()) == 0) {
                            try {
                                courseList.setMobilePhone(AESUtils.decrypt(storeMemberList.getMobilePhone()).replaceAll("\u0000",""));
                            } catch (Exception e) {
                                pageResponse.setCodeAndMsg(ResponseCode.MSG,"会员手机号解析失败");
                                return pageResponse;
                            }
                            courseList.setMemberName(storeMemberList.getMemberName());
                            courseList.setMemberNum(storeMemberList.getMemberNum());
                        }
                    }
                    courseList.setCourseReatmentNum(courseAccount.getCourseNum());
                    for (BaseProject baseProject : projectList) {
                        if (baseProject.getId().compareTo(courseAccount.getCourseProjectId()) == 0) {
                            courseList.setProjectNum(baseProject.getProjectNum());
                            courseList.setProjectName(baseProject.getProjectName());
                        }
                    }
                    courseList.setCourseCount(courseAccount.getCourseCount());
                    courseList.setCourseProjectMoney(courseAccount.getCourseProjectMoney());
                    courseList.setCourseStandardMoney(courseAccount.getCourseStandardMoney());
                    courseList.setCourseStandardCount(courseAccount.getCourseStandardCount());
                    courseList.setState("已锁定");
                    if (courseAccount.getState() == 1) {
                        courseList.setState("正常");
                    }
                    courseList.setLastConsumeDate(courseAccount.getLastConsumeTime());
                    courseList.setCourseRestCount(courseAccount.getCourseRestCount());
                    courseList.setCourseConsumeCount(courseAccount.getCourseConsumeCount());
                    excelBaseProjectTypeList.add(courseList);
                }
            }
            PageInfo<ExcelCourseList> pageInfo = new PageInfo<>(excelBaseProjectTypeList);
            pageInfo.setPageNum(list.getPageNum());
            pageInfo.setPageSize(list.getPageSize());
            pageInfo.setTotal(list.getTotal());
            pageResponse.setPageInfo(pageInfo);
            pageResponse.setCodeAndMsg(ResponseCode.OK);
            return pageResponse;

    }
    private void setCourseType(ExcelCourseList courseList, String courseType) {
        switch (courseType){
            case "" : courseList.setCourseType("会员转卡");break;
            case "0" : courseList.setCourseType("疗程开卡");break;
            case "1" : courseList.setCourseType("疗程促销");break;
            case "2" : courseList.setCourseType("疗程促销赠品");break;
            case "3" : courseList.setCourseType("加价转疗程");break;
        }
    }

}
