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.BaseProjectType;
import com.ssm.manage.entity.SmsException;
import com.ssm.manage.excelEntity.ExcelBaseProjectType;
import com.ssm.manage.query.ProjectTypeRequest;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.service.SsmProjectTypeService;
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.ArrayList;
import java.util.List;

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

    @Autowired
    private SsmProjectTypeService ssmProjectTypeService;

    @ApiOperation(value = "分页查询项目类别  门店端-项目类别-分页查询项目类别",httpMethod = "POST",response = PageResponse.class)
    @RequestMapping("/page")
    public PageResponse selectPage(@RequestBody ProjectTypeRequest projectTypeRequest,HttpSession session){
        PageResponse<BaseProjectType> pageResponse = new PageResponse<>();
        PageInfo<BaseProjectType> pageInfo = new PageInfo<>();
        projectTypeRequest.setStoreId(SessionHelp.getStoreId(session));
        try {
            pageInfo = ssmProjectTypeService.selectPage(projectTypeRequest);
        }catch (Exception e){
            log.error("SsmProjectTypeController.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 ProjectTypeRequest projectTypeRequest, HttpSession session){
        GenericResponse<BaseProjectType> genericResponse = new GenericResponse<>();
        if (StringUtils.isBlank(projectTypeRequest.getProjectTypeNum())){
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"项目类别编码");
            return genericResponse;
        }
        if (StringUtils.isBlank(projectTypeRequest.getProjectTypeName())){
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S,"项目类别名称");
            return genericResponse;
        }
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String key = SessionHelp.getLoginAccount(session);
        projectTypeRequest.setStoreId(storeId);
        projectTypeRequest.setStoreName(storeName);
        int i = 0;
        try {
            i = ssmProjectTypeService.addProjectType(projectTypeRequest,key);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmProjectTypeController.add",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0){
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "查询所有项目类别   门店端-项目类别-项目添加-查询所有项目类别",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/list")
    public GenericResponse list(HttpSession session){
        GenericResponse<BaseProjectType> genericResponse = new GenericResponse<>();

        Long storeId = SessionHelp.getStoreId(session);
        List<BaseProjectType> list = new ArrayList<>();
        try {
            list = ssmProjectTypeService.list(storeId);
        }catch (Exception e){
            log.error("SsmProjectTypeController.add",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setRows(list);
        return genericResponse;
    }
    @ApiOperation(value = "查询所有项目类别   门店端-项目类别-项目添加-查询所有项目类别(树形)",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/queryTree")
    public GenericResponse queryTree(HttpSession session){
        GenericResponse<ProjectTypeRequest> genericResponse = new GenericResponse<>();

        Long storeId = SessionHelp.getStoreId(session);
        ProjectTypeRequest projectTypeRequest = new ProjectTypeRequest();
        projectTypeRequest.setStoreId(storeId);
        List<ProjectTypeRequest> list = new ArrayList<>();
        try {
            list = ssmProjectTypeService.getMenu(projectTypeRequest);
        }catch (Exception e){
            log.error("SsmProjectTypeController.add",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setRows(list);
        return genericResponse;
    }

    @ApiOperation(value = "项目类别修改  门店端-项目类别-项目类别修改",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/update")
    public GenericResponse update(@RequestBody ProjectTypeRequest projectTypeRequest, HttpSession session){
        GenericResponse<BaseProjectType> genericResponse = new GenericResponse<>();

        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String key = SessionHelp.getLoginAccount(session);
        projectTypeRequest.setStoreId(storeId);
        projectTypeRequest.setStoreName(storeName);
        int i = 0;
        try {
            i = ssmProjectTypeService.updateProjectType(projectTypeRequest,key);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmProjectTypeController.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("/delete")
    public GenericResponse delete(@RequestBody ProjectTypeRequest projectTypeRequest){
        GenericResponse<BaseProjectType> genericResponse = new GenericResponse<>();

        int i = 0;
        try {
            i = ssmProjectTypeService.deleteProjectType(projectTypeRequest);
        }catch (SmsException e){
            log.error("SsmProjectTypeController.delete",e);
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmProjectTypeController.delete",e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0){
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "项目类别状态修改  门店端-项目类别-项目类别状态修改",httpMethod = "POST",response = GenericResponse.class)
    @RequestMapping("/updateStates")
    public GenericResponse updateStates(@RequestBody ProjectTypeRequest projectTypeRequest){
        GenericResponse<BaseProjectType> genericResponse = new GenericResponse<>();

        int i = 0;
        try {
            i = ssmProjectTypeService.updateStates(projectTypeRequest);
        }catch (SmsException e){
            log.error("SsmProjectTypeController.updateStates",e);
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e){
            log.error("SsmProjectTypeController.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("/download")
    public void download(HttpSession session, HttpServletResponse response) {

        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        ExcelWriter excelWriter = null;
        OutputStream out = null;
        try {
            String fileName = "projectType";
            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/projectType.xlsx");

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

    @ApiOperation(value = "门店项目类别批量导出  门店端-项目类别列表-门店项目类别批量导出", httpMethod = "POST", response = GenericResponse.class)
    @RequestMapping("/export")
    public void export(@RequestBody ProjectTypeRequest projectTypeRequest, HttpSession session) {
        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
        // {} 代表普通变量 {.} 代表是list的变量 {前缀.} 前缀可以区分不同的list
        ExcelWriter excelWriter = null;
        OutputStream out = null;
        projectTypeRequest.setStoreId(SessionHelp.getStoreId(session));
        projectTypeRequest.setStoreName(SessionHelp.getStoreName(session));
        BaseProjectType baseProjectType = new BaseProjectType();
        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/projectType.xlsx");
//            BeanUtils.copyProperties(projectTypeRequest, baseProjectType);
//            List<BaseProjectType> list = ssmProjectTypeService.select(baseProjectType);
            Example example = new Example(BaseProjectType.class);
            Example.Criteria criteria = example.createCriteria();
            if (StringUtils.isNotBlank(projectTypeRequest.getProjectTypeNum())){
                criteria.andLike("projectTypeNum", "%" + projectTypeRequest.getProjectTypeNum() + "%");
            }
            if (StringUtils.isNotBlank(projectTypeRequest.getProjectTypeName())){
                criteria.andLike("projectTypeName","%" + projectTypeRequest.getProjectTypeName() + "%");
            }
            if (projectTypeRequest.getState() != null){
                criteria.andEqualTo("state",projectTypeRequest.getState());
            }

            criteria.andEqualTo("storeId",projectTypeRequest.getStoreId());
            List<ExcelBaseProjectType> excelBaseProjectTypeList = new ArrayList<>();
            List<BaseProjectType> list = ssmProjectTypeService.selectByExample(example);
            for (BaseProjectType projectType : list) {
                ExcelBaseProjectType excelBaseProjectType = new ExcelBaseProjectType();
                BeanUtils.copyProperties(projectType, excelBaseProjectType);
                if (projectType.getState() == 1){
                    excelBaseProjectType.setState("启用");
                }else if (projectType.getState() == 0){
                    excelBaseProjectType.setState("禁用");
                }
                if(null != projectType.getParentId()){
                    for (BaseProjectType type : list) {
                        if(type.getId().equals(projectType.getParentId())){
                            excelBaseProjectType.setParentNum(type.getProjectTypeNum());
                        }
                    }
                }
                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("/import")
    public GenericResponse proTypeImport(MultipartFile multipartFile, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        Long storeId = SessionHelp.getStoreId(session);
        String storeName = SessionHelp.getStoreName(session);
        String key = SessionHelp.getLoginAccount(session);
        List<ExcelBaseProjectType> list = null;
        try {
            list = EasyExcelUtil.simpleWrite(multipartFile, ExcelBaseProjectType.class);
        } catch (SmsException e) {
            log.error("SsmProjectTypeController.proTypeImport:",e);
            return genericResponse;
        }
        List<BaseProjectType> projectTypeList = new ArrayList<>();
        for (ExcelBaseProjectType excelBaseProjectType : list) {
           BaseProjectType projectType = new BaseProjectType();
           BeanUtils.copyProperties(excelBaseProjectType, projectType);

           if (excelBaseProjectType.getState().equals("启用")){
               projectType.setState(1);
           }else if (excelBaseProjectType.getState().equals("禁用")){
               projectType.setState(0);
           }
           projectTypeList.add(projectType);
        }
        List<BaseProjectType> unusualList = new ArrayList<>();
        try {
            unusualList = ssmProjectTypeService.insertBatch(projectTypeList,storeId, storeName, key);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }

        if (!unusualList.isEmpty()) {
            genericResponse.setRows(unusualList);
        }
        return genericResponse;

    }
}
