/*
 * Author: wangjian
 * 生成controller
 */
package com.tofly.bigscreen.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.bigscreen.entity.BigScreenData;
import com.tofly.bigscreen.service.BigScreenDataService;
import com.tofly.common.EasyPoiSheetCreaterUtil;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.em.IsNewEnum;
import com.tofly.common.em.SourceEnum;
import com.tofly.common.log.annotation.ToFlyAppLog;
import com.tofly.common.oauth.util.SecurityUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 指标管理
 */
@RestController
@AllArgsConstructor
@RequestMapping("/bigScreenData")
@Api(tags = "指标管理接口")
public class BigScreenDataController {

    @Autowired
    private BigScreenDataService screenDataService;

    /**
     * 分页查询
     *
     * @param page 分页对象
     * @param bigScreenData   指标管理实体
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(value = "分页查询")
    public ResultRespone getBigScreenDataPage(Page page, @ModelAttribute BigScreenData bigScreenData) {
        Page page1 = screenDataService.page(page, Wrappers.<BigScreenData>query().lambda().eq(StringUtils.isNotBlank(bigScreenData.getIsNew()), BigScreenData::getIsNew, bigScreenData.getIsNew())
                .and(StringUtils.isNotBlank(bigScreenData.getIndexName()),wrapper->wrapper.like(StringUtils.isNotBlank(bigScreenData.getIndexName()), BigScreenData::getIndexName,bigScreenData.getIndexName())
                .or().like(StringUtils.isNotBlank(bigScreenData.getIndexName()), BigScreenData::getIndexType,bigScreenData.getIndexName())));
        return ResultRespone.success(page1);
    }

    /**
     * 列表查询
     *
     * @param bigScreenData   指标管理实体
     * @return
     */
    @GetMapping("/list")
    @ApiOperation(value = "列表查询")
    public ResultRespone getBigScreenDataList(@ModelAttribute BigScreenData bigScreenData) {
        if(StringUtils.isBlank(bigScreenData.getIsNew())){
            bigScreenData.setIsNew(IsNewEnum.YES.getCode());
        }
        List<BigScreenData> list = screenDataService.list(Wrappers.<BigScreenData>query().lambda().eq(StringUtils.isNotBlank(bigScreenData.getIsNew()), BigScreenData::getIsNew, bigScreenData.getIsNew())
                .and(StringUtils.isNotBlank(bigScreenData.getIndexName()),wrapper->wrapper.like(StringUtils.isNotBlank(bigScreenData.getIndexName()), BigScreenData::getIndexName,bigScreenData.getIndexName())
                        .or().like(StringUtils.isNotBlank(bigScreenData.getIndexName()), BigScreenData::getIndexType,bigScreenData.getIndexName())));
        return ResultRespone.success(list);
    }


    /**
     * 新增指标管理
     *
     * @param bigScreenData 指标管理实体
     * @return ResultRespone
     */
    @ToFlyAppLog(title = "新增指标管理")
    @ApiOperation(value = "新增指标管理")
    @PostMapping
    public ResultRespone save(@RequestBody BigScreenData bigScreenData) {
        List<BigScreenData> list = screenDataService.list(Wrappers.<BigScreenData>query().lambda().eq(BigScreenData::getIndexCode, bigScreenData.getIndexCode())
        .eq(BigScreenData::getIsNew,IsNewEnum.YES.getCode()));
        if(list!=null && list.size()>0){
            list.stream().forEach(d->{
                d.setIsNew(IsNewEnum.NO.getCode());
                screenDataService.updateById(d);
            });
        }
        bigScreenData.setIsNew(IsNewEnum.YES.getCode());
        bigScreenData.setSource(SourceEnum.XZ.getCode());
        bigScreenData.setCreateUserName(SecurityUtils.getUserName());
        return ResultRespone.success(screenDataService.save(bigScreenData));
    }

    /**
     * 修改指标管理
     *
     * @param bigScreenData 指标管理实体
     * @return ResultRespone
     */
    @ToFlyAppLog(title = "修改指标管理")
    @ApiOperation(value = "修改指标管理")
    @PutMapping
    public ResultRespone updateById(@RequestBody BigScreenData bigScreenData) {
        List<BigScreenData> list = screenDataService.list(Wrappers.<BigScreenData>query().lambda().eq(BigScreenData::getIndexCode, bigScreenData.getIndexCode())
                .eq(BigScreenData::getIsNew,IsNewEnum.YES.getCode())
                .ne(BigScreenData::getId, bigScreenData.getId()));
        if(list!=null && list.size()>0){
            list.stream().forEach(d->{
                d.setIsNew(IsNewEnum.NO.getCode());
                screenDataService.updateById(d);
            });
        }
        bigScreenData.setIsNew(IsNewEnum.YES.getCode());
        bigScreenData.setSource(SourceEnum.XZ.getCode());
        return ResultRespone.success(screenDataService.updateById(bigScreenData));
    }

