package com.yeejoin.amos.boot.module.hygf.biz.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.hygf.api.config.UserLimits;
import com.yeejoin.amos.boot.module.hygf.api.dto.JpStationDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.TdHygfJpInverterWarnDto;
import com.yeejoin.amos.boot.module.hygf.api.entity.HYGFMaintenanceTickets;
import com.yeejoin.amos.boot.module.hygf.api.entity.JpPersonStation;
import com.yeejoin.amos.boot.module.hygf.api.entity.JpStation;
import com.yeejoin.amos.boot.module.hygf.api.mapper.HYGFMaintenanceTicketsMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.JpPersonStationMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.JpStationMapper;
import com.yeejoin.amos.boot.module.hygf.api.tdenginemapper.TdHygfJpInverterWarnMapper;
import com.yeejoin.amos.boot.module.hygf.api.util.TimeUtil;
import com.yeejoin.amos.boot.module.hygf.biz.service.impl.TdHygfJpInverterWarnServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 户用光伏监盘逆变器报警表
 *
 * @author system_generator
 * @date 2023-09-19
 */
@RestController
@Api(tags = "户用光伏监盘逆变器报警表Api")
@RequestMapping(value = "/td-hygf-jp-inverter-warn")
public class TdHygfJpInverterWarnController extends BaseController {

    @Autowired
    TdHygfJpInverterWarnServiceImpl tdHygfJpInverterWarnServiceImpl;
    @Autowired
    JpPersonStationMapper pPersonStationMapper;
    @Autowired
    TdHygfJpInverterWarnMapper tdHygfJpInverterWarnMapper;
    @Autowired
    JpStationMapper jpStationMapper;
    @Autowired
    HYGFMaintenanceTicketsMapper hygfMaintenanceTicketsMapper;

