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 <%=packageName%>.service.BigScreenConfigService;
import <%=packageName%>.service.BigScreenService;
import <%=packageName%>.service.CommonConditionQueryService;
import <%=packageName%>.service.dto.BigScreenConfigDTO;
import <%=packageName%>.web.rest.errors.BadRequestAlertException;
import <%=packageName%>.web.rest.vm.BigScreenConfigVO;
import <%=packageName%>.service.dto.BigScreenDTO;
import <%=packageName%>.service.criteria.BigScreenCriteria;
import <%=packageName%>.service.BigScreenQueryService;

import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.beans.factory.annotation.Value;
<%_ 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.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 org.apache.poi.ss.usermodel.Workbook;


import javax.validation.Valid;
import java.io.File;
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.BigScreen}.
 */
@RestController
@RequestMapping("/api")
public class BigScreenResource {

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

    private static final String ENTITY_NAME = "bigScreenBigScreen";

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

    private final BigScreenService bigScreenService;

    private final CommonConditionQueryService commonConditionQueryService;

    private final BigScreenQueryService bigScreenQueryService;

    private final BigScreenConfigService bigScreenConfigService;

    public BigScreenResource(BigScreenService bigScreenService, CommonConditionQueryService commonConditionQueryService, BigScreenQueryService bigScreenQueryService, BigScreenConfigService bigScreenConfigService) {
        this.bigScreenService = bigScreenService;
        this.commonConditionQueryService = commonConditionQueryService;
        this.bigScreenQueryService = bigScreenQueryService;
        this.bigScreenConfigService = bigScreenConfigService;
    }

