package com.njcn.device.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.collection.CollectionUtil;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.constant.OperateType;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.HttpResultUtil;
import com.njcn.common.utils.LogUtil;
import com.njcn.device.enums.DeviceResponseEnum;
import com.njcn.device.pojo.bo.excel.TerminalBaseExcel;
import com.njcn.device.pojo.param.*;
import com.njcn.device.pojo.po.Line;
import com.njcn.device.pojo.vo.TerminalVO;
import com.njcn.device.service.TerminalBaseService;
import com.njcn.poi.excel.ExcelUtil;
import com.njcn.poi.util.PoiUtil;
import com.njcn.web.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * pqs
 *
 * @author cdf
 * @date 2022/1/4
 */
@Slf4j
@Api(tags = "装置管理")
@RestController
@RequestMapping("/device")
@RequiredArgsConstructor
public class TerminalBaseController extends BaseController {

    private final TerminalBaseService terminalBaseService;



    /**
     * 终端新增操作
     *
     * @author cdf
     * @date 2021/7/5
     */
    @ApiOperation("终端新增操作")
    @OperateInfo(operateType = OperateType.ADD, info = LogEnum.BUSINESS_MEDIUM)
    @PostMapping("addTerminal")
    public HttpResult addTerminal(@Valid @RequestBody AddTerminalParam addTerminalParam) {
        String methodDescribe = getMethodDescribe("addTerminal");
        //装置母线监测点相关检验
        if (CollectionUtil.isNotEmpty(addTerminalParam.getDeviceParam())) {
            //校验装置是否存在重名
            List<DeviceParam> listDev = addTerminalParam.getDeviceParam();
            List<String> devName = listDev.stream().map(DeviceParam::getName).collect(Collectors.toList());
            long count = devName.stream().distinct().count();
            if (count != devName.size()) {
                throw new BusinessException(DeviceResponseEnum.DEVICE_REPETITION);
            }
            //校验装置是否存在重复ip
            List<String> devIp = listDev.stream().map(DeviceParam::getIp).collect(Collectors.toList());
            long countIp = devIp.stream().distinct().count();
            if (countIp != devIp.size()) {
                throw new BusinessException(DeviceResponseEnum.DEVICE_IP_REPETITION);
            }

            //校验母线名称
            for (DeviceParam deviceParam : listDev) {
                if (CollectionUtil.isNotEmpty(deviceParam.getSubVoltageParam())) {
                    List<SubVoltageParam> subvList = deviceParam.getSubVoltageParam();
                    List<String> subVName = subvList.stream().map(SubVoltageParam::getName).collect(Collectors.toList());
                    long countSubV = subVName.stream().distinct().count();
                    if (countSubV != subVName.size()) {
                        throw new BusinessException(DeviceResponseEnum.SUBV_NAME_REPETITION);
                    }
                    //校验监测点名称
                    for (SubVoltageParam subVoltageParam : subvList) {
                        if (CollectionUtil.isNotEmpty(subVoltageParam.getLineParam())) {
                            List<LineParam> listLine = subVoltageParam.getLineParam();
                            List<String> lineName = listLine.stream().map(LineParam::getName).collect(Collectors.toList());
                            long countLine = lineName.stream().distinct().count();
                            if (countLine != lineName.size()) {
                                throw new BusinessException(DeviceResponseEnum.LINE_NAME_REPETITION);
                            }
                            List<Integer> lineNum = listLine.stream().map(LineParam::getNum).collect(Collectors.toList());
                            long countNum = lineNum.stream().distinct().count();
                            if (countNum != lineNum.size()) {
                                throw new BusinessException(DeviceResponseEnum.LINE_NUM_REPETITION);
                            }
                        }
                    }
                }
            }
        }
        terminalBaseService.addTerminal(addTerminalParam);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
    }


    /**
     * 终端修改操作
     *
     * @author cdf
     * @date 2021/7/19
     */
    @ApiOperation("终端修改操作")
    @OperateInfo(operateType = OperateType.UPDATE, info = LogEnum.BUSINESS_MEDIUM)
    @PutMapping("updateTerminal")
    public HttpResult updateTerminal(@Valid @RequestBody UpdateTerminalParam updateTerminalParam) {
        String methodDescribe = getMethodDescribe("updateTerminal");
        terminalBaseService.updateTerminal(updateTerminalParam);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
    }

