package com.patzn.lims.env.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.patzn.lims.core.PtConstants;
import com.patzn.lims.core.api.PtResult;
import com.patzn.lims.core.web.LoginHelper;
import com.patzn.lims.core.web.ServiceController;
import com.patzn.lims.env.entity.LmsEnvMonitor;
import com.patzn.lims.env.service.ILmsEnvMonitorService;
import com.patzn.lims.env.vo.LmsEnvMonitorVO;
import com.patzn.lims.excel.eto.EnvMicrobeMonitorETO;
import com.patzn.lims.excel.eto.EnvNormalMonitorETO;
import com.patzn.lims.excel.handler.EnvMicrobeMonitorExportHandler;
import com.patzn.lims.excel.handler.EnvNormalMonitorExportHandler;
import com.patzn.poibox.excel.reader.SheetReader;
import com.patzn.poibox.excel.sheet.XceliteSheetImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 环境监测管理 前端控制器
 * </p>
 *
 * @author patzn
 * @since 2017-11-07
 */
@Api(description = "环境监测管理")
@RestController
@RequestMapping("/v1/env_monitor")
public class LmsEnvMonitorController extends ServiceController<ILmsEnvMonitorService, LmsEnvMonitor> {


    @Autowired
    private ILmsEnvMonitorService lmsEnvMonitorService;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


