package com.yeejoin.equipmanage.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.dto.OrgMenuDto;
import com.yeejoin.equipmanage.common.utils.CommonPageable;
import com.yeejoin.equipmanage.common.utils.CommonResponseUtil;
import com.yeejoin.equipmanage.common.utils.DateUtils;
import com.yeejoin.equipmanage.common.utils.StringUtil;
import com.yeejoin.equipmanage.common.vo.BigScreenVo;
import com.yeejoin.equipmanage.config.PersonIdentify;
import com.yeejoin.equipmanage.fegin.IotFeign;
import com.yeejoin.equipmanage.mapper.FireFightingSystemMapper;
import com.yeejoin.equipmanage.service.IFireFightingSystemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Api(tags = "一张图大屏API")
@RequestMapping(value = "/bigScreen", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class BigScreenController extends AbstractBaseController {

    @Autowired
    private IFireFightingSystemService iFireFightingSystemService;

    @Autowired
    private FireFightingSystemMapper fireFightingSystemMapper;

    @Autowired
    private IotFeign iotFeign;

    @Value("${equipment.pressurepump.start}")
    private String pressurePumpStart;

    @GetMapping(value = "/list")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "系统、消防水池、工业水池、水源总容积、消防车辆(接口弃用)", notes = "系统、消防水池、工业水池、水源总容积、消防车辆")
    public ResponseModel<BigScreenVo> getSystemAlarmInfoNum(@RequestParam(required = false, value = "companyCode") String companyCode) {
        return CommonResponseUtil.success(iFireFightingSystemService.getSystemAlarmInfoNum(companyCode));
    }

    @GetMapping(value = "/getCarInfo")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "系统、消防水池、工业水池、消防车辆", notes = "系统、消防水池、工业水池、消防车辆")
    public ResponseModel<BigScreenVo> getCarInfo(@RequestParam(required = false, value = "companyCode") String companyCode) {
        return CommonResponseUtil.success(iFireFightingSystemService.getCarInfo(companyCode));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "水源信息列表")
    @GetMapping("/getWaterInfo")
    public ResponseModel getWaterInfo(CommonPageable commonPageable, @RequestParam(value = "companyCode",required = false)String companyCode) {
        if (commonPageable.getPageNumber() == 0) {
            commonPageable.setPageNumber(1);
        }

        Page page = new Page<>(commonPageable.getPageNumber(), commonPageable.getPageSize());
        return CommonResponseUtil.success(iFireFightingSystemService.getWaterInfo(page, companyCode, null));
    }

    @PersonIdentify
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "稳压泵列表信息")
    @GetMapping("/getPressurePumpInfo")
    public ResponseModel getPressurePumpInfo(CommonPageable commonPageable,@RequestParam(required = false, value = "companyCode")String companyCode) {
        if (commonPageable.getPageNumber() == 0) {
            commonPageable.setPageNumber(1);
        }

        Page page = new Page<>(commonPageable.getPageNumber(), commonPageable.getPageSize());
        String bizOrgCode = null;
        if (StringUtil.isNotEmpty(companyCode)) {
            bizOrgCode = fireFightingSystemMapper.queryByCompanyCode(companyCode);
        }
        Page<Map<String, Object>> pressurePumpInfo = fireFightingSystemMapper.getPressurePumpInfo(page, bizOrgCode, null);
        pressurePumpInfo.getRecords().stream().map(item -> {
            item.put("startAndStopNum", 0);
            item.put("update_time", "--");
            item.put("equipment_index_name", "--");
            String prefix = null;
            String suffix = null;
            String iotCode = item.get("iot_code").toString();
            if (iotCode.length() > 8) {
                prefix = iotCode.substring(0, 8);
                suffix = iotCode.substring(8);
            } else {
                throw new BadRequest("装备物联编码错误，请确认！");
            }

            String nowStrLong = DateUtils.getNowStrLong();
            Date startDate = DateUtils.dateAddMinutes(null, -4);
            String startDateStr = DateUtils.convertDateToString(startDate, DateUtils.DATE_TIME_PATTERN);
            ResponseModel entity1 = null;
            ResponseModel entity2 = null;
            try {
                entity1 = iotFeign.selectListNew(prefix,suffix, startDateStr, nowStrLong,  "true", pressurePumpStart);
                entity2 = iotFeign.selectListNew(prefix,suffix, startDateStr, nowStrLong,  "false", pressurePumpStart);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (200 == entity1.getStatus() && 200 == entity2.getStatus()) {
                String json1 = JSON.toJSONString(entity1.getResult());
                List<Map<String, String>> listObject1 = (List<Map<String, String>>) JSONArray.parse(json1);
                String json2 = JSON.toJSONString(entity2.getResult());
                List<Map<String, String>> listObject2 = (List<Map<String, String>>) JSONArray.parse(json2);
                listObject1.addAll(listObject2);
                List<Map<String, String>> collect = listObject1.stream().filter(t -> (t.containsKey(pressurePumpStart) && t.get(pressurePumpStart).equals("true")) || (t.containsKey(pressurePumpStart) && t.get(pressurePumpStart).equals("false"))).collect(Collectors.toList());
                int num = collect.size();
                item.put("startAndStopNum", num);
            }
            item.put("stateDesc", (Integer) item.get("startAndStopNum") <= 1 && Integer.parseInt(String.valueOf(item.get("isAlarm"))) == 0 ? "1" : "0");
            item.put("normalNum", (Integer) item.get("startAndStopNum") <= 1 ? 1 : 0);
            item.put("unNormalNum", (Integer) item.get("startAndStopNum") <= 1 ? 0 : 1);
            Map<String, String> stateMap = fireFightingSystemMapper.queryPressureNowStateBySpecificId((Long) item.get("id"));
            if (!ObjectUtils.isEmpty(stateMap) && stateMap.containsKey("update_date") && stateMap.containsKey("equipment_index_name")) {
                item.put("update_time", String.valueOf(stateMap.get("update_date")).replaceAll("T", " "));
                item.put("equipment_index_name", stateMap.get("equipment_index_name"));
            }
            return item;
        }).collect(Collectors.toList());
        return CommonResponseUtil.success(pressurePumpInfo);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "系统今日告警信息列表")
    @GetMapping("/getSystemInfo")
    public ResponseModel getSystemInfo(CommonPageable commonPageable, @RequestParam(value = "companyCode",required = false)String companyCode) {
        if (commonPageable.getPageNumber() == 0) {
            commonPageable.setPageNumber(1);
        }
        Page page = new Page<>(commonPageable.getPageNumber(), commonPageable.getPageSize());
        return CommonResponseUtil.success(iFireFightingSystemService.getSystemInfo(page, companyCode, null));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "卡片BigSystem报警处理情况统计")
    @GetMapping("/statistic/alarm")
    public ResponseModel getSystemAlarmStatistic(
            @RequestParam(value = "systemCode", required = false) String systemCode,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate
    ) {
        return CommonResponseUtil.success(iFireFightingSystemService.getSystemAlarmStatistic(systemCode, startDate, endDate));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "卡片BigSystem报警趋势统计")
    @GetMapping("/statistic/trend")
    public ResponseModel getSystemAlarmTrend(@RequestParam(value = "systemCode", required = false)String systemCode,
                                             @RequestParam(value = "updateTime", required = false)String updateTime) {
        return CommonResponseUtil.success(iFireFightingSystemService.getSystemAlarmTrend(systemCode, updateTime));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "卡片BigSystem报警趋势统计")
    @GetMapping("/statistic/trend/forSbpt")
    public ResponseModel getSystemAlarmTrendForSbpt(@RequestParam(value = "systemCode", required = false)String systemCode,
                                             @RequestParam(value = "updateTime", required = false)String updateTime) {
        return CommonResponseUtil.success(iFireFightingSystemService.getSystemAlarmTrendForSbpt(systemCode, updateTime));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "卡片BigSystem树接口")
    @GetMapping("/system/tree")
    public List<OrgMenuDto> getSystemEquipTree(@RequestParam(value = "systemCode")String systemCode) {
        return iFireFightingSystemService.getSystemEquipTree(systemCode);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "卡片BigSystem点击树查对应设备")
    @GetMapping("/system/equip/page")
    public ResponseModel getEquipmentsBySystemInfo(CommonPageable commonPageable, @RequestParam(value = "systemCode",required = false)String systemCode,
                                                   @RequestParam(value = "equipmentCode", required = false)String equipmentCode) {
        if (commonPageable.getPageNumber() == 0) {
            commonPageable.setPageNumber(1);
        }
        Page page = new Page<>(commonPageable.getPageNumber(), commonPageable.getPageSize());
        return CommonResponseUtil.success(iFireFightingSystemService.getEquipmentsBySystemInfo(page, systemCode, equipmentCode));
    }

}
