package cn.cecep.talroad.controller;

import cn.cecep.talroad.common.core.exception.BussinessException;
import cn.cecep.talroad.common.core.utils.StringUtils;
import cn.cecep.talroad.common.core.utils.poi.ExcelUtil;
import cn.cecep.talroad.common.core.web.controller.BasesController;
import cn.cecep.talroad.common.core.web.domain.AjaxResults;
import cn.cecep.talroad.common.log.annotation.Log;
import cn.cecep.talroad.common.log.enums.BusinessType;
import cn.cecep.talroad.common.security.utils.SecurityUtils;
import cn.cecep.talroad.domain.AmProblemFi;
import cn.cecep.talroad.domain.AmProblemFiProcess;
import cn.cecep.talroad.enums.AmProblemAuditTypeEnum;
import cn.cecep.talroad.enums.AmProblemStatusEnum;
import cn.cecep.talroad.service.*;
import cn.cecep.talroad.vo.AmProblemFiVo;
import cn.cecep.talroad.vo.EChartsVO;
import cn.cecep.talroad.vo.query.AmProblemFiQuery;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Api(tags = "预警报警信息")
@RestController
@RequestMapping("/amProblemFi")
public class AmProblemFiController extends BasesController {
    @Autowired
    private IAmProblemFiService amProblemFiService;
    @Autowired
    private IAmProblemFiProcessService amProblemFiProcessService;
    @Autowired
    private IBEnterpriseIrBusinessAlertsService bEnterpriseIrBusinessAlertsService;
    @Autowired
    private IBEnterpriseIrNotifierproNoticeService bEnterpriseIrNotifierproNoticeService;

    @ApiOperation(value = "查询预警报警信息")
    @GetMapping("/list")
    public AjaxResults<IPage<AmProblemFiVo>> list(AmProblemFiQuery query) {
        Page<AmProblemFiVo> page = new Page<>(query.getPageNum(), query.getPageSize());
        amProblemFiService.selectList(page, query);
        return AjaxResults.success(page);
    }

    @ApiOperation(value = "查询图表数据")
    @GetMapping("/chartData")
    public AjaxResults<List<EChartsVO.Sunburst>> chartData(AmProblemFiQuery.ChartDataParam param) {
        String regionCode = SecurityUtils.getLoginUser().getSysUser().getRegionCode();
        List<EChartsVO.Sunburst> data = amProblemFiService.getChartData(param, regionCode);
        return AjaxResults.success(data);
    }

    @ApiOperation(value = "查询趋势图数据")
    @GetMapping("/trendData")
    public AjaxResults<EChartsVO> trendData(AmProblemFiQuery.ChartDataParam param) {
        EChartsVO data = amProblemFiService.getTrendData(param);
        return AjaxResults.success(data);
    }

    @ApiOperation(value = "导出预警报警信息")
    @Log(title = "预警报警信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody AmProblemFiQuery query) {
        Page<AmProblemFiVo> page = new Page<>(query.getPageNum(), query.getPageSize());
        List<AmProblemFiVo> list = amProblemFiService.selectList(page, query);
        ExcelUtil<AmProblemFiVo> util = new ExcelUtil<>(AmProblemFiVo.class);
        util.exportExcel(response, list, "预警报警信息数据");
    }

    /**
     * 获取预警报警信息详细信息
     */
    @ApiOperation(value = "获取预警报警信息详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResults<AmProblemFiVo.Detail> getInfo(@PathVariable("id") String id) {
        return AjaxResults.success(amProblemFiService.getInfo(id));
    }

    @ApiOperation(value = "模型分析结果验证保存")
    @PostMapping(value = "/modelValid/update")
    public AjaxResults updateModelValid(@RequestBody @Validated AmProblemFiVo.ModelValidForm form) {
        amProblemFiService.updateModelValid(form);
        return AjaxResults.success();
    }

    @ApiOperation(value = "数据逻辑异常问题类型详情数据")
    @GetMapping("/logicExceptionData")
    public AjaxResults<IProductionManageService.FrameDataVo> logicExceptionData(
            @RequestParam("id") String id,
            @RequestParam("startTime") String startTime,
            @RequestParam("endTime") String endTime,
            @RequestParam("pageNum") Long pageNum,
            @RequestParam("pageSize") Long pageSize
    ) {
        IProductionManageService.FrameDataVo data = amProblemFiService.logicExceptionData(id, startTime, endTime, pageNum, pageSize);
        return AjaxResults.success(data);
    }

    @ApiOperation(value = "生产问题详情数据")
    @GetMapping("/detail/002")
    public AjaxResults<IProductionManageService.FrameDataVo> detail002(
            @RequestParam("id") String id,
            @RequestParam("startTime") String startTime,
            @RequestParam("endTime") String endTime,
            @RequestParam("pageNum") Long pageNum,
            @RequestParam("pageSize") Long pageSize
    ) {
        IProductionManageService.FrameDataVo data = amProblemFiService.detail002(id, startTime, endTime, pageNum, pageSize);
        return AjaxResults.success(data);
    }