    @ApiOperation(value = "分页列表", notes = "分页查询数据列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = PtConstants.PAGE_PAGE, value = "请求数据的页码", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = PtConstants.PAGE_ROWS, value = "每页条数", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = PtConstants.PAGE_SIDX, value = "排序字段", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = PtConstants.PAGE_SORD, value = "排序方式", paramType = "query", dataType = "String"),
    })
    @PostMapping("/page")
    public PtResult<IPage<LmsEnvMonitorVO>> getPage(LmsEnvMonitorVO lmsEnvMonitorVO) {
        return success(lmsEnvMonitorService.pageVO(getPage(), lmsEnvMonitorVO));
    }


    @ApiOperation(value = "查询列表", notes = "查询数据列表")
    @PostMapping("/list")
    public PtResult<List<LmsEnvMonitorVO>> getList(LmsEnvMonitorVO lmsEnvMonitorVO) {
        return success(lmsEnvMonitorService.listVO(lmsEnvMonitorVO));
    }


    @ApiOperation(value = "查询 id 信息", notes = "查询指定 id 的数据内容")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", required = true, paramType = "path", dataType = "long"),
    })
    @GetMapping("/vo/{id}")
    public PtResult<LmsEnvMonitorVO> getVO(@PathVariable("id") Long id) {
        return success(lmsEnvMonitorService.getVOById(id));
    }


    @ApiOperation(value = "根据 id 修改信息", notes = "根据指定 id 修改该条数据内容")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", required = true, paramType = "path", dataType = "long"),
    })
    @PutMapping("/edit/{id}")
    public PtResult<Boolean> edit(@PathVariable("id") Long id, LmsEnvMonitor lmsEnvMonitor) {
        return success(lmsEnvMonitorService.updateMonitorById(lmsEnvMonitor));
    }


    @ApiOperation(value = "添加", notes = "添加一条数据")
    @PostMapping("/")
    @Override
    public PtResult<Boolean> add(LmsEnvMonitor lmsEnvMonitor) {
        lmsEnvMonitor.setRecorder(LoginHelper.getAccount().getUserId());
        lmsEnvMonitor.setRecorderName(LoginHelper.getAccount().getUserName());
        return success(lmsEnvMonitorService.save(lmsEnvMonitor));
    }


    @ApiOperation(value = "根据 ids 删除", notes = "根据 id 数组删除指定的数据内容")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "主键数组", required = true, paramType = "query", dataType = "array"),
    })
    @DeleteMapping("/")
    public PtResult<Boolean> delete(@RequestParam("ids") Long[] ids) {
        return success(lmsEnvMonitorService.remove(Wrappers.<LmsEnvMonitor>query().in("id", ids)));
    }

    @GetMapping("/exportNormal")
    public void exportNormalExcel(@RequestParam("ids") List<Long> ids) {
        List<EnvNormalMonitorETO> dtoList = Lists.newArrayList();
        List<LmsEnvMonitor> list = lmsEnvMonitorService.selectNormalByIds(ids);
        for (LmsEnvMonitor monitor : list) {
            EnvNormalMonitorETO dto = getNormalDto(monitor);

            dtoList.add(dto);
        }
        new EnvNormalMonitorExportHandler(dtoList).generater(response);
    }

    @GetMapping("/exportNormalAll")
    public void exportNormalExcelAll() {
        List<EnvNormalMonitorETO> dtoList = Lists.newArrayList();
//        List<LmsEnvMonitor> list = lmsEnvMonitorService.selectNormalByIds(null);
//        for (LmsEnvMonitor monitor: list) {
//            EnvNormalMonitorETO dto = getNormalDto(monitor);
//
//            dtoList.add(dto);
//        }
        new EnvNormalMonitorExportHandler(dtoList).generater(response);
    }

    @PostMapping("/importNormal")
    public PtResult<Boolean> importNormalExcel(MultipartFile file) {
        List<LmsEnvMonitor> monitorList = Lists.newArrayList();
        try {
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            if (".xlsx".equals(suffix)) {
                Workbook workbook = new XSSFWorkbook(file.getInputStream());
                Sheet sheet = workbook.getSheetAt(0);
                SheetReader<EnvNormalMonitorETO> reader = new XceliteSheetImpl(sheet).getBeanReader(EnvNormalMonitorETO.class);
                Collection<EnvNormalMonitorETO> items = reader.read();
                for (EnvNormalMonitorETO monitorDto : items) {
                    LmsEnvMonitor monitor = getNormalEntity(monitorDto);
                    monitorList.add(monitor);
                }

                lmsEnvMonitorService.saveBatch(monitorList);
            } else {
                return success(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return success(true);
    }

    @GetMapping("/exportMicrobe")
    public void exportMicrobeExcel(@RequestParam("ids") List<Long> ids) {
        List<EnvMicrobeMonitorETO> dtoList = Lists.newArrayList();
        List<LmsEnvMonitor> list = lmsEnvMonitorService.selectMicrobeByIds(ids);
        for (LmsEnvMonitor monitor : list) {
            EnvMicrobeMonitorETO dto = getMicrobeDto(monitor);

            dtoList.add(dto);
        }
        new EnvMicrobeMonitorExportHandler(dtoList).generater(response);
    }

    @GetMapping("/exportMicrobeAll")
    public void exportMicrobeExcelAll() {
        List<EnvMicrobeMonitorETO> dtoList = Lists.newArrayList();
        new EnvMicrobeMonitorExportHandler(dtoList).generater(response);
    }

    @PostMapping("/importMicrobe")
    public PtResult<Boolean> importMicrobeExcel(MultipartFile file) {
        List<LmsEnvMonitor> monitorList = Lists.newArrayList();
        try {
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            if (".xlsx".equals(suffix)) {
                Workbook workbook = new XSSFWorkbook(file.getInputStream());
                Sheet sheet = workbook.getSheetAt(0);
                SheetReader<EnvMicrobeMonitorETO> reader = new XceliteSheetImpl(sheet).getBeanReader(EnvMicrobeMonitorETO.class);
                Collection<EnvMicrobeMonitorETO> items = reader.read();
                for (EnvMicrobeMonitorETO monitorDto : items) {
                    LmsEnvMonitor monitor = getMicrobeEntity(monitorDto);
                    monitorList.add(monitor);
                }

                lmsEnvMonitorService.saveBatch(monitorList);
            } else {
                return success(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return success(true);
    }

    private EnvNormalMonitorETO getNormalDto(LmsEnvMonitor monitor) {
        EnvNormalMonitorETO dto = new EnvNormalMonitorETO();
        dto.setLocation(monitor.getLocation());
        dto.setHumidity(monitor.getHumidity());
        dto.setTemperature(monitor.getTemperature());
        dto.setRecorderName(monitor.getRecorderName());

        if (null != monitor.getMonitorDate()) {
            dto.setMonitorDateStr(sdf.format(monitor.getMonitorDate()));
        }

        return dto;
    }

    private LmsEnvMonitor getNormalEntity(EnvNormalMonitorETO dto) throws ParseException {
        LmsEnvMonitor entity = new LmsEnvMonitor();
        entity.setType(0);
        entity.setLocation(dto.getLocation());
        entity.setHumidity(dto.getHumidity());
        entity.setTemperature(dto.getTemperature());

        if (null != dto.getMonitorDateStr()) {
            entity.setMonitorDate(sdf.parse(dto.getMonitorDateStr()));
        }

        entity.setRecorder(LoginHelper.getAccount().getUserId());
        entity.setRecorderName(LoginHelper.getAccount().getUserName());

        return entity;
    }

    private EnvMicrobeMonitorETO getMicrobeDto(LmsEnvMonitor monitor) {
        EnvMicrobeMonitorETO dto = new EnvMicrobeMonitorETO();
        dto.setLocation(monitor.getLocation());
        dto.setHumidity(monitor.getHumidity());
        dto.setTemperature(monitor.getTemperature());
        dto.setAirborneMicrobe(monitor.getAirborneMicrobe());
        dto.setSettlingMicrobe(monitor.getSettlingMicrobe());
        dto.setRecorderName(monitor.getRecorderName());

        if (null != monitor.getMonitorDate()) {
            dto.setMonitorDateStr(sdf.format(monitor.getMonitorDate()));
        }

        return dto;
    }

    private LmsEnvMonitor getMicrobeEntity(EnvMicrobeMonitorETO dto) throws ParseException {
        LmsEnvMonitor entity = new LmsEnvMonitor();
        entity.setType(1);
        entity.setLocation(dto.getLocation());
        entity.setHumidity(dto.getHumidity());
        entity.setTemperature(dto.getTemperature());
        entity.setAirborneMicrobe(dto.getAirborneMicrobe());
        entity.setSettlingMicrobe(dto.getSettlingMicrobe());

        if (null != dto.getMonitorDateStr()) {
            entity.setMonitorDate(sdf.parse(dto.getMonitorDateStr()));
        }

        entity.setRecorder(LoginHelper.getAccount().getUserId());
        entity.setRecorderName(LoginHelper.getAccount().getUserName());

        return entity;
    }

}