    /**
     * 根据id level获取终端相关信息
     *
     * @author cdf
     * @date 2021/7/19
     */
    @ApiOperation("查询终端详情")
    @OperateInfo(info = LogEnum.BUSINESS_MEDIUM)
    @GetMapping("queryTerminal")
    public HttpResult<TerminalVO> queryTerminal(@RequestParam("id") String id) {
        String methodDescribe = getMethodDescribe("queryTerminal");
        TerminalVO t = terminalBaseService.queryTerminal(id);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, t, methodDescribe);
    }


    /**
     * 根据id和节点level删除当前节点以及下级节点
     *
     * @author cdf
     * @date 2021/7/21
     */
    @ApiOperation("终端删除操作")
    @OperateInfo(operateType = OperateType.DELETE, info = LogEnum.BUSINESS_SERIOUS)
    @DeleteMapping("delTerminal")
    public HttpResult delTerminal(@RequestParam("id") String id) {
        String methodDescribe = getMethodDescribe("delTerminal");
        terminalBaseService.delTerminal(id);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
    }


    /**
     * 功能描述:根据变电站id获取变电站详情
     *
     * @param list
     * @return
     * @author xy
     * @date 2022/2/21 18:53
     */
    @ApiOperation("获取变电站信息")
    @OperateInfo
    @GetMapping("/getSubstationById")
    @ApiIgnore
    public HttpResult<List<Line>> getSubstationById(@RequestParam("list") List<String> list) {
        String methodDescribe = getMethodDescribe("getSubstationById");
        LogUtil.njcnDebug(log, "{}，变电站集合为：{}", methodDescribe, list);
        List<Line> subList = terminalBaseService.getSubstationById(list);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, subList, methodDescribe);
    }

    /**
     * 批量导入oracle中的原始数据
     *
     * @param file 上传的数据文件
     * @return 返回导入结果
     */
    @ResponseBody
    @ApiOperation("批量导入oracle中的原始数据")
    @PostMapping(value = "importOracleTerminalData")
    public HttpResult<String> importOracleTerminalData(@ApiParam(value = "文件", required = true) @RequestPart("file") MultipartFile file, HttpServletResponse response) {
        String methodDescribe = getMethodDescribe("importOracleTerminalData");
        terminalBaseService.importOracleTerminalData(file,response);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
    }


    /**
     * 导出台账
     * @author cdf
     * @date 2022/5/17
     */
    @ResponseBody
    @ApiOperation("导出台账信息")
    @GetMapping(value = "exportTerminalBase")
    public HttpResult<String> exportTerminalBase(HttpServletResponse response){
        String methodDescribe = getMethodDescribe("exportTerminalBase");
        String fileName = "台账信息.xls";
        List<TerminalBaseExcel> baseExcelList = null;
        try {
            baseExcelList = terminalBaseService.exportTerminalBase();
        }catch (Exception e) {
            e.printStackTrace();
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe);
        }
        ExportParams exportExcel = new ExportParams("批量导入模板（请严格按照模板标准填入数据）","台账信息");
        Workbook workbook = ExcelExportUtil.exportExcel(exportExcel,TerminalBaseExcel.class, baseExcelList);
        PoiUtil.exportFileByWorkbook(workbook,fileName,response);
        return null;
    }

    /**
     * 导出台账生成的excel
     * @author cdf
     * @date 2022/5/17
     */
    @ApiOperation("下载台账信息")
    @GetMapping(value = "downTerminalBase")
    public void downTerminalBase(HttpServletResponse response) {
        String fileName = "台账信息.xls";
/*
            ExportParams exportExcel = new ExportParams("批量导入模板（请严格按照模板标准填入数据）","台账信息");
            Workbook workbook = ExcelExportUtil.exportExcel(exportExcel,TerminalBaseExcel.class, baseExcelList);
            PoiUtil.exportFileByWorkbook(workbook,fileName,response);*/


    }

    /**
     * 导入excel台账模板
     * @author cdf
     * @date 2022/5/18
     */
    @ResponseBody
    @ApiOperation("excel批量导入台账信息")
    @PostMapping(value = "importTerminalBase")
    public HttpResult<String> importTerminalBase(@ApiParam(value = "文件", required = true) @RequestPart("file") MultipartFile file, HttpServletResponse response) {
        String methodDescribe = getMethodDescribe("importTerminalBase");
        terminalBaseService.importTerminalBase(file,response);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
    }
}