    @ApiOperation(value = "排放量超标（003004）、预警（003005）详情接口")
    @GetMapping(value = {"/detail/003004", "/detail/003005"})
    public AjaxResults<EChartsVO> detail003004(
            @RequestParam("id") String id,
            @RequestParam("startTime") String startTime,
            @RequestParam("endTime") String endTime
    ) {
        EChartsVO data = amProblemFiService.detail003004(id, startTime, endTime);
        return AjaxResults.success(data);
    }

    @ApiOperation(value = "浓度超标（003002）、预警（003003）详情接口")
    @GetMapping(value = {"/detail/003002", "/detail/003003"})
    public AjaxResults<EChartsVO> detail003002(
            @RequestParam("id") String id,
            @RequestParam("startTime") String startTime,
            @RequestParam("endTime") String endTime
    ) {
        EChartsVO data = amProblemFiService.detail003002(id, startTime, endTime);
        return AjaxResults.success(data);
    }

    @ApiOperation(value = "获取dcs、分表计电曲线图数据")
    @GetMapping("/detail/dcsElec")
    public AjaxResults<IProductionManageService.FrameDataVo> dcsElec(
            @RequestParam("id") String id,
            @RequestParam("startTime") String startTime,
            @RequestParam("endTime") String endTime,
            @RequestParam("pageNum") Long pageNum,
            @RequestParam("pageSize") Long pageSize
    ) {
        IProductionManageService.FrameDataVo data = amProblemFiService.dcsElec(id, startTime, endTime, pageNum, pageSize);
        return AjaxResults.success(data);
    }

    @ApiOperation(value = "治理设施停运问题详情")
    @GetMapping("/detail/elecMerge")
    public AjaxResults<EChartsVO> elecMerge(
            @RequestParam("id") String id,
            @RequestParam("startTime") String startTime,
            @RequestParam("endTime") String endTime
    ) {
        EChartsVO chartsVO = amProblemFiService.elecMerge(id, startTime, endTime);
        return AjaxResults.success(chartsVO);
    }

