package <%=packageName%>.web.rest;

<%_
const pageName = ormTool !== 'mybatis' ? 'Page': 'IPage';
const pageType = ormTool !== 'mybatis' ? 'Pageable': 'Page';
const specificationType = ormTool !== 'mybatis' ? 'Specification' : 'QueryWrapper';
const specificationInstance = ormTool !== 'mybatis' ? 'specification' : 'queryWrapper';
const pageGetContent = ormTool !== 'mybatis' ? 'getContent': 'getRecords';
const pageUtil = ormTool !== 'mybatis' ? 'PaginationUtil': 'IPageUtil';
const pageInstance = ormTool !== 'mybatis' ? 'pageable' : 'PageableUtils.toPage(pageable)';
_%>
import cn.hutool.core.bean.BeanUtil;
import <%=packageName%>.domain.BigScreenMap;
import <%=packageName%>.service.BigScreenMapService;
import <%=packageName%>.service.CommonConditionQueryService;
import <%=packageName%>.service.dto.BigScreenConfigDTO;
import <%=packageName%>.service.dto.BigScreenDTO;
import <%=packageName%>.web.rest.errors.BadRequestAlertException;
import <%=packageName%>.service.dto.BigScreenMapDTO;
import <%=packageName%>.service.criteria.BigScreenMapCriteria;
import <%=packageName%>.service.BigScreenMapQueryService;

import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
<%_ if (ormTool !== 'mybatis') { _%>
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import tech.jhipster.web.util.PaginationUtil;
<%_ } else { _%>
import <%= packageName %>.util.web.IPageUtil;
import <%= packageName %>.util.web.PageableUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
<%_ } _%>
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.util.PoiPublicUtil;

import org.apache.poi.ss.usermodel.Workbook;


import javax.validation.Valid;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.Optional;
import java.util.UUID;

// jhipster-needle-add-import - JHipster will add getters and setters here, do not remove

/**
 * REST controller for managing {@link <%=packageName%>.domain.BigScreenMap}.
 */
@RestController
@RequestMapping("/api")
public class BigScreenMapResource {

    private final Logger log = LoggerFactory.getLogger(BigScreenMapResource.class);

    private static final String ENTITY_NAME = "dataViewBigScreenMap";

    @Value("${jhipster.clientApp.name}")
    private String applicationName;

    private final BigScreenMapService bigScreenMapService;

    private final CommonConditionQueryService commonConditionQueryService;

    private final BigScreenMapQueryService bigScreenMapQueryService;

    public BigScreenMapResource(BigScreenMapService bigScreenMapService, CommonConditionQueryService commonConditionQueryService, BigScreenMapQueryService bigScreenMapQueryService) {
        this.bigScreenMapService = bigScreenMapService;
        this.commonConditionQueryService = commonConditionQueryService;
        this.bigScreenMapQueryService = bigScreenMapQueryService;
    }