    /**
     * 新增户用光伏监盘逆变器报警表
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "新增户用光伏监盘逆变器报警表", notes = "新增户用光伏监盘逆变器报警表")
    public ResponseModel<TdHygfJpInverterWarnDto> save(@RequestBody TdHygfJpInverterWarnDto model) {
        model = tdHygfJpInverterWarnServiceImpl.createWithModel(model);
        return ResponseHelper.buildResponse(model);
    }

    /**
     * 根据sequenceNbr更新
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PutMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新户用光伏监盘逆变器报警表", notes = "根据sequenceNbr更新户用光伏监盘逆变器报警表")

    public ResponseModel<TdHygfJpInverterWarnDto> updateBySequenceNbrTdHygfJpInverterWarn(
            @RequestBody TdHygfJpInverterWarnDto model, @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
        return ResponseHelper.buildResponse(tdHygfJpInverterWarnServiceImpl.updateWithModel(model));

    }

    /**
     * 根据sequenceNbr删除
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除户用光伏监盘逆变器报警表", notes = "根据sequenceNbr删除户用光伏监盘逆变器报警表")
    public ResponseModel<Boolean> deleteBySequenceNbr(HttpServletRequest request,
                                                      @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
        return ResponseHelper.buildResponse(tdHygfJpInverterWarnServiceImpl.removeById(sequenceNbr));
    }

    /**
     * 根据sequenceNbr查询
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个户用光伏监盘逆变器报警表", notes = "根据sequenceNbr查询单个户用光伏监盘逆变器报警表")
    public ResponseModel<TdHygfJpInverterWarnDto> selectOne(@PathVariable Long sequenceNbr) {
        return ResponseHelper.buildResponse(tdHygfJpInverterWarnServiceImpl.queryBySeq(sequenceNbr));
    }

    /**
     * 根据sequenceNbr查询
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @GetMapping(value = "time/{createdTime}")
    @ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个户用光伏监盘逆变器报警表", notes = "根据sequenceNbr查询单个户用光伏监盘逆变器报警表")
    public ResponseModel<TdHygfJpInverterWarnDto> selectCreatedTime(@PathVariable Long createdTime) {
        return ResponseHelper.buildResponse(tdHygfJpInverterWarnServiceImpl.queryByCreatedTime(createdTime));
    }

    /**
     * 列表分页查询
     *
     * @param current 当前页
     * @param current 每页大小
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/page")
    @ApiOperation(httpMethod = "GET", value = "户用光伏监盘逆变器报警表分页查询", notes = "户用光伏监盘逆变器报警表分页查询")
    public ResponseModel<Page<TdHygfJpInverterWarnDto>> queryForPage(@RequestParam(value = "current") int current,
                                                                     @RequestParam(value = "size") int size, TdHygfJpInverterWarnDto tdHygfJpInverterWarnDto) {
        List<JpPersonStation> pPersonStation = null;
        if (tdHygfJpInverterWarnDto.getName() != null && !"".equals(tdHygfJpInverterWarnDto.getName())) {
            LambdaQueryWrapper<JpPersonStation> qug1 = new LambdaQueryWrapper<>();
            qug1.like(JpPersonStation::getStationName, tdHygfJpInverterWarnDto.getName());
            pPersonStation = pPersonStationMapper.selectList(qug1);
        } else {
            LambdaQueryWrapper<JpPersonStation> qug = new LambdaQueryWrapper<>();
            qug.eq(JpPersonStation::getPersonId, getUserInfo().getUserId());
            pPersonStation = pPersonStationMapper.selectList(qug);


        }

        if (!pPersonStation.isEmpty()) {
            Page<TdHygfJpInverterWarnDto> page = new Page<TdHygfJpInverterWarnDto>();
            page.setCurrent(current);
            page.setSize(size);
            List<String> ids = pPersonStation.stream().map(i -> i.getStationId()).collect(Collectors.toList());
            tdHygfJpInverterWarnDto.setStationIds(ids);
            return ResponseHelper.buildResponse(
                    tdHygfJpInverterWarnServiceImpl.queryForTdHygfJpInverterWarnPage(page, tdHygfJpInverterWarnDto));
        } else {
            return ResponseHelper.buildResponse(new Page<TdHygfJpInverterWarnDto>());
        }

    }

    /**
     * 列表全部数据查询
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "户用光伏监盘逆变器报警表列表全部数据查询", notes = "户用光伏监盘逆变器报警表列表全部数据查询")
    @GetMapping(value = "/list")
    public ResponseModel<List<TdHygfJpInverterWarnDto>> selectForList() {
        return ResponseHelper.buildResponse(tdHygfJpInverterWarnServiceImpl.queryForTdHygfJpInverterWarnList());
    }

    /**
     * 获取告警统计
     **/
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "户用光伏监盘逆变器报警表列表全部数据查询", notes = "户用光伏监盘逆变器报警表列表全部数据查询")
    @GetMapping(value = "/selectcount")
    public ResponseModel<Map<String, Object>> selectcount(JpStationDto reviewDto) {
        LambdaQueryWrapper<JpStation> qugda = new LambdaQueryWrapper<>();

        //获取当前人管理场站
        if (reviewDto.getThirdStationId() == null) {
            //获取当前人管理场站
            LambdaQueryWrapper<JpPersonStation> qug = new LambdaQueryWrapper<>();
            qug.eq(JpPersonStation::getPersonId, getUserInfo().getUserId());
            List<JpPersonStation> pPersonStation = pPersonStationMapper.selectList(qug);

            if (pPersonStation == null || pPersonStation.isEmpty()) {
                return ResponseHelper.buildResponse(null);
            }
            List ids = null;
            if (pPersonStation != null && !pPersonStation.isEmpty()) {
                ids = new ArrayList();
                for (JpPersonStation jpPersonStation : pPersonStation) {
                    ids.add(jpPersonStation.getStationId());
                }
                qugda.in(ids != null, JpStation::getThirdStationId, ids);
            }
        } else {
            qugda.eq(JpStation::getThirdStationId, reviewDto.getThirdStationId());
        }
        qugda.like(reviewDto.getName() != null, JpStation::getName, reviewDto.getName());
        qugda.like(reviewDto.getArea() != null, JpStation::getArea, reviewDto.getArea());
        List<JpStation> pPersonStation = jpStationMapper.selectList(qugda);
        List<Map<String, Object>> datalist = tdHygfJpInverterWarnMapper.getCountTdHygfJpInverterWarn(pPersonStation != null && !pPersonStation.isEmpty() ? pPersonStation : null);
        Map<String, Object> collector = new HashMap<>();
        collector.put("wcl", 0);
        collector.put("ycl", 0);

        if (datalist != null && !datalist.isEmpty()) {
            for (Map<String, Object> map : datalist) {
                if ("未处理".equals(map.get("state").toString())) {
                    collector.put("wcl", Integer.valueOf(map.get("num").toString()));
                } else if ("已处理".equals(map.get("state").toString()) || "已恢复".equals(map.get("state").toString())) {
                    collector.put("ycl", Integer.valueOf(map.get("num").toString()));
                }
            }
        }
        return ResponseHelper.buildResponse(collector);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "户用光伏监盘逆变器报警表列表全部数据查询", notes = "户用光伏监盘逆变器报警表列表全部数据查询")
    @GetMapping(value = "/selectWarnList")
    @UserLimits
    public ResponseModel<Page<TdHygfJpInverterWarnDto>> selectWarnList(@RequestParam(required = false) List<String> state,
                                                                       @RequestParam(required = false) String handlerStatus,
                                                                       @RequestParam(required = false) String regionalCompaniesCode,
                                                                       @RequestParam(required = false) String amosCompanyCode,
                                                                       @RequestParam(required = false) String thirdStationId,
                                                                       @RequestParam(required = false) String type,
                                                                       @RequestParam(required = false) String level,
                                                                       @RequestParam(required = false) String stationName,
                                                                       @RequestParam(required = false) String minvalue,
                                                                       @RequestParam(required = false) String maxValue,
                                                                       @RequestParam(required = false) String snCode,
                                                                       @RequestParam(required = false) List<String> stationId,
                                                                       @RequestParam(required = false) String[] time,
                                                                       @RequestParam(required = false) Integer current,
                                                                       @RequestParam(required = false) Integer size,
                                                                       @RequestParam(required = false) String content) {

        Page<TdHygfJpInverterWarnDto> result = new Page<>();
        result.setCurrent(current);
        result.setSize(size);
//        JpStationDto reviewDto = new JpStationDto();
//        Map<String, String> nameMaps = new HashMap<>();
//        if (null != stationName && stationName != "") {
//            reviewDto.setName(stationName);
//        }
//        List<JpStation> jpStation = jpStationMapper.getJpStation(reviewDto);
//        if (CollectionUtil.isEmpty(jpStation)) {
//            result.setTotal(0);
//            List<TdHygfJpInverterWarnDto> list = new ArrayList<>();
//            result.setRecords(list);
//            return ResponseHelper.buildResponse(result);
//
//        }
//        nameMaps = jpStation.stream().collect(Collectors.toMap(JpStation::getThirdStationId, JpStation::getName, (existing, replacement) -> existing));
//
//        if (null == stationId) {
//            stationId = jpStation.stream().map(JpStation::getThirdStationId).collect(Collectors.toList());
//        }
        String startTime = "";
        String endTime = "";
        if (null != time) {

            try {
                startTime = String.valueOf(DateUtils.dateParse(time[0].replace("[", ""), null).getTime());
                Date date = DateUtils.dateParse(time[1].replace("]", ""), null);
                endTime = String.valueOf(DateUtils.dateAddDays(date, 1).getTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotEmpty(snCode)) {
            snCode = '%' + snCode + '%';
        }
        if (StringUtils.isNotEmpty(content)) {
            content = '%' + content + '%';
        }
        if (StringUtils.isNotEmpty(stationName)) {
            stationName = '%' + stationName + '%';
        }


        List<TdHygfJpInverterWarnDto> maps = tdHygfJpInverterWarnServiceImpl.selectWarnList(state,regionalCompaniesCode,amosCompanyCode, thirdStationId, type, level, minvalue, maxValue, snCode, stationId, startTime, endTime, content, current, size, handlerStatus, stationName);
        for (TdHygfJpInverterWarnDto map : maps) {
//            if (nameMaps.containsKey(map.getThirdStationId())) {
//                map.setStationName(nameMaps.get(map.getThirdStationId()));
//            }
            String te = map.getTimeLong() != null ? TimeUtil.longFormat(map.getTimeLong()) : "";
            map.setTimeLongFormat(te);
        }

        result.setTotal(tdHygfJpInverterWarnServiceImpl.selectWarnListTotal(state,regionalCompaniesCode,amosCompanyCode, thirdStationId, type, level, minvalue, maxValue, snCode, stationId, startTime, endTime, content, handlerStatus, stationName));
        List<Long> waringIds = maps.stream().map(tdHygfJpInverterWarnDto -> tdHygfJpInverterWarnDto.getCreatedTime()).collect(Collectors.toList());
        if (waringIds.size() == 0) {
            waringIds = Arrays.asList(0L);
        }
        List<HYGFMaintenanceTickets> hygfMaintenanceTicketsList = hygfMaintenanceTicketsMapper.selectList(new QueryWrapper<HYGFMaintenanceTickets>().in("warning_id", waringIds));
        if (hygfMaintenanceTicketsList.size() > 0) {
            maps.forEach(tdHygfJpInverterWarnDto -> {
                Set<String> status = hygfMaintenanceTicketsList.stream().filter(hygfmaintenanceTickets -> tdHygfJpInverterWarnDto.getCreatedTime().equals(hygfmaintenanceTickets.getWarningId())).map(HYGFMaintenanceTickets::getHandlerStatus).collect(Collectors.toSet());
                if (status.contains("未处理")) {
                    tdHygfJpInverterWarnDto.setTicketStatus("处理中");
                }
                if (status.contains("已处理") && status.size() == 1) {
                    tdHygfJpInverterWarnDto.setTicketStatus("已处理");
                }
            });
        }
        result.setRecords(maps);
        return ResponseHelper.buildResponse(result);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "户用光伏逆变器报警表统计数据查询", notes = "户用光伏逆变器报警表统计数据查询")
    @GetMapping(value = "/queryAlarmNumber")
    @UserLimits
    public ResponseModel<Map<String, Object>> queryAlarmNumber(String regionalCompaniesCode,
                                                               String amosCompanyCode,
                                                               String thirdStationId,
                                                               String type
    ) {
//        Map<String, Object> result = tdHygfJpInverterWarnServiceImpl.queryAlarmNumber(regionalCompaniesCode, amosCompanyCode, thirdStationId, type);

        Map<String, Object> result = new HashMap<>();

        int wcl = tdHygfJpInverterWarnServiceImpl.selectWarnTotal(Arrays.asList("未处理"), regionalCompaniesCode, amosCompanyCode, thirdStationId, type);
        int ycl = tdHygfJpInverterWarnServiceImpl.selectWarnTotal(Arrays.asList("已处理", "已恢复"), regionalCompaniesCode, amosCompanyCode, thirdStationId, type);

        result.put("wcl", wcl);
        result.put("ycl", ycl);

        return ResponseHelper.buildResponse(result);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "户用光伏统计数据查询", notes = "户用光伏统计数据查询")
    @GetMapping(value = "/queryStateNumber")
    @UserLimits
    public ResponseModel<Map<String, Object>> queryStateNumber(@RequestParam(required = false) String regionalCompaniesCode,
                                                               @RequestParam(required = false) String amosCompanyCode,
                                                               @RequestParam(required = false) String thirdStationId,
                                                               @RequestParam(required = false) String type
    ) {
        Map<String, Object> result = tdHygfJpInverterWarnServiceImpl.queryStateNumber(regionalCompaniesCode, amosCompanyCode, thirdStationId, type);

        return ResponseHelper.buildResponse(result);
    }

}
