package com.xydl.cac.controller;

import com.xydl.cac.entity.Bdz;
import com.xydl.cac.entity.NSensor;
import com.xydl.cac.exception.BusinessException;
import com.xydl.cac.model.ConditionModel;
import com.xydl.cac.model.Response;
import com.xydl.cac.model.SensorDetail;
import com.xydl.cac.model.SensorUpdateModel;
import com.xydl.cac.repository.NSensorRepository;
import com.xydl.cac.service.NSensorService;
import com.xydl.cac.service.ParamBindService;
import com.xydl.cac.service.ReportService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.repository.query.Param;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = {"监测设备相关接口"})
@RequestMapping("nsensor")
@Slf4j
public class NSensorController extends BasicController {

    @Resource
    NSensorService service;
    @Resource
    ReportService reportService;
    @Resource
    ParamBindService bindService;
    @Resource
    NSensorRepository sensorRepository;

    @GetMapping("getTrunk")
    @ApiOperation("查询树干")
    public Response<List<Bdz>> getTrunk() throws Exception {
        List<Bdz> result = bindService.getTrunk();
        return Response.success(result);
    }

    @GetMapping("getTree")
    @ApiOperation("查询树")
    public Response<List<Bdz>> getTree() throws Exception {
        List<Bdz> result = bindService.getTree(true);
        return Response.success(result);
    }

    @GetMapping("listAll")
    @ApiOperation("查询全部")
    public Response<List<NSensor>> listAll(@ApiParam("主设备id") @RequestParam(value = "zsbid", required = false) Integer zsbid,
                                           @ApiParam("类型") @RequestParam(value = "typeId", required = false) Integer typeId) throws Exception {
        List<NSensor> result = service.listAll(zsbid, typeId);
        return Response.success(result);
    }

    @GetMapping("list")
    @ApiOperation("查询列表")
    public Response<Page<NSensor>> list(@ApiParam("类型") @RequestParam(value = "typeId", required = false) Integer typeId,
                                        @ApiParam("页码") @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                        @ApiParam("每页数量") @RequestParam(value = "pageSize", required = false) Integer pageSize) throws Exception {
        pageNum = this.initPageNum(pageNum);
        pageSize = this.initPageSize(pageSize);
        Page<NSensor> result = service.list(typeId, pageNum, pageSize);
        return Response.success(result);
    }

    @PostMapping("add")
    @ApiOperation("新增")
    public Response<NSensor> add(@Validated @RequestBody NSensor item) throws Exception {
        NSensor result = service.add(item);
        return Response.success(result);
    }

    @PostMapping("update")
    @ApiOperation("更新")
    public Response<String> update(@Validated @RequestBody NSensor item) throws Exception {
        if (item.getId() == null) {
            throw new BusinessException("ID不能为空!");
        }
        service.update(item);
        return Response.success("OK");
    }

    @PostMapping("batchUpdate")
    @ApiOperation("批量更新")
    public Response<String> batchUpdate(@Validated @RequestBody SensorUpdateModel model) throws Exception {
        service.batchUpdate(model);
        return Response.success("OK");
    }

    @PostMapping("delete")
    @ApiOperation("删除")
    public Response<String> delete(@Validated @NotNull(message = "ID不能为空!") @Param("id") Integer id) throws Exception {
        service.delete(id);
        return Response.success("OK");
    }

    @GetMapping("detail")
    @ApiOperation("查询单个装置采集到的数据")
    public Response<SensorDetail> getDetail(@Validated ConditionModel model) throws Exception {
        if (model.getPageNum() != null || model.getPageSize() != null) {
            model.setPageNum(this.initPageNum(model.getPageNum()));
            model.setPageSize(this.initPageSize(model.getPageSize()));
        }
        SensorDetail result = service.getDetail(model);
        return Response.success(result);
    }

    @PostMapping("bindicd")
    @ApiOperation("详情")
    public Response<String> bindicd(@Validated @NotNull(message = "ID不能为空!") @Param("id") Integer id, @Validated @NotNull(message = "icdid不能为空!") @Param("icdid") Integer icdid) {
        try {
            service.bindicd(id, icdid);
            return Response.success("OK");
        } catch (Exception ex) {
            return Response.fail(ex.getMessage());
        }
    }

    @PostMapping("importCac")
    @ApiOperation("导入CAC")
    public Response<String> importCac(@RequestParam("file") MultipartFile file) throws Exception {
        if (file != null && file.getInputStream() != null) {
            reportService.importCac(file.getInputStream());
            return Response.success("OK");
        } else {
            return Response.fail("缺少上传文件");
        }
    }

    @GetMapping("export")
    @ApiOperation("导出单个或多个装置采集到的数据")
    public void export(@Validated ConditionModel model, HttpServletResponse response) throws Exception {
        if (model.getPageNum() != null || model.getPageSize() != null) {
            model.setPageNum(this.initPageNum(model.getPageNum()));
            model.setPageSize(this.initPageSize(model.getPageSize()));
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        if (model.getTypeId() != null) {
            String typename = "";
            List<NSensor> list = sensorRepository.findByTypeId(model.getTypeId());
            if (CollectionUtils.isEmpty(list)) {
                throw new BusinessException("未找到该类型的装置typeId=" + model.getTypeId());
            }
            List<SensorDetail<Map<String, Object>>> detailList = new ArrayList<>();
            for (NSensor sensor : list) {
                model.setId(sensor.getId());
                SensorDetail<Map<String, Object>> detail = service.getDetail(model);
                typename = detail.getSensor().getTypeName();
                detailList.add(detail);
            }
            response.setHeader("Content-Disposition", "attachment; filename="
                    + URLEncoder.encode(typename + ".xlsx", "UTF-8"));
            reportService.exportSensorList(detailList, response.getOutputStream());

        } else {
            SensorDetail<Map<String, Object>> detail = service.getDetail(model);
            response.setHeader("Content-Disposition", "attachment; filename="
                    + URLEncoder.encode(detail.getSensor().getName() + ".xlsx", "UTF-8"));
            reportService.exportSensor(detail, response.getOutputStream());
        }
    }

    @PostMapping("importFromModev")
    @ApiOperation("从modev表导入")
    public Response<String> importFromModev() throws Exception {
        String str = service.importFromModev();
        return Response.success(str);
    }


    @GetMapping("exportLatest")
    @ApiOperation("导出")
    public void exportLatest(@ApiParam("主设备id") @RequestParam(value = "zsbid", required = false) Integer zsbid,
                             @ApiParam("类型") @RequestParam(value = "typeId", required = false) Integer typeId, HttpServletResponse response) throws Exception {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        List<NSensor> result = service.listAll(zsbid, typeId);

        Map<Integer, List<NSensor>> map = new HashMap<>();
        for (NSensor nSensor : result) {
            if (map.containsKey(nSensor.getTypeId())) {
                map.get(nSensor.getTypeId()).add(nSensor);
            } else {
                List<NSensor> list = new ArrayList<>();
                list.add(nSensor);
                map.put(nSensor.getTypeId(), list);
            }
        }

        String excelName = "传感器的最新数据";

        response.setHeader("Content-Disposition", "attachment; filename="
                + URLEncoder.encode(excelName + ".xlsx", "UTF-8"));

        reportService.exportLatest(map, response.getOutputStream());

    }

}