    /**
     * {@code POST  /big-screen-maps} : Create a new bigScreenMap.
     *
     * @param bigScreenMapDTO the bigScreenMapDTO to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new bigScreenMapDTO, or with status {@code 400 (Bad Request)} if the bigScreenMap has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("/big-screen-maps")
    public ResponseEntity<BigScreenMapDTO> createBigScreenMap(@Valid @RequestBody BigScreenMapDTO bigScreenMapDTO) throws URISyntaxException {
        log.debug("REST request to save BigScreenMap : {}", bigScreenMapDTO);
        if (bigScreenMapDTO.getId() != null) {
            throw new BadRequestAlertException("A new bigScreenMap cannot already have an ID", ENTITY_NAME, "idexists");
        }
        BigScreenMapDTO result = bigScreenMapService.save(bigScreenMapDTO);
        return ResponseEntity.created(new URI("/api/big-screen-maps/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * {@code Get  /big-screen-maps/data/{id}} : get a map data for id.
     *
     * @param id the bigScreenMaoDTO  id .
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new bigScreenDTO, or with status {@code 400 (Bad Request)} if the bigScreen has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @GetMapping("/big-screen-maps/data/{id}")
    public ResponseEntity<String> createNewBigScreen(@PathVariable Long id) throws URISyntaxException {
        log.debug("REST get data to id : {}", id);
        Optional<BigScreenMapDTO> result = bigScreenMapService.findOne(id);
        if (result.isPresent()) {
            return ResponseEntity.ok(result.get().getData());
        } else {
            return ResponseEntity.ok("");
        }
    }

    /**
     * {@code PUT  /big-screen-maps} : Updates an existing bigScreenMap.
     *
     * @param bigScreenMapDTO the bigScreenMapDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated bigScreenMapDTO,
     * or with status {@code 400 (Bad Request)} if the bigScreenMapDTO is not valid,
     * or with status {@code 500 (Internal Server Error)} if the bigScreenMapDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PutMapping("/big-screen-maps")
    public ResponseEntity<BigScreenMapDTO> updateBigScreenMap(@Valid @RequestBody BigScreenMapDTO bigScreenMapDTO) throws URISyntaxException {
        log.debug("REST request to update BigScreenMap : {}", bigScreenMapDTO);
        if (bigScreenMapDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        BigScreenMapDTO result = bigScreenMapService.save(bigScreenMapDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, bigScreenMapDTO.getId().toString()))
            .body(result);
    }
    /**
     * {@code GET  /big-screen-maps} : get all the bigScreenMaps.
     *

     * @param pageable the pagination information.
     * @param criteria the criteria which the requested entities should match.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of bigScreenMaps in body.
     */
    @GetMapping("/big-screen-maps")
    public ResponseEntity<List<BigScreenMapDTO>> getAllBigScreenMaps(BigScreenMapCriteria criteria, Pageable pageable, @RequestParam(value = "listModelName", required = false) String listModelName, @RequestParam(value = "commonQueryId", required = false) Long commonQueryId) throws ClassNotFoundException  {
        log.debug("REST request to get BigScreenMaps by criteria: {}", criteria);
        <%= pageName%><BigScreenMapDTO> page;
        if (listModelName != null) {
            if (commonQueryId != null) {
                <%= specificationType%> <%= specificationInstance%> = commonConditionQueryService.create<%= specificationType%>(commonQueryId);
                page = bigScreenMapQueryService.selectByCustomEntity(listModelName, criteria<%= ormTool === 'hibernate' ? ', null' : ''%>, <%= specificationInstance%>, <%= pageInstance %>);
            } else {
                page = bigScreenMapQueryService.selectByCustomEntity(listModelName, criteria<%= ormTool === 'hibernate' ? ', null' : ''%>, null, <%= pageInstance %>);
            }
        } else {
            if (commonQueryId != null) {
                <%= specificationType%> <%= specificationInstance%> = commonConditionQueryService.create<%= specificationType%>(commonQueryId);
                page = bigScreenMapQueryService.findBy<%= specificationType%>(<%= specificationInstance%>, <%= pageInstance %>);
            } else {
                page = bigScreenMapQueryService.findByCriteria(criteria, pageable);
            }
        }
        HttpHeaders headers = <%= pageUtil%>.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
        return ResponseEntity.ok().headers(headers).body(page.<%= pageGetContent%>());
    }

    /**
    * {@code GET  /big-screen-maps/count} : count all the bigScreenMaps.
    *
    * @param criteria the criteria which the requested entities should match.
    * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the count in body.
    */
    @GetMapping("/big-screen-maps/count")
    public ResponseEntity<Long> countBigScreenMaps(BigScreenMapCriteria criteria) {
        log.debug("REST request to count BigScreenMaps by criteria: {}", criteria);
        return ResponseEntity.ok().body(bigScreenMapQueryService.countByCriteria(criteria));
    }


