package com.njcn.advance.controller.govern.voltage;


import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.advance.enums.AdvanceResponseEnum;
import com.njcn.advance.pojo.dto.govern.voltage.SgEventExcel;
import com.njcn.advance.pojo.param.govern.voltage.SgEventParam;
import com.njcn.advance.pojo.vo.govern.voltage.SgEventVO;
import com.njcn.advance.pojo.vo.govern.voltage.TransientEventCountVO;
import com.njcn.advance.service.govern.voltage.ISgEventService;
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.poi.util.PoiUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.njcn.web.controller.BaseController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hongawen
 * @since 2024-02-29
 */
@Slf4j
@Validated
@RestController
@Api(tags = "暂降治理暂降数据控制器")
@RequestMapping("/sgEvent")
@RequiredArgsConstructor
public class SgEventController extends BaseController {

    private final ISgEventService sgEventService;

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @PostMapping("/list")
    @ApiOperation("查询指定生产线的暂降数据")
    @ApiImplicitParam(name = "sgEventParamQueryParam", value = "查询参数", required = true)
    public HttpResult<Page<SgEventVO>> list(@RequestBody SgEventParam.SgEventParamQueryParam sgEventParamQueryParam) {
        String methodDescribe = getMethodDescribe("list");
        LogUtil.njcnDebug(log, "{}，查询数据为：{}", methodDescribe, sgEventParamQueryParam);
        Page<SgEventVO> result = sgEventService.sgEventList(sgEventParamQueryParam);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @PostMapping("/getEventDataByProductLineId")
    @ApiOperation("查询生产线下时间范围内的暂降数据")
    @ApiImplicitParam(name = "sgEventParamQueryParam", value = "查询参数", required = true)
    public HttpResult<List<SgEventVO>> getEventDataByProductLineId(@RequestBody SgEventParam.SgEventParamQueryParam sgEventParamQueryParam) {
        String methodDescribe = getMethodDescribe("getEventDataByProductLineId");
        LogUtil.njcnDebug(log, "{}，查询数据为：{}", methodDescribe, sgEventParamQueryParam);
        List<SgEventVO> result = sgEventService.getEventDataByProductLineId(sgEventParamQueryParam);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @GetMapping("/downloadTemplate")
    @ApiOperation("下载暂降事件模板")
    public void downloadTemplate() {
        sgEventService.downloadTemplate();
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @PostMapping("/exportEventData")
    @ApiOperation("导出暂降数据")
    @ApiImplicitParam(name = "sgEventParamQueryParam", value = "查询参数", required = true)
    public void exportEventData(@RequestBody SgEventParam.SgEventParamQueryParam sgEventParamQueryParam) {
        sgEventService.exportEventData(sgEventParamQueryParam);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @PostMapping("/3DList")
    @ApiOperation("获取3d数据")
    @ApiImplicitParam(name = "sgEventParamQueryParam", value = "查询参数", required = true)
    public HttpResult<TransientEventCountVO> threeDList(@RequestBody SgEventParam.SgEventParamQueryParam sgEventParamQueryParam) {
        String methodDescribe = getMethodDescribe("threeDList");
        TransientEventCountVO result = sgEventService.threeDList(sgEventParamQueryParam);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }


    @PostMapping(value = "/importEventData")
    @ApiOperation("批量导入暂降数据")
    @OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.ADD)
    public HttpResult<String> importEventData(@RequestParam("file") MultipartFile file, @RequestParam("incomingLineId") String incomingLineId, @RequestParam("productLineId") String productLineId, HttpServletResponse response) {
        String methodDescribe = getMethodDescribe("importEventData");

        // 检查文件MIME类型是否为csv
        String contentType = file.getContentType();
        if (!"text/csv".equals(contentType)) {
            throw new BusinessException(AdvanceResponseEnum.INVALID_FILE_TYPE);
        }

        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        params.setNeedVerify(true);
        params.setStartSheetIndex(0);
        params.setSheetNum(1);
        try {
            ExcelImportResult<SgEventExcel> sgEventExcelExcelImportResult = ExcelImportUtil.importExcelMore(file.getInputStream(), SgEventExcel.class, params);
            //如果存在非法数据，将不合格的数据导出
            if (sgEventExcelExcelImportResult.isVerifyFail()) {
                // 此处到处前端要做特殊处理，具体可以参考技术监督的数据导入，todo...
                PoiUtil.exportFileByWorkbook(sgEventExcelExcelImportResult.getFailWorkbook(), "非法暂降数据.xlsx", response);
                throw new BusinessException(AdvanceResponseEnum.IMPORT_EVENT_DATA_FAIL);
            } else {
                //批量录入暂降数据
                List<SgEventExcel> sgEventExcels = sgEventExcelExcelImportResult.getList();
                sgEventService.importEventData(sgEventExcels, incomingLineId, productLineId);
            }
        } catch (Exception e) {
            throw new BusinessException(AdvanceResponseEnum.IMPORT_EVENT_DATA_FAIL);
        }
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
    }


    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @GetMapping("/calcLoss")
    @ApiOperation("计算暂降损失")
    public HttpResult<String> calcLoss(String id) {
        String methodDescribe = getMethodDescribe("calcLoss");
        LogUtil.njcnDebug(log, "{}，暂降事件ID数据为：{}", methodDescribe, id);
        sgEventService.calcLoss(id);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
    }


    @OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.UPDATE)
    @PostMapping("/delete")
    @ApiOperation("删除暂降事件")
    @ApiImplicitParam(name = "ids", value = "暂降事件索引", required = true, dataTypeClass = List.class)
    public HttpResult<Object> delete(@RequestBody List<String> ids) {
        String methodDescribe = getMethodDescribe("delete");
        LogUtil.njcnDebug(log, "{}，暂降事件ID数据为：{}", methodDescribe, String.join(StrUtil.COMMA, ids));
        boolean result = sgEventService.deleteEventData(ids);
        if (result) {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
        } else {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe);
        }
    }

}

