package com.ho.flow.controller;

import com.alibaba.excel.EasyExcel;
import com.ho.business.vo.req.deviceModel.SynchronousReqVo;
import com.ho.common.tools.annotation.LogAnnotation;
import com.ho.common.tools.constant.ContextConstant;
import com.ho.common.tools.exception.BaseResponseCode;
import com.ho.common.tools.exception.BusinessException;
import com.ho.common.tools.exception.DataResult;
import com.ho.common.tools.util.PageResult;
import com.ho.flow.service.DeviceColDefineService;
import com.ho.flow.vo.DeviceColDefine;
import com.ho.flow.vo.req.AlarmConfig.DeviceColDefineReqVo;
import com.ho.flow.vo.req.devicecoldefine.DeviceColDefineDeleteVO;
import com.ho.flow.vo.req.devicecoldefine.DeviceColDefineModifyVO;
import com.ho.flow.vo.req.devicecoldefine.DeviceColDefineReqVO;
import com.ho.flow.vo.req.devicecoldefine.DeviceColDefineSyncVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;


/**
 * @author gyan
 * @desc: 告警配置功能
 * @DateTime: 2023/2/1 16:05
 */
@RestController
@RequestMapping(ContextConstant.FLOW_CONTEXT +"deviceColDefine")
@Api(tags = "告警字段定义")
@Slf4j
public class DeviceColDefineController {
    @Autowired
    DeviceColDefineService deviceColDefineService;

    @PostMapping("/page")
    @ApiOperation(value = "分页查询告警配置接口")
    public DataResult<PageResult<DeviceColDefine>> page(@RequestBody @Valid DeviceColDefineReqVo definePageReq) {
        DataResult<PageResult<DeviceColDefine>> result = DataResult.success();
        String deviceType = definePageReq.getDeviceType();
        if(null!=deviceType && !deviceType.isEmpty()){
            PageResult<DeviceColDefine> deviceColDefine = deviceColDefineService.selectPage(definePageReq);
            result.setData(deviceColDefine);
        }
        return result;
    }

    @PostMapping("/colDefineList")
    @ApiOperation(value = "查询告警配置接口,不分页")
    public DataResult<DeviceColDefine> colDefineList(@RequestBody @Valid DeviceColDefineReqVo vo) {
        List<DeviceColDefine> deviceColDefine = deviceColDefineService.selectList(vo);
        return DataResult.success(deviceColDefine);
    }


    @GetMapping("/{id}")
    @ApiOperation(value = "根据设备告警字段id查询告警配置接口")
    public DataResult<DeviceColDefine> selectById(@PathVariable @Valid Integer id) {
        DataResult<DeviceColDefine> result = DataResult.success();
        DeviceColDefine deviceColDefine= deviceColDefineService.selectById(id);
        result.setData(deviceColDefine);
        return result;
    }

    /**
     * 读取excel文件
     * @param file
     */
    @PostMapping("/importExcel")
    @ApiOperation(value = "导入模板数据")
    public DataResult<String> importExcel(@RequestBody MultipartFile file){
        try {
            List<DeviceColDefineReqVO> list = EasyExcel.read(file.getInputStream()).head(DeviceColDefineReqVO.class).sheet().doReadSync();
            int count = deviceColDefineService.insertList(list);
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new BusinessException(BaseResponseCode.SJEKK_EXCEL_DATA);
        }
        return DataResult.success();
    }

    @PostMapping("exportTemplate")
    @ApiOperation(value = "导出模板")
    public void exportTemplate(HttpServletResponse response) {
        ServletOutputStream out = null;
        try {
            String fileName = URLEncoder.encode("deviceColDefineTemplate.xls", "utf-8");
            InputStream fis = getResourcesFileInputStream("template/deviceColDefineTemplate.xls");
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.setHeader("Content-disposition", "attachment;fileName=" + fileName);
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            out = response.getOutputStream();
            out.write(buffer);
        } catch (Exception ex) {
            log.error("下载失败,{}", ex.getMessage());
        } finally {
            try {
                assert out != null;
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 导出模板
    private static InputStream getResourcesFileInputStream(String fileName) {
        return Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
    }

    @PostMapping("/addDeviceColDefine")
    @ApiOperation(value = "新增告警字段定义")
    @LogAnnotation(title = "告警字段定义", action = "新增告警字段定义")
    public DataResult addDeviceColDefine(@RequestBody DeviceColDefineReqVO vo) {
        deviceColDefineService.addDeviceColDefine(vo);
        return DataResult.success();
    }

    @PostMapping("/modifyDeviceColDefine")
    @ApiOperation(value = "修改告警字段定义")
    @LogAnnotation(title = "告警字段定义", action = "修改告警字段定义")
    public DataResult modifyDeviceColDefine(@RequestBody DeviceColDefineModifyVO vo) {
        if(vo.getInfo0().length()>200||vo.getInfo1().length()>200){
            throw new BusinessException(BaseResponseCode.PARAM_EXCEED_LENGTH);
        }
        deviceColDefineService.modifyDeviceColDefine(vo);
        return DataResult.success();
    }

    @PostMapping("/deleteDeviceColDefine")
    @ApiOperation(value = "删除告警字段定义")
    @LogAnnotation(title = "告警字段定义", action = "删除告警字段定义")
    public DataResult deleteDeviceColDefine(@RequestBody DeviceColDefineDeleteVO vo) {
        if(vo.getIdList().size()==0){
            throw new BusinessException(BaseResponseCode.DELETE_ERROR_NO_DATA);
        }
        deviceColDefineService.deleteDeviceColDefine(vo);
        return DataResult.success();
    }

    @PostMapping("/syncDeviceColDefine")
    @ApiOperation(value = "同步数据")
    @LogAnnotation(title = "告警字段定义", action = "同步告警字段定义")
    public DataResult syncDeviceColDefine(@RequestBody SynchronousReqVo vo) {
        deviceColDefineService.syncNewDeviceColDefine(vo);
        return DataResult.success();
    }

    @PostMapping("/syncDeviceColDefines")
    @ApiOperation(value = "新同步数据")
    @LogAnnotation(title = "告警字段定义", action = "同步告警字段定义")
    public DataResult syncDeviceColDefines(@RequestBody DeviceColDefineSyncVO definePageReq) {
        deviceColDefineService.syncDeviceColDefine(definePageReq);
        return DataResult.success();
    }
}