    /**
     * {@code GET  /big-screen-maps/:id} : get the "id" bigScreenMap.
     *
     * @param id the id of the bigScreenMapDTO to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the bigScreenMapDTO, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/big-screen-maps/{id}")

    public ResponseEntity<BigScreenMapDTO> getBigScreenMap(@PathVariable Long id) {
        log.debug("REST request to get BigScreenMap : {}", id);
        Optional<BigScreenMapDTO> bigScreenMapDTO = bigScreenMapService.findOne(id);
        return ResponseUtil.wrapOrNotFound(bigScreenMapDTO);
    }

    /**
     * GET  /big-screen-maps/export : export the bigScreenMaps.
     *
     *
     * @return the ResponseEntity with status 200 (OK) and with body the bigScreenMapDTO, or with status 404 (Not Found)
     */
    @GetMapping("/big-screen-maps/export")
    public ResponseEntity<Void> exportToExcel() throws IOException {
        <%= pageName%><BigScreenMapDTO> page = bigScreenMapService.findAll(<% if (ormTool !== 'mybatis') { %>Pageable.unpaged()<% } else { %>null<% } %>);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("计算机一班学生","学生"),
            BigScreenMapDTO.class, page.<%= pageGetContent%>());
        File savefile = new File("export");
        if (!savefile.exists()) {
            savefile.mkdirs();
        }
        FileOutputStream fos = new FileOutputStream("export/personDTO_2018_09_10.xls");
        workbook.write(fos);
        fos.close();
        return ResponseEntity.ok().build();
    }

    /**
     * POST  /big-screen-maps/import : import the bigScreenMaps from excel file.
     *
     *
     * @return the ResponseEntity with status 200 (OK) and with body the bigScreenMapDTO, or with status 404 (Not Found)
     */
    @PostMapping("/big-screen-maps/import")
    public ResponseEntity<Void> exportToExcel(MultipartFile file) throws IOException {
        String fileRealName = file.getOriginalFilename();//获得原始文件名;
        int pointIndex =  fileRealName.lastIndexOf(".");//点号的位置
        String fileSuffix = fileRealName.substring(pointIndex);//截取文件后缀
        String fileNewName = UUID.randomUUID().toString();//文件new名称时间戳
        String saveFileName = fileNewName.concat(fileSuffix);//文件存取名
        String filePath  = "import" ;
        File path = new File(filePath); //判断文件路径下的文件夹是否存在，不存在则创建
        if (!path.exists()) {
            path.mkdirs();
        }
        File savedFile = new File(filePath,saveFileName);
        file.transferTo(savedFile);
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        List<BigScreenMapDTO> list = ExcelImportUtil.importExcel(savedFile, BigScreenMapDTO.class, params);
        list.forEach(bigScreenMapService::save);
        return ResponseEntity.ok().build();
    }

    /**
     * {@code DELETE  /big-screen-maps/:id} : delete the "id" bigScreenMap.
     *
     * @param id the id of the bigScreenMapDTO to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/big-screen-maps/{id}")
    public ResponseEntity<Void> deleteBigScreenMap(@PathVariable Long id) {
        log.debug("REST request to delete BigScreenMap : {}", id);
        bigScreenMapService.delete(id);
        return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())).build();
    }

    /**
    * {@code DELETE  /big-screen-maps} : delete all the "ids" BigScreenMaps.
    *
    * @param ids the ids of the articleDTO to delete.
    * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
    */
    @DeleteMapping("/big-screen-maps")
    public ResponseEntity<Void> deleteBigScreenMapsByIds(@RequestParam("ids") ArrayList<Long> ids) {
        log.debug("REST request to delete BigScreenMaps : {}", ids);
        if (ids != null) {
            ids.forEach(bigScreenMapService::delete);
        }
        return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, (ids != null ? ids.toString() : "NoIds"))).build();
    }


    /**
     * {@code PUT  /big-screen-maps/specified-fields} : Updates an existing bigScreenMap by specified fields.
     *
     * @param bigScreenMapDTOAndSpecifiedFields the bigScreenMapDTO and specifiedFields to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated bigScreenMapDTO,
     * or with status {@code 400 (Bad Request)} if the bigScreenMapDTO is not valid,
     * or with status {@code 500 (Internal Server Error)} if the bigScreenMapDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PutMapping("/big-screen-maps/specified-fields")
    public ResponseEntity<BigScreenMapDTO> updateBigScreenMapBySpecifiedFields(@RequestBody BigScreenMapDTOAndSpecifiedFields bigScreenMapDTOAndSpecifiedFields) throws URISyntaxException {
        log.debug("REST request to update BigScreenMap : {}", bigScreenMapDTOAndSpecifiedFields);
        BigScreenMapDTO bigScreenMapDTO = bigScreenMapDTOAndSpecifiedFields.getBigScreenMap();
        Set<String> specifiedFields = bigScreenMapDTOAndSpecifiedFields.getSpecifiedFields();
        if (bigScreenMapDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        BigScreenMapDTO result = bigScreenMapService.updateBySpecifiedFields(bigScreenMapDTO,specifiedFields);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, bigScreenMapDTO.getId().toString()))
            .body(result);
    }

    /**
     * {@code PUT  /big-screen-maps/specified-field} : Updates an existing bigScreenMap by specified field.
     *
     * @param bigScreenMapDTOAndSpecifiedFields the bigScreenMapDTO and specifiedFields to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated bigScreenMapDTO,
     * or with status {@code 400 (Bad Request)} if the bigScreenMapDTO is not valid,
     * or with status {@code 500 (Internal Server Error)} if the bigScreenMapDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PutMapping("/big-screen-maps/specified-field")
    public ResponseEntity<BigScreenMapDTO> updateBigScreenMapBySpecifiedField(@RequestBody BigScreenMapDTOAndSpecifiedFields bigScreenMapDTOAndSpecifiedFields, BigScreenMapCriteria criteria) throws URISyntaxException {
        log.debug("REST request to update BigScreenMap : {}", bigScreenMapDTOAndSpecifiedFields);
        BigScreenMapDTO bigScreenMapDTO = bigScreenMapDTOAndSpecifiedFields.getBigScreenMap();
        String fieldName = bigScreenMapDTOAndSpecifiedFields.getSpecifiedField();
        if (bigScreenMapDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        BigScreenMapDTO result = bigScreenMapService.updateBySpecifiedField(bigScreenMapDTO, fieldName);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
            .body(result);
    }
    // jhipster-needle-rest-resource-add-api - JHipster will add getters and setters here, do not remove

    private static class BigScreenMapDTOAndSpecifiedFields {
        private BigScreenMapDTO bigScreenMap;
        private Set<String> specifiedFields;
        private String specifiedField;

        private BigScreenMapDTO getBigScreenMap() {
            return bigScreenMap;
        }

        private void setBigScreenMap(BigScreenMapDTO bigScreenMap) {
            this.bigScreenMap = bigScreenMap;
        }

        private Set<String> getSpecifiedFields() {
            return specifiedFields;
        }

        private void setSpecifiedFields(Set<String> specifiedFields) {
            this.specifiedFields = specifiedFields;
        }

        public String getSpecifiedField() {
            return specifiedField;
        }

        public void setSpecifiedField(String specifiedField) {
            this.specifiedField = specifiedField;
        }
    }
}