    /**
     * {@code POST  /big-screens} : Create a new bigScreen.
     *
     * @param bigScreenDTO the bigScreenDTO to create.
     * @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.
     */
    @PostMapping("/big-screens")
    public ResponseEntity<BigScreenDTO> createBigScreen(@Valid @RequestBody BigScreenDTO bigScreenDTO) throws URISyntaxException {
        log.debug("REST request to save BigScreen : {}", bigScreenDTO);
        if (bigScreenDTO.getId() != null) {
            throw new BadRequestAlertException("A new bigScreen cannot already have an ID", ENTITY_NAME, "idexists");
        }
        BigScreenDTO result = bigScreenService.save(bigScreenDTO);
        return ResponseEntity.created(new URI("/api/big-screens/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * {@code POST  /big-screens} : Create a new bigScreen.
     *
     * @param bigScreenConfigVO the bigScreenDTO to create.
     * @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.
     */
    @PostMapping("/big-screens/new")
    public ResponseEntity<BigScreenDTO> createNewBigScreen(@RequestBody BigScreenConfigVO bigScreenConfigVO) throws URISyntaxException {
        log.debug("REST request to save BigScreen : {}", bigScreenConfigVO);
        BigScreenDTO result = bigScreenService.save(bigScreenConfigVO.getVisual());
        bigScreenConfigVO.getConfig().setBigScreen(result);
        BigScreenConfigDTO configDTO = bigScreenConfigService.save(bigScreenConfigVO.getConfig());

        return ResponseEntity.created(new URI("/api/big-screens/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * {@code PUT  /big-screens} : Updates an existing bigScreen.
     *
     * @param bigScreenConfigVO the bigScreenDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated bigScreenDTO,
     * or with status {@code 400 (Bad Request)} if the bigScreenDTO is not valid,
     * or with status {@code 500 (Internal Server Error)} if the bigScreenDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PutMapping("/big-screens")
    public ResponseEntity<BigScreenDTO> updateBigScreen(@RequestBody BigScreenConfigVO bigScreenConfigVO) throws URISyntaxException {
        log.debug("REST request to update BigScreen : {}", bigScreenConfigVO);
        if (bigScreenConfigVO.getVisual().getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        BigScreenDTO result = bigScreenService.updateBySpecifiedField(bigScreenConfigVO.getVisual(), "backgroundUrl");
        bigScreenConfigService.save(bigScreenConfigVO.getConfig());
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, bigScreenConfigVO.getVisual().getId().toString()))
            .body(result);
    }
    /**
     * {@code GET  /big-screens} : get all the bigScreens.
     *

     * @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 bigScreens in body.
     */
    @GetMapping("/big-screens")
    public ResponseEntity<List<BigScreenDTO>> getAllBigScreens(BigScreenCriteria 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 BigScreens by criteria: {}", criteria);
        <%= pageName%><BigScreenDTO> page;
        if (listModelName != null) {
            if (commonQueryId != null) {
                <%= specificationType%> <%= specificationInstance%> = commonConditionQueryService.create<%= specificationType%>(commonQueryId);
                page = bigScreenQueryService.selectByCustomEntity(listModelName, criteria<%= ormTool === 'hibernate' ? ', null' : ''%>, <%= specificationInstance%>, <%= pageInstance%>);
            } else {
                page = bigScreenQueryService.selectByCustomEntity(listModelName, criteria<%= ormTool === 'hibernate' ? ', null' : ''%>, null, <%= pageInstance%>);
            }
        } else {
            if (commonQueryId != null) {
                <%= specificationType%> <%= specificationInstance%> = commonConditionQueryService.create<%= specificationType%>(commonQueryId);
                page = bigScreenQueryService.findBy<%= specificationType%>(<%= specificationInstance%>, <%= pageInstance%>);
            } else {
                page = bigScreenQueryService.findByCriteria(criteria, <%= pageInstance%>);
            }
        }
        HttpHeaders headers = <%= pageUtil%>.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
        return ResponseEntity.ok().headers(headers).body(page.<%= pageGetContent%>());
    }

    /**
    * {@code GET  /big-screens/count} : count all the bigScreens.
    *
    * @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-screens/count")
    public ResponseEntity<Long> countBigScreens(BigScreenCriteria criteria) {
        log.debug("REST request to count BigScreens by criteria: {}", criteria);
        return ResponseEntity.ok().body(bigScreenQueryService.countByCriteria(criteria));
    }


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

    public ResponseEntity<BigScreenDTO> getBigScreen(@PathVariable Long id) {
        log.debug("REST request to get BigScreen : {}", id);
        Optional<BigScreenDTO> bigScreenDTO = bigScreenService.findOne(id);
        return ResponseUtil.wrapOrNotFound(bigScreenDTO);
    }
    /**
     * GET  /big-screens/export : export the bigScreens.
     *
     *
     * @return the ResponseEntity with status 200 (OK) and with body the bigScreenDTO, or with status 404 (Not Found)
     */
    @GetMapping("/big-screens/export")
    public ResponseEntity<Void> exportToExcel() throws IOException {
        <%= pageName%><BigScreenDTO> page = bigScreenService.findAll(<% if (ormTool !== 'mybatis') { %>Pageable.unpaged()<% } else { %>null<% } %>);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("计算机一班学生","学生"),
            BigScreenDTO.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-screens/import : import the bigScreens from excel file.
     *
     *
     * @return the ResponseEntity with status 200 (OK) and with body the bigScreenDTO, or with status 404 (Not Found)
     */
    @PostMapping("/big-screens/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<BigScreenDTO> list = ExcelImportUtil.importExcel(savedFile, BigScreenDTO.class, params);
        list.forEach(bigScreenService::save);
        return ResponseEntity.ok().build();
    }

    /**
     * {@code DELETE  /big-screens/:id} : delete the "id" bigScreen.
     *
     * @param id the id of the bigScreenDTO to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/big-screens/{id}")
    public ResponseEntity<Void> deleteBigScreen(@PathVariable Long id) {
        log.debug("REST request to delete BigScreen : {}", id);
        bigScreenConfigService.delete(id);
        bigScreenService.delete(id);
        return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())).build();
    }

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

    @GetMapping("/big-screens/creator/current-user")
    public ResponseEntity<List<BigScreenDTO>> findByCreatorIsCurrentUser() {
        log.debug("REST request to get BigScreen for current user. ");
        List<BigScreenDTO> result = bigScreenService.findByCreatorIsCurrentUser();
        return ResponseEntity.ok(result);
    }
    @GetMapping("/big-screens/modifier/current-user")
    public ResponseEntity<List<BigScreenDTO>> findByModifierIsCurrentUser() {
        log.debug("REST request to get BigScreen for current user. ");
        List<BigScreenDTO> result = bigScreenService.findByModifierIsCurrentUser();
        return ResponseEntity.ok(result);
    }

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

    /**
     * {@code PUT  /big-screens/specified-field} : Updates an existing bigScreen by specified field.
     *
     * @param bigScreenDTOAndSpecifiedFields the bigScreenDTO and specifiedFields to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated bigScreenDTO,
     * or with status {@code 400 (Bad Request)} if the bigScreenDTO is not valid,
     * or with status {@code 500 (Internal Server Error)} if the bigScreenDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PutMapping("/big-screens/specified-field")
    public ResponseEntity<BigScreenDTO> updateBigScreenBySpecifiedField(@RequestBody BigScreenDTOAndSpecifiedFields bigScreenDTOAndSpecifiedFields, BigScreenCriteria criteria) throws URISyntaxException {
        log.debug("REST request to update BigScreen : {}", bigScreenDTOAndSpecifiedFields);
        BigScreenDTO bigScreenDTO = bigScreenDTOAndSpecifiedFields.getBigScreen();
        String fieldName = bigScreenDTOAndSpecifiedFields.getSpecifiedField();
        if (bigScreenDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        BigScreenDTO result = bigScreenService.updateBySpecifiedField(bigScreenDTO, 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 BigScreenDTOAndSpecifiedFields {
        private BigScreenDTO bigScreen;
        private Set<String> specifiedFields;
        private String specifiedField;

        private BigScreenDTO getBigScreen() {
            return bigScreen;
        }

        private void setBigScreen(BigScreenDTO bigScreen) {
            this.bigScreen = bigScreen;
        }

        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;
        }
    }
}
