package com.ssm.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.github.pagehelper.PageInfo;
import com.ssm.manage.response.GenericResponse;
import com.ssm.manage.response.PageResponse;
import com.ssm.core.util.EasyExcelUtil;
import com.ssm.manage.utils.SessionHelp;
import com.ssm.manage.entity.*;
import com.ssm.manage.excelEntity.ExcelBaseProject;
import com.ssm.manage.query.ProjectRequest;
import com.ssm.manage.query.ProjectTypeRequest;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.service.SsmProjectService;
import com.ssm.manage.service.SsmProjectTypeService;
import com.ssm.manage.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

@Api(value = "项目controller", tags = {"项目相关接口"})
@RestController
@RequestMapping("/demay/ssm/pro")
@Slf4j
public class SsmProjectController {

    @Autowired
    private SsmProjectService ssmProjectService;

    @Autowired
    private SsmProjectTypeService ssmProjectTypeService;

    @ApiOperation(value = "分页查询项目 门店端-项目-分页查询项目", httpMethod = "POST", response = PageResponse.class)
    @RequestMapping("/page")
    public PageResponse selectPageNew(@RequestBody ProjectRequest projectRequest, HttpSession session) {
        PageResponse<BaseProject> pageResponse = new PageResponse<>();
        PageInfo<BaseProject> pageInfo = new PageInfo<>();
        if(null == projectRequest.getStoreId()){
            projectRequest.setStoreId(SessionHelp.getStoreId(session));
        }

        try {
            pageInfo = ssmProjectService.selectPage(projectRequest);
        } catch (Exception e) {
            log.error("SsmProjectController.page", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setPageInfo(pageInfo);
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;
    }

    @ApiOperation(value = "分页查询重名项目", httpMethod = "POST", response = PageResponse.class)
    @RequestMapping("/repeatPage")
    public PageResponse repeatPage(@RequestBody ProjectRequest projectRequest, HttpSession session) {
        PageResponse<BaseProject> pageResponse = new PageResponse<>();
        PageInfo<BaseProject> pageInfo = new PageInfo<>();
        if(null == projectRequest.getStoreId()){
            projectRequest.setStoreId(SessionHelp.getStoreId(session));
        }

        try {
            pageInfo = ssmProjectService.repeatPage(projectRequest);
        } catch (Exception e) {
            log.error("SsmProjectController.page", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setPageInfo(pageInfo);
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;
    }

    @ApiOperation(value = "分页查询项目 门店端-项目-分页查询项目", httpMethod = "POST", response = PageResponse.class)
    @RequestMapping("/selectPageNew")
    public PageResponse selectPage(@RequestBody ProjectRequest projectRequest, HttpSession session) {
        PageResponse<BaseProject> pageResponse = new PageResponse<>();
        PageInfo<BaseProject> pageInfo = new PageInfo<>();
        if(null == projectRequest.getStoreId()){
            projectRequest.setStoreId(SessionHelp.getStoreId(session));
        }
        try {
            pageInfo = ssmProjectService.selectPageNew(projectRequest);
        } catch (Exception e) {
            log.error("SsmProjectController.page", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setPageInfo(pageInfo);
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;
    }

    @ApiOperation(value = "分页查询项目 门店端-项目-分页查询项目(根据项目类型ID精准查询)", httpMethod = "POST", response = PageResponse.class)
    @RequestMapping("/pageType")
    public PageResponse selectPageType(@RequestBody ProjectRequest projectRequest, HttpSession session) {
        PageResponse<BaseProject> pageResponse = new PageResponse<>();
        PageInfo<BaseProject> pageInfo = new PageInfo<>();
        if(null == projectRequest.getStoreId()){
            projectRequest.setStoreId(SessionHelp.getStoreId(session));
        }

        try {
            pageInfo = ssmProjectService.selectPageType(projectRequest);
        } catch (Exception e) {
            log.error("SsmProjectController.page", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setPageInfo(pageInfo);
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;
    }

    @ApiOperation(value = "项目添加  门店端-项目-项目添加", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/add")
    public GenericResponse add(@RequestBody ProjectRequest projectRequest, HttpSession session) {
        GenericResponse<BaseProject> genericResponse = new GenericResponse<>();
        if (StringUtils.isBlank(String.valueOf(projectRequest.getId()))){
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"项目编码");
            return genericResponse;
        }
        if (StringUtils.isBlank(projectRequest.getProjectName())) {
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "项目名称");
            return genericResponse;
        }
        if(projectRequest.getStoreId()==null) {
            Long storeId = SessionHelp.getStoreId(session);
            projectRequest.setStoreId(storeId);
        }
        if(projectRequest.getStoreName()==null || projectRequest.getStoreName().equals("")) {
            String storeName = SessionHelp.getStoreName(session);
            projectRequest.setStoreName(storeName);
        }
        String phone = SessionHelp.getLoginAccount(session);
        int i = 0;
        try {
            i = ssmProjectService.addProject(projectRequest, phone);
        } catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        } catch (Exception e) {
            log.error("SsmProjectController.add", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if(i ==999){
            genericResponse.setCodeAndMsg(ResponseCode.FAILEDS);
            return genericResponse;
        }else if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "项目修改  门店端-项目-项目修改", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/update")
    public GenericResponse update(@RequestBody ProjectRequest projectRequest, HttpSession session) {
        GenericResponse<BaseProject> genericResponse = new GenericResponse<>();
        if(projectRequest.getStoreId()==null) {
            Long storeId = SessionHelp.getStoreId(session);
            projectRequest.setStoreId(storeId);
        }
        String storeName = SessionHelp.getStoreName(session);
        String phone = SessionHelp.getLoginAccount(session);
        projectRequest.setStoreName(storeName);
        int i = 0;
        try {
            i = ssmProjectService.updateProject(projectRequest, phone);
        } catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        } catch (Exception e) {
            log.error("SsmProjectController.update", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if(i ==999){
            genericResponse.setCodeAndMsg(ResponseCode.FAILEDS);
            return genericResponse;
        }else if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "项目删除  门店端-项目-项目删除", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/delete")
    public GenericResponse delete(@RequestBody ProjectRequest projectRequest, HttpSession session) {
        GenericResponse<BaseProject> genericResponse = new GenericResponse<>();
        if(projectRequest.getStoreId()==null) {
            Long storeId = SessionHelp.getStoreId(session);
            projectRequest.setStoreId(storeId);
        }
        int i = 0;
        try {
            i = ssmProjectService.deleteProject(projectRequest);
        } catch (SmsException e){
            log.error("SsmProjectController.delete", e);
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e) {
            log.error("SsmProjectController.delete", 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("/updateStates")
    public GenericResponse updateStates(@RequestBody ProjectRequest projectRequest, HttpSession session) {
        GenericResponse<BaseProject> genericResponse = new GenericResponse<>();
        if(projectRequest.getStoreId()==null) {
            Long storeId = SessionHelp.getStoreId(session);
            projectRequest.setStoreId(storeId);
        }
        int i = 0;
        try {
            i = ssmProjectService.updateStates(projectRequest);
        }catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e) {
            log.error("SsmProjectController.updateStates", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }


    @ApiOperation(value = "项目设置业绩提成   门店端-项目-项目设置业绩提成", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/setAchiComm")
    public GenericResponse setAchiComm(@RequestBody ProjectRequest projectRequest, HttpSession session) {
        String phone = SessionHelp.getLoginAccount(session);
        projectRequest.setUpdateCommPhone(phone);
        GenericResponse<BaseProject> genericResponse = new GenericResponse<>();
        if(projectRequest.getStoreId()==null) {
            Long storeId = SessionHelp.getStoreId(session);
            projectRequest.setStoreId(storeId);
        }
        int i = 0;
        try {
            i = ssmProjectService.setAchiComm(projectRequest);
        } catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e) {
            log.error("SsmProjectController.setAchiComm", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "项目拷贝业绩提成   门店端-项目-项目设置业绩提成", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/setAchiCommList")
    public GenericResponse setAchiCommList(@RequestBody ProjectRequest projectRequest, HttpSession session) {
        GenericResponse<BaseProject> genericResponse = new GenericResponse<>();
        if(projectRequest.getStoreId()==null) {
            Long storeId = SessionHelp.getStoreId(session);
            projectRequest.setStoreId(storeId);
        }
        int i = 0;
        try {
            i = ssmProjectService.setAchiComms(projectRequest);
        } catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e) {
            log.error("SsmProjectController.setAchiComm", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }


    @ApiOperation(value = "项目明细查询  门店端-项目-项目明细查询", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/one")
    public GenericResponse one(@RequestBody ProjectRequest projectRequest, HttpSession session) {
        GenericResponse<BaseProject> genericResponse = new GenericResponse<>();
        if(projectRequest.getStoreId()==null) {
            Long storeId = SessionHelp.getStoreId(session);
            projectRequest.setStoreId(storeId);
        }
        int i = 0;
        BaseProject baseProject = new BaseProject();
        try {
            baseProject = ssmProjectService.one(projectRequest);
        } catch (Exception e) {
            log.error("SsmProjectController.one", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }

        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setData(baseProject);
        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 = "project";
            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/project.xlsx");

            List<ExcelBaseProject> 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("SsmProjectController.download:",e);
        } finally {
            //destFile.delete();
            // 别忘记关闭流
            excelWriter.finish();
        }
    }

    @ApiOperation(value = "门店项目批量导出  门店端-项目列表-门店项目批量导出", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/exportold")
    public void exportold(@RequestBody ProjectRequest projectRequest, HttpSession session) {
        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        ExcelWriter excelWriter = null;
        OutputStream out = null;
        if(projectRequest.getStoreId()==null) {
            Long storeId = SessionHelp.getStoreId(session);
            projectRequest.setStoreId(storeId);
        }
        if(projectRequest.getStoreName()==null || projectRequest.getStoreName().equals("")){
            projectRequest.setStoreName(SessionHelp.getStoreName(session));

        }
        BaseProject baseProject = new BaseProject();
        try {
            String fileName = "project";
            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/project.xlsx");
//            BeanUtils.copyProperties(projectRequest, baseProject);
//            List<BaseProject> list = ssmProjectService.select(baseProject);

            Example example = new Example(BaseProject.class);
            Example.Criteria criteria = example.createCriteria();
            example.setOrderByClause("project_num desc");
            if (StringUtils.isNotBlank(projectRequest.getProjectNum())){
                criteria.andLike("projectNum","%" + projectRequest.getProjectNum() + "%");
            }
            if (StringUtils.isNotBlank(projectRequest.getProjectName())){
                criteria.andLike("projectName","%" + projectRequest.getProjectName() + "%");
            }
            if (StringUtils.isNotBlank(projectRequest.getProjectTypeName())){
                criteria.andLike("projectTypeName","%" + projectRequest.getProjectTypeName() + "%");
            }
            if (projectRequest.getState() != null){
                criteria.andEqualTo("state",projectRequest.getState());
            }

            criteria.andEqualTo("storeId",projectRequest.getStoreId());

            if (projectRequest.getDirectConsumption() != null){
                criteria.andEqualTo("directConsumption",projectRequest.getDirectConsumption());
            }
            if (projectRequest.getType() != null){
                criteria.andBetween("founderDatetime", DateUtils.diffDay(new Date(), -7), new Date());
            }
            List<BaseProject> list = ssmProjectService.selectByExample(example);
            List<ExcelBaseProject> excelBaseProjects = new ArrayList<>();
            for (BaseProject project  : list) {
                ExcelBaseProject excelBaseProject = new ExcelBaseProject();
                BeanUtils.copyProperties(project, excelBaseProject);

                if (project.getState() == 1){
                    excelBaseProject.setState("启用");
                }else if (project.getState() == 0){
                    excelBaseProject.setState("禁用");
                }
                if (project.getDirectConsumption() == 1){
                    excelBaseProject.setDirectConsumption("是");
                }else if (project.getDirectConsumption() == 0){
                    excelBaseProject.setDirectConsumption("否");
                }
                if(null != project.getIsCooperation()){
                    if (project.getIsCooperation() == 1){
                        excelBaseProject.setIsCooperation("是");
                    }else if (project.getIsCooperation() == 0){
                        excelBaseProject.setIsCooperation("否");
                    }
                }
                if(null != project.getNoDiscount()){
                    if (project.getNoDiscount() == 1){
                        excelBaseProject.setNoDiscount("否");
                    }else if (project.getNoDiscount() == 0){
                        excelBaseProject.setNoDiscount("是");
                    }
                }
                if(null != project.getIsCardPay()){
                    if (project.getIsCardPay() == 1){
                        excelBaseProject.setIsCardPay("否");
                    }else if (project.getIsCardPay() == 0){
                        excelBaseProject.setIsCardPay("是");
                    }
                }
//                if(null != project.getStoreType()){
//                    if (project.getStoreType() == 1){
//                        excelBaseProject.setStoreType("美容店");
//                    }else if (project.getStoreType() == 0){
//                        excelBaseProject.setIsCooperation("美发店");
//                    }
//                }
                excelBaseProjects.add(excelBaseProject);
            }
            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(excelBaseProjects, writeSheet);
            out.flush();
        } catch (Exception e) {
            log.error("SsmProjectController.export:",e);
        } finally {
            //destFile.delete();
            // 别忘记关闭流
            excelWriter.finish();
        }
    }

    @ApiOperation(value = "门店项目批量导出  门店端-项目列表-门店项目批量导出", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/export")
    public void export(@RequestBody ProjectRequest projectRequest, HttpSession session) {
        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        ExcelWriter excelWriter = null;
        OutputStream out = null;
        projectRequest.setStoreId(SessionHelp.getStoreId(session));
        projectRequest.setStoreName(SessionHelp.getStoreName(session));
        BaseProject baseProject = new BaseProject();
        try {
            String fileName = "project";
            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/project.xlsx");
//            BeanUtils.copyProperties(projectRequest, baseProject);
//            List<BaseProject> list = ssmProjectService.select(baseProject);
            List<BaseProject> listAll = new ArrayList<>();


            if(null != projectRequest.getProjectTypeName()){
                if(projectRequest.getExport()==0){
                    Example example = new Example(BaseProject.class);
                    Example.Criteria criteria = example.createCriteria();
                    example.setOrderByClause("project_num desc");
                    if (StringUtils.isNotBlank(projectRequest.getProjectNum())){
                        criteria.andLike("projectNum","%" + projectRequest.getProjectNum() + "%");
                    }
                    if (StringUtils.isNotBlank(projectRequest.getProjectName())){
                        criteria.andLike("projectName","%" + projectRequest.getProjectName() + "%");
                    }
                    if (StringUtils.isNotBlank(projectRequest.getProjectTypeName())){
                        criteria.andLike("projectTypeName","%" + projectRequest.getProjectTypeName() + "%");
                    }
                    if (null == projectRequest.getProjectTypeId()){
                        criteria.andEqualTo("projectTypeId",projectRequest.getProjectTypeId());
                    }
                    if (projectRequest.getState() != null){
                        criteria.andEqualTo("state",projectRequest.getState());
                    }

                    criteria.andEqualTo("storeId",projectRequest.getStoreId());

                    if (projectRequest.getDirectConsumption() != null){
                        criteria.andEqualTo("directConsumption",projectRequest.getDirectConsumption());
                    }
                    if (projectRequest.getType() != null){
                        criteria.andBetween("founderDatetime", DateUtils.diffDay(new Date(), -7), new Date());
                    }
                    List<BaseProject> list = ssmProjectService.selectByExample(example);
                    List<ExcelBaseProject> excelBaseProjects = new ArrayList<>();
                    for (BaseProject project  : list) {
                        ExcelBaseProject excelBaseProject = new ExcelBaseProject();
                        BeanUtils.copyProperties(project, excelBaseProject);
                        if (project.getState() == 1){
                            excelBaseProject.setState("启用");
                        }else if (project.getState() == 0){
                            excelBaseProject.setState("禁用");
                        }
                        if (project.getDirectConsumption() == 1){
                            excelBaseProject.setDirectConsumption("是");
                        }else if (project.getDirectConsumption() == 0){
                            excelBaseProject.setDirectConsumption("否");
                        }
                        if(null != project.getIsCooperation()){
                            if (project.getIsCooperation() == 1){
                                excelBaseProject.setIsCooperation("是");
                            }else if (project.getIsCooperation() == 0){
                                excelBaseProject.setIsCooperation("否");
                            }
                        }
                        if(null != project.getNoDiscount()){
                            if (project.getNoDiscount() == 1){
                                excelBaseProject.setNoDiscount("否");
                            }else if (project.getNoDiscount() == 0){
                                excelBaseProject.setNoDiscount("是");
                            }
                        }
                        if(null != project.getIsCardPay()){
                            if (project.getIsCardPay() == 1){
                                excelBaseProject.setIsCardPay("否");
                            }else if (project.getIsCardPay() == 0){
                                excelBaseProject.setIsCardPay("是");
                            }
                        }
                        if(null != project.getSmokeCommissionWay()){
                            if (project.getSmokeCommissionWay() == 1){
                                excelBaseProject.setSmokeCommissionWay("比例");
                            }else if (project.getSmokeCommissionWay() == 0){
                                excelBaseProject.setSmokeCommissionWay("固定");
                            }
                        }
//                if(null != project.getStoreType()){
//                    if (project.getStoreType() == 1){
//                        excelBaseProject.setStoreType("美容店");
//                    }else if (project.getStoreType() == 0){
//                        excelBaseProject.setIsCooperation("美发店");
//                    }
//                }
                        excelBaseProjects.add(excelBaseProject);
                    }
                    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();
                    Comparator<ExcelBaseProject> comparing = Comparator.comparing(ExcelBaseProject::getProjectNum);
//                    Collections.sort(excelBaseProjects,comparing);
                    Collections.sort(excelBaseProjects,comparing.reversed());
                    excelWriter.fill(excelBaseProjects, writeSheet);
                    out.flush();
                }else{
                    List<Long> projectTypes = new ArrayList<>();

                    if(null != projectRequest.getProjectTypeName()){
                        ProjectTypeRequest projectRequest1 = new ProjectTypeRequest();
                        projectRequest1.setProjectTypeName(projectRequest.getProjectTypeName());
                        projectRequest1.setStoreId(projectRequest.getStoreId());
                        List<ProjectTypeRequest> menuId = ssmProjectTypeService.getMenuId(projectRequest1);
                        for (ProjectTypeRequest projectTypeRequest : menuId) {
                            projectTypes.add(projectTypeRequest.getId());
                        }
                    }




                    Example example = new Example(BaseProject.class);
                    Example.Criteria criteria = example.createCriteria();
                    example.setOrderByClause("project_num desc");
                    if (StringUtils.isNotBlank(projectRequest.getProjectNum())){
                        criteria.andLike("projectNum","%" + projectRequest.getProjectNum() + "%");
                    }
                    if (StringUtils.isNotBlank(projectRequest.getProjectName())){
                        criteria.andLike("projectName","%" + projectRequest.getProjectName() + "%");
                    }
                    if (projectTypes.size()>0){
                        criteria.andIn("projectTypeId",projectTypes);
                    }
                    if (projectRequest.getState() != null){
                        criteria.andEqualTo("state",projectRequest.getState());
                    }

                    criteria.andEqualTo("storeId",projectRequest.getStoreId());

                    if (projectRequest.getDirectConsumption() != null){
                        criteria.andEqualTo("directConsumption",projectRequest.getDirectConsumption());
                    }
                    if (projectRequest.getType() != null){
                        criteria.andBetween("founderDatetime", DateUtils.diffDay(new Date(), -7), new Date());
                    }
                    List<BaseProject> list = ssmProjectService.selectByExample(example);
                    List<ExcelBaseProject> excelBaseProjects = new ArrayList<>();
                    for (BaseProject project  : list) {
                        ExcelBaseProject excelBaseProject = new ExcelBaseProject();
                        BeanUtils.copyProperties(project, excelBaseProject);
                        if(project.getModifyBy()!=null){
                            excelBaseProject.setModifyBy(project.getModifyBy());
                        }
                        if(project.getFounderDatetime()!=null){
                            excelBaseProject.setFounderDatetime(project.getFounderDatetime());
                        }
                        if(project.getModifyDatetime()!=null){
                            excelBaseProject.setModifyDatetime(project.getModifyDatetime());
                        }
                        if (project.getState() == 1){
                            excelBaseProject.setState("启用");
                        }else if (project.getState() == 0){
                            excelBaseProject.setState("禁用");
                        }
                        if (project.getDirectConsumption() == 1){
                            excelBaseProject.setDirectConsumption("是");
                        }else if (project.getDirectConsumption() == 0){
                            excelBaseProject.setDirectConsumption("否");
                        }
                        if(null != project.getIsCooperation()){
                            if (project.getIsCooperation() == 1){
                                excelBaseProject.setIsCooperation("是");
                            }else if (project.getIsCooperation() == 0){
                                excelBaseProject.setIsCooperation("否");
                            }
                        }
                        if(null != project.getNoDiscount()){
                            if (project.getNoDiscount() == 1){
                                excelBaseProject.setNoDiscount("否");
                            }else if (project.getNoDiscount() == 0){
                                excelBaseProject.setNoDiscount("是");
                            }
                        }
                        if(null != project.getIsCardPay()){
                            if (project.getIsCardPay() == 1){
                                excelBaseProject.setIsCardPay("否");
                            }else if (project.getIsCardPay() == 0){
                                excelBaseProject.setIsCardPay("是");
                            }
                        }
                        if(null != project.getSmokeCommissionWay()){
                            if (project.getSmokeCommissionWay() == 1){
                                excelBaseProject.setSmokeCommissionWay("比例");
                            }else if (project.getSmokeCommissionWay() == 0){
                                excelBaseProject.setSmokeCommissionWay("固定");
                            }
                        }
//                if(null != project.getStoreType()){
//                    if (project.getStoreType() == 1){
//                        excelBaseProject.setStoreType("美容店");
//                    }else if (project.getStoreType() == 0){
//                        excelBaseProject.setIsCooperation("美发店");
//                    }
//                }
                        excelBaseProjects.add(excelBaseProject);
                    }
//                    excelBaseProjects.stream().sorted().var;
                    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(excelBaseProjects, writeSheet);
                    out.flush();
                }
            }else{
                Example example = new Example(BaseProject.class);
                Example.Criteria criteria = example.createCriteria();
                example.setOrderByClause("project_num desc");
                if (StringUtils.isNotBlank(projectRequest.getProjectNum())){
                    criteria.andLike("projectNum","%" + projectRequest.getProjectNum() + "%");
                }
                if (StringUtils.isNotBlank(projectRequest.getProjectName())){
                    criteria.andLike("projectName","%" + projectRequest.getProjectName() + "%");
                }
                if (StringUtils.isNotBlank(projectRequest.getProjectTypeName())){
                    criteria.andLike("projectTypeName","%" + projectRequest.getProjectTypeName() + "%");
                }
                if (null == projectRequest.getProjectTypeId()){
                    criteria.andEqualTo("projectTypeId",projectRequest.getProjectTypeId());
                }
                if (projectRequest.getState() != null){
                    criteria.andEqualTo("state",projectRequest.getState());
                }

                criteria.andEqualTo("storeId",projectRequest.getStoreId());

                if (projectRequest.getDirectConsumption() != null){
                    criteria.andEqualTo("directConsumption",projectRequest.getDirectConsumption());
                }
                if (projectRequest.getType() != null){
                    criteria.andBetween("founderDatetime", DateUtils.diffDay(new Date(), -7), new Date());
                }
                List<BaseProject> list = ssmProjectService.selectByExample(example);
                List<ExcelBaseProject> excelBaseProjects = new ArrayList<>();
                for (BaseProject project  : list) {
                    ExcelBaseProject excelBaseProject = new ExcelBaseProject();
                    BeanUtils.copyProperties(project, excelBaseProject);
//                    excelBaseProject.setFounderDatetime(project.getFounderDatetime());
//                    excelBaseProject.setModifyDatetime(project.getModifyDatetime());
                    if (project.getState() == 1){
                        excelBaseProject.setState("启用");
                    }else if (project.getState() == 0){
                        excelBaseProject.setState("禁用");
                    }
                    if (project.getDirectConsumption() == 1){
                        excelBaseProject.setDirectConsumption("是");
                    }else if (project.getDirectConsumption() == 0){
                        excelBaseProject.setDirectConsumption("否");
                    }
                    if(null != project.getIsCooperation()){
                        if (project.getIsCooperation() == 1){
                            excelBaseProject.setIsCooperation("是");
                        }else if (project.getIsCooperation() == 0){
                            excelBaseProject.setIsCooperation("否");
                        }
                    }
                    if(null != project.getNoDiscount()){
                        if (project.getNoDiscount() == 1){
                            excelBaseProject.setNoDiscount("否");
                        }else if (project.getNoDiscount() == 0){
                            excelBaseProject.setNoDiscount("是");
                        }
                    }
                    if(null != project.getIsCardPay()){
                        if (project.getIsCardPay() == 1){
                            excelBaseProject.setIsCardPay("否");
                        }else if (project.getIsCardPay() == 0){
                            excelBaseProject.setIsCardPay("是");
                        }
                    }
                    if(null != project.getSmokeCommissionWay()){
                        if (project.getSmokeCommissionWay() == 1){
                            excelBaseProject.setSmokeCommissionWay("比例");
                        }else if (project.getSmokeCommissionWay() == 0){
                            excelBaseProject.setSmokeCommissionWay("固定");
                        }
                    }
//                if(null != project.getStoreType()){
//                    if (project.getStoreType() == 1){
//                        excelBaseProject.setStoreType("美容店");
//                    }else if (project.getStoreType() == 0){
//                        excelBaseProject.setIsCooperation("美发店");
//                    }
//                }
//                    excelBaseProject.setSmokeCommissionWay();
                    excelBaseProjects.add(excelBaseProject);
                }
                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(excelBaseProjects, writeSheet);
                out.flush();
            }


        } catch (Exception e) {
            log.error("SsmProjectController.export:",e);
        } finally {
            //destFile.delete();
            // 别忘记关闭流
            excelWriter.finish();
        }
    }


    @ApiOperation(value = "门店项目批量导入  门店端-员工列表-门店项目批量导入", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/import")
    public GenericResponse proImport(MultipartFile multipartFile, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String key = SessionHelp.getLoginAccount(session);
        List<ExcelBaseProject> list = null;
        try {
            list = EasyExcelUtil.simpleWrite(multipartFile, ExcelBaseProject.class);
        } catch (SmsException e) {
            log.error("SsmProjectController.proImport:",e);
            return genericResponse;
        }
        List<BaseProject> projectList = new ArrayList<>();
        for (ExcelBaseProject excelBaseProject : list) {
            BaseProject baseProject = new BaseProject();
            BeanUtils.copyProperties(excelBaseProject, baseProject);
            if (excelBaseProject.getState().equals("启用")){
                baseProject.setState(1);
            }else if (excelBaseProject.getState().equals("禁用")){
                baseProject.setState(0);
            }
            if (excelBaseProject.getDirectConsumption().equals("是")){
                baseProject.setDirectConsumption(1);
            }else if (excelBaseProject.getDirectConsumption().equals("否")){
                baseProject.setDirectConsumption(0);
            }

            if(null != excelBaseProject.getIsCooperation()){
                if (excelBaseProject.getIsCooperation().equals("是")){
                    baseProject.setIsCooperation(1);
                }else if (excelBaseProject.getIsCooperation().equals("否")){
                    baseProject.setIsCooperation(0);
                }
            }
            if(null != excelBaseProject.getNoDiscount()){
                if (excelBaseProject.getNoDiscount().equals("是")){
                    baseProject.setNoDiscount(0);
                }else if (excelBaseProject.getNoDiscount().equals("否")){
                    baseProject.setNoDiscount(1);
                }
            }
            if(null != excelBaseProject.getIsCardPay()){
                if (excelBaseProject.getIsCardPay().equals("是")){
                    baseProject.setIsCardPay(0);
                }else if (excelBaseProject.getIsCardPay().equals("否")){
                    baseProject.setIsCardPay(1);
                }
            }
            if(null != excelBaseProject.getSmokeCommissionWay()){
                if (excelBaseProject.getSmokeCommissionWay().equals("固定")){
                    baseProject.setSmokeCommissionWay(0);
                }else if (excelBaseProject.getSmokeCommissionWay().equals("比例")){
                    baseProject.setSmokeCommissionWay(1);
                }
            }
//            if(null != excelBaseProject.getStoreType()){
//                if (excelBaseProject.getStoreType().equals("美容店")){
//                    baseProject.setStoreType(1);
//                }else if (excelBaseProject.getStoreType().equals("美发店")){
//                    baseProject.setStoreType(0);
//                }
//            }
            projectList.add(baseProject);
        }
        List<BaseProject> unusualList = new ArrayList<>();
        try {
            unusualList = ssmProjectService.insertBatch2(projectList,storeId, storeName, key);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmProjectController.proImport:",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (!unusualList.isEmpty()) {
            genericResponse.setRows(unusualList);
        }
        return genericResponse;
    }

    @ApiOperation(value = "分派本店项目到其他门店", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/assignProjectList")
    public GenericResponse assignProjectList(@RequestBody  List<ProjectRequest> projectRequest, HttpSession session) {
        GenericResponse<BaseProject> genericResponse = new GenericResponse<>();
        String phone = SessionHelp.getLoginAccount(session);
        for (ProjectRequest request : projectRequest) {
            request.setUpdateCommPhone(phone);
        }
        String userNum = SessionHelp.getLoginAccount(session);
        int i = 0;
        try {
            i = ssmProjectService.assignProjectList(projectRequest,userNum);
        }catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e) {
            log.error("SsmProjectController.updateStates", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "分派本店项目到其他门店", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/assignProject")
    public GenericResponse assignProject(@RequestBody ProjectRequest projectRequest, HttpSession session) {
        GenericResponse<BaseProject> genericResponse = new GenericResponse<>();
        String userNum = SessionHelp.getLoginAccount(session);
        String phone = SessionHelp.getLoginAccount(session);
        projectRequest.setUpdateCommPhone(phone);
        int i = 0;
        try {
            i = ssmProjectService.assignProject(projectRequest,userNum);
        }catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e) {
            log.error("SsmProjectController.updateStates", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }


    @ApiOperation(value = "引入本门店总店下的其他门店项目", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/importProject")
    public GenericResponse importProject(@RequestBody  ProjectRequest projectRequest, HttpSession session) {
        GenericResponse<BaseProject> genericResponse = new GenericResponse<>();
        List<BaseProject> baseProjects = projectRequest.getBaseProjects();
        String userNum = SessionHelp.getLoginAccount(session);
        for (BaseProject request: baseProjects) {
            request.setStoreId(SessionHelp.getStoreId(session));
            request.setStoreName(SessionHelp.getStoreName(session));
        }

        int i = 0;
        try {
            i = ssmProjectService.importProject(baseProjects,userNum);
        }catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e) {
            log.error("SsmProjectController.updateStates", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }



    @ApiOperation(value = "查询项目提成复制 门店端-项目-项目提成复制", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/copyProject")
    public GenericResponse coupyProject(@RequestBody ProjectRequest projectRequest, HttpSession session) {
        GenericResponse<BaseProject> genericResponse = new GenericResponse();
        if(null == projectRequest.getStoreId()){
            projectRequest.setStoreId(SessionHelp.getStoreId(session));
        }
        BaseProject project=new BaseProject();
        List<BaseProject> list=new ArrayList<>();
        try {
             project = ssmProjectService.copyProject(projectRequest);
            list.add(project);
        }catch (SmsException e) {
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        } catch (Exception e) {
            log.error("SsmProjectController.page", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        //pageResponse.setData(project);
        genericResponse.setRows(list);
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }

}