    /**
     * 通过id删除指标管理
     *
     * @param id id
     * @return ResultRespone
     */
    @ToFlyAppLog(title="通过id删除指标管理" )
    @ApiOperation(value = "通过id删除指标管理")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long")
    })
    @DeleteMapping("/{id}" )
    public ResultRespone removeById(@PathVariable Long id) {
      return ResultRespone.success(screenDataService.removeById(id));
    }


    @ToFlyAppLog(title="通过id批量删除指标管理" )
    @ApiOperation(value = "通过ID批量删除指标管理")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "批量删除，多个id以逗号隔开", required = true, dataType = "String")
    })
    @DeleteMapping("/deleteByIds" )
    public ResultRespone removeById(String ids) {
        ResultRespone<Boolean> success = ResultRespone.success(screenDataService.removeByIds(Arrays.asList(ids.split(","))));
        return success;
    }

    /**
     * 导出指标信息
     * @param bigScreenData 指标实体
     * @return
     */
    @ApiOperation(value = "导出指标信息", httpMethod = "GET")
    @GetMapping("/exportExcel")
    public void export(@ModelAttribute BigScreenData bigScreenData, HttpServletResponse response){
        try{
            Workbook workBook = null;
            if(StringUtils.isBlank(bigScreenData.getIsNew())){
                bigScreenData.setIsNew(IsNewEnum.YES.getCode());
            }
            List<BigScreenData> list = screenDataService.list(Wrappers.<BigScreenData>query().lambda().eq(StringUtils.isNotBlank(bigScreenData.getIsNew()), BigScreenData::getIsNew, bigScreenData.getIsNew())
                    .like(StringUtils.isNotBlank(bigScreenData.getIndexName()), BigScreenData::getIndexName, bigScreenData.getIndexName()));
            List<Map<String, Object>> sheetsList = new ArrayList<>();
            Map<String, Object> trendSheet = EasyPoiSheetCreaterUtil.getSheet(BigScreenData.class,list, "sheet1");
            sheetsList.add(trendSheet);
            // 设置excel的文件名称
            String excelName="指标管理信息表";
            // 重置响应对象
            response.reset();
            // 指定下载的文件名--设置响应头
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((excelName + ".xls").getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            workBook = ExcelExportUtil.exportExcel(sheetsList, ExcelType.HSSF);
            // 写出数据输出流到页面
            OutputStream output = response.getOutputStream();
            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
            workBook.write(bufferedOutPut);
            bufferedOutPut.flush();
            bufferedOutPut.close();
            output.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 导入指标信息
     * @param file 导入文件
     * @return
     */
    @ApiOperation(value = "导入指标信息", httpMethod = "POST")
    @PostMapping("/importExcel")
    public ResultRespone importExcel(@RequestParam("file") MultipartFile file){
        List<BigScreenData> bigScreenDatas=null;
        try {
            ImportParams params = new ImportParams();
            params.setHeadRows(1);
            bigScreenDatas =ExcelImportUtil.importExcel(file.getInputStream(), BigScreenData.class,params);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(bigScreenDatas!=null && bigScreenDatas.size()>0){
            bigScreenDatas.forEach(d->{
                d.setIsNew(IsNewEnum.YES.getCode());
                d.setSource(SourceEnum.DR.getCode());
                d.setCreateUserName(SecurityUtils.getUserName());
                List<BigScreenData> list = screenDataService.list(Wrappers.<BigScreenData>query().lambda().eq(BigScreenData::getIndexCode, d.getIndexCode())
                        .eq(BigScreenData::getIsNew,IsNewEnum.YES.getCode()));
                if(list!=null && list.size()>0){
                    list.stream().forEach(s->{
                        s.setIsNew(IsNewEnum.NO.getCode());
                        screenDataService.updateById(s);
                    });
                }
                screenDataService.save(d);
            });
        }
        return ResultRespone.success();
    }

}