    @ApiOperation(value = "生产工况监测大屏-治理设施异常问题统计")
    @GetMapping("/problemType/count")
    public AjaxResults<List<AmProblemFiVo.CountVo>> problemTypeCount(@RequestParam(value = "problemType", defaultValue = "004") String problemType) {
        List<AmProblemFiVo.CountVo> data = amProblemFiService.getProblemTypeCount(problemType);
        return AjaxResults.success(data);
    }

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "企业端分页查询预警信息")
    @GetMapping("/pageYjProblem")
    public AjaxResults<IPage<AmProblemFiVo>> pageYjProblem(AmProblemFiQuery query) {
        query.setType(0);
        query.setFactoryId(SecurityUtils.getLoginUser().getSysUser().getFactoryId());
        if (StringUtils.isEmpty(query.getFactoryId())) {
            throw new BussinessException("未找到用户关联企业");
        }
        query.setNoRegion(true);
        Page<AmProblemFiVo> page = new Page<>(query.getPageNum(), query.getPageSize());
        amProblemFiService.selectList(page, query);
        return AjaxResults.success(page);
    }

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "企业端分页查询报警信息")
    @GetMapping("/pageBjProblem")
    public AjaxResults<IPage<AmProblemFiVo>> pageBjProblem(AmProblemFiQuery query) {
        query.setType(1);
        query.setNoRegion(true);
        final String factoryId = SecurityUtils.getLoginUser().getSysUser().getFactoryId();
        if (StringUtils.isEmpty(factoryId)) {
            throw new BussinessException("未找到用户关联企业");
        }
        query.setFactoryId(factoryId);
        Page<AmProblemFiVo> page = new Page<>(query.getPageNum(), query.getPageSize());
        amProblemFiService.selectList(page, query);
        return AjaxResults.success(page);
    }

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "分页查询报警审核信息")
    @GetMapping("/pageBjShProblem")
    public AjaxResults<IPage<AmProblemFiVo>> pageBjShProblem(AmProblemFiQuery query) {
        query.setNoRegion(true);
        query.setType(1);
        query.setProblemStatusList(Lists.newArrayList(
                AmProblemStatusEnum.WAIT_AUDIT.getValue(),
                AmProblemStatusEnum.PASS.getValue(),
                AmProblemStatusEnum.UN_PASS.getValue()
        ));
        query.setProblemAuditType(AmProblemAuditTypeEnum.ZS.getValue());
        Page<AmProblemFiVo> page = new Page<>(query.getPageNum(), query.getPageSize());
        amProblemFiService.selectList(page, query);
        return AjaxResults.success(page);
    }

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "查询报警处理详情信息")
    @GetMapping("/getProblemProcess")
    public AjaxResults<List<AmProblemFiProcess>> getProblemProcess(@RequestParam String problemId) {
        return AjaxResults.success(amProblemFiProcessService.list(Wrappers.<AmProblemFiProcess>lambdaQuery().eq(AmProblemFiProcess::getProblemId, problemId)));
    }

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "整改信息填写")
    @PostMapping(value = "/rectify/save")
    public AjaxResults rectifySave(@RequestBody @Validated AmProblemFiProcess param) {
        param.setProcessUserId(SecurityUtils.getLoginUser().getSysUser().getUserId().toString());
        param.setProcessUserName(SecurityUtils.getLoginUser().getSysUser().getNickName());
        amProblemFiService.rectifySave(param);
        return AjaxResults.success();
    }

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "审核结果")
    @PostMapping(value = "/audit/result")
    public AjaxResults auditResult(@RequestBody @Validated AmProblemFiProcess param) {
        param.setProcessUserId(SecurityUtils.getUserKey());
        param.setProcessUserName(SecurityUtils.getUsername());
        amProblemFiService.auditResult(param);
        return AjaxResults.success();
    }

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "预警签收")
    @PostMapping(value = "/yj/sign")
    public AjaxResults yjSign(@RequestBody @Validated AmProblemFiProcess param) {
        param.setProcessUserId(SecurityUtils.getUserKey());
        param.setProcessUserName(SecurityUtils.getUsername());
        amProblemFiService.yjSign(param);
        return AjaxResults.success();
    }


    @ApiOperation(value = "聚合接口查各类告警总数")
    @GetMapping(value = "/countList")
    public AjaxResults countList(@RequestParam String factoryId) {
        List<Map<String, String>> res = new ArrayList<>();
        if (factoryId.isEmpty()) {
            return AjaxResults.success(res);
        }
        //type: 0-预警;1-报警
        Integer warnCount = amProblemFiService.countByFactoryId(factoryId, 0);

        Map<String, String> warnMap = new HashMap<>();
        warnMap.put("typeDesc", "预警");
        warnMap.put("id", "warn");
        warnMap.put("count", warnCount.toString());
        res.add(warnMap);

        Integer baojinWarnCount = amProblemFiService.countByFactoryId(factoryId, 1);
        Map<String, String> baojinWarnMap = new HashMap<>();
        baojinWarnMap.put("typeDesc", "报警");
        baojinWarnMap.put("id", "baojinWarn");
        baojinWarnMap.put("count", baojinWarnCount.toString());
        res.add(baojinWarnMap);
        //通知

        Integer noticeCount = bEnterpriseIrNotifierproNoticeService.countByFactoryId(factoryId);
        Map<String, String> noticeCountMap = new HashMap<>();
        noticeCountMap.put("typeDesc", "通知");
        noticeCountMap.put("id", "notice");
        noticeCountMap.put("count", noticeCount.toString());
        res.add(noticeCountMap);

        //提醒

        Integer alertCount = bEnterpriseIrBusinessAlertsService.countByFactoryId(factoryId);
        Map<String, String> alertCountMap = new HashMap<>();
        alertCountMap.put("typeDesc", "业务提醒");
        alertCountMap.put("id", "tixing");
        alertCountMap.put("count", alertCount.toString());
        res.add(alertCountMap);

        return AjaxResults.success(res);
    }
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "预警添加反馈")
    @PostMapping(value = "/yj/addCause")
    public AjaxResults addCause(@RequestBody @Validated AmProblemFi param) {
        return AjaxResults.success(amProblemFiService.addCause(param));
    }
    @ApiOperation(value = "预警、报警 问题分类级联数据")
    @GetMapping("/getAListOfAlerts")
    @ApiImplicitParams({@ApiImplicitParam(name = "type",value = "0为预警，1为报警，不能查询全部,不传递默认为0"),
    @ApiImplicitParam(name = "topType",value = "0：预警，1：不涉及违法问题，2涉及违法问题，不传递默认按照type处理")})
    public AjaxResults<List<Map<String, Object>>> getAListOfAlerts(
                                @RequestParam(required = false,defaultValue = "0") String type,
                                @RequestParam(required = false) String topType) {
        List<Map<String, Object>> list = amProblemFiService.getAListOfAlerts( type,topType);
        return AjaxResults.success(list);
    }

    @ApiOperation(value = "整改时间填写")
    @PostMapping(value = "/rectify/update")
    public AjaxResults rectifyUpdate(@RequestBody @Validated AmProblemFiVo param) {
        return AjaxResults.success(amProblemFiService.rectifyUpdate(param));
    }
}
