package com.yeejoin.equipmanage.controller;

import java.util.*;
import java.util.stream.Collectors;

import com.yeejoin.equipmanage.common.constant.Constant;
import com.yeejoin.equipmanage.common.entity.vo.EquiplistSpecificBySystemVO;
import com.yeejoin.equipmanage.common.utils.*;
import com.yeejoin.equipmanage.fegin.IotFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
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.utils.ResponseModel;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yeejoin.equipmanage.common.dto.EquipmentSpecificDto;
import com.yeejoin.equipmanage.common.entity.EquipmentDetail;
import com.yeejoin.equipmanage.common.entity.EquipmentSpecific;
import com.yeejoin.equipmanage.common.entity.dto.EquipmentSpecificDTO;
import com.yeejoin.equipmanage.common.entity.dto.SourceNameListDTO;
import com.yeejoin.equipmanage.common.entity.vo.ComplementCodeVO;
import com.yeejoin.equipmanage.common.entity.vo.SourceNameByEquipSpeIdVO;
import com.yeejoin.equipmanage.common.vo.EquipmentOnCarVo;
import com.yeejoin.equipmanage.common.vo.VideoOnEquipmentSpecificVo;
import com.yeejoin.equipmanage.mapper.EquipmentSpecificMapper;
import com.yeejoin.equipmanage.service.IEquipmentDetailService;
import com.yeejoin.equipmanage.service.IEquipmentSpecificSerivce;
import com.yeejoin.equipmanage.service.impl.FireFightingSystemServiceImpl;

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.util.ObjectUtils;
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.ResponseModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ZeHua Li
 * @date 2020/10/29 14:26
 * @since v2.0
 */
@Slf4j
@RestController
@Api(tags = "单个设备管理")
@RequestMapping(value = "/equipSpecific")
public class EquipmentSpecificController extends AbstractBaseController {

    public static final int RESULT_SUCCESS_CODE = 200;

    @Autowired
    IEquipmentSpecificSerivce equipmentSpecificSerivce;

    @Autowired
    EquipmentSpecificMapper equipmentSpecificMapper;

    @Autowired
    IEquipmentDetailService equipmentDetailService;

    @Value("${systemctl.sync.switch}")
    private Boolean syncSwitch;

    @Autowired
    FireFightingSystemServiceImpl fireFightingSystemServiceImpl;

    @Autowired
    IotFeign iotFeign;

    /**
     * 补码页面分页
     *
     * @return
     */
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "列表分页查询", notes = "补码列表接口,废弃未用到")
    public IPage<ComplementCodeVO> saveEquipmentPoint(@RequestBody EquipmentSpecificDTO equipmentSpecific) {
        return equipmentSpecificSerivce.selectEquipmentSpecific(equipmentSpecific);
    }

    /**
     * 通过id获取设备区域建筑等信息
     *
     * @return
     */
    @GetMapping(value = "/getSourceNameByEquipSpeId")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "通过id获取设备区域建筑等信息", notes = "通过id获取设备区域建筑等信息")
    public SourceNameByEquipSpeIdVO getSourceNameByEquipSpeId(Long id) {
        return equipmentSpecificSerivce.getSourceNameByEquipSpeId(id);
    }

    /**
     * 通过id获取设备区域建筑等信息
     *
     * @return
     */
    @PostMapping(value = "/getSourceNameList")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "获取设备区域建筑列表等信息", notes = "获取设备区域建筑列表等信息")
    public IPage<SourceNameByEquipSpeIdVO> getSourceNameList(@RequestBody SourceNameListDTO sourceNameListDTO) {
        return equipmentSpecificSerivce.getSourceNameList(sourceNameListDTO.getPage(), sourceNameListDTO.getWarehouseStructureId(), sourceNameListDTO.getSourceId(), sourceNameListDTO.getEquipmentName(), sourceNameListDTO.getEquipmentCode());
    }

    /**
     * 修改
     *
     * @return
     */
    @RequestMapping(value = "/exit", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "修改"	, notes = "修改")
    public EquipmentSpecific updateEquipmentSpecific(@RequestBody EquipmentSpecific equipmentSpecific) {
        EquipmentSpecific updateEquipmentSpecific = equipmentSpecificSerivce.updateEquipmentSpecific(equipmentSpecific, getSelectedOrgInfo(), getUserInfo());
        if (syncSwitch) {
            // TODO 后续判断成功，执行同步
            Long equipmentDetailId = updateEquipmentSpecific.getEquipmentDetailId();
            EquipmentDetail equipmentDetail = equipmentDetailService.getById(equipmentDetailId);
            equipmentSpecificSerivce.equipSpecificDataSync(equipmentDetail.getEquipmentId());
        }
        return updateEquipmentSpecific;
    }

    /**
     * 设备报警信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public Map<String, Object> selectById(Long id) {
        return equipmentSpecificSerivce.getAll(id);
    }

    /**
     * 获取巡检维保信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/getMaintenanceInfo", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public Map<String, Object> getMaintenanceInfo(String checkDate) {
        return equipmentSpecificSerivce.getMaintenanceInfo(checkDate);
    }

    /**
     * 组态使用装备卡片数据
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/getOneCard", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "组装组态使用装备卡片数据")
    public Object getOneCard(Long id, String type) {
        return equipmentSpecificSerivce.getOneCard(id, type);
    }

    /**
     * 获取巡检维保信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/hasIotCode/{id}", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询物联编码是否有重复", notes = "查询物联编码是否有重复")
    public ResponseModel hasIotCode(@PathVariable("id") String id, String iotCode) {
        Map map1 = new HashMap();
        map1.put("state", "FAILED");
        map1.put("message", "若您设置物联编码，请至少输入9位字符！");
        Map map2 = new HashMap();
        map2.put("state", "DUPLICATE");
        map2.put("message", "物联编码重复，请重新设置！");
        Map map3 = new HashMap();
        map3.put("state", "SUCCESS");
        map3.put("message", "成功！");
        if (iotCode.trim().length() < 9) {
            return CommonResponseUtil.success(map1);
        }
        List<String> list = equipmentSpecificMapper.getIotCodeList(id);
        List<String> iotCodeList = new ArrayList<String>();
        if (list != null && !list.isEmpty()) {
            iotCodeList = list.stream().filter(x -> x.equals(iotCode)).collect(Collectors.toList());
        }
        if (iotCodeList.size() == 0) {
            return CommonResponseUtil.success(map3);
        } else {
            return CommonResponseUtil.success(map2);
        }
    }

    /**
     * 获取设备详情
     *
     * @param equipmentSpecific
     * @return
     */
    @RequestMapping(value = "/getEquipSpecificDetail", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "获取设备详情", notes = "获取设备详情")
    public ResponseModel getEquipSpecificDetail(@RequestBody EquipmentSpecific equipmentSpecific) {
        return CommonResponseUtil.success(equipmentSpecificSerivce.getEquipSpecificDetail(equipmentSpecific));
    }

    /**
     * 获取instanceId和orgCode
     *
     * @param sourceId
     * @return
     */
    @RequestMapping(value = "/getInstanceIdAndOrgCode", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取instanceId和orgCode", notes = "获取instanceId和orgCode")
    public ResponseModel getInstanceIdAndOrgCode(@RequestParam Long sourceId) {
        if (Objects.isNull(sourceId)) {
            return CommonResponseUtil.success(null);
        }
        return CommonResponseUtil.success(equipmentSpecificSerivce.getInstanceIdAndOrgCode(sourceId));
    }

    /**
     * @param like    设备名称或编码code
     * @param notLike wl_equipment_category，code不包含（右%），多个用英文逗号隔开
     * @param status  wl_stock_detail.status
     * @return
     */
    @RequestMapping(value = "/getAirEquipSpecificList", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取特定条件设备集合", notes = "获取特定条件设备集合")
    public ResponseModel getAirEquipSpecificList(@RequestParam(required = false) String like,
                                                 @RequestParam(required = false) String notLike,
                                                 @RequestParam(required = false) Integer status) {
        return CommonResponseUtil.success(equipmentSpecificSerivce.getAirEquipSpecificList(like, notLike, status));
    }

    /**
     * 页面分页
     *
     * @return
     */
    @RequestMapping(value = "/getAirEquipSpecificPage", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "列表分页查询", notes = "列表分页查询")
    public IPage<EquipmentOnCarVo> onCarVoIPage(@RequestBody EquipmentSpecificDto equipmentSpecificDto) {
        return equipmentSpecificSerivce.onCarVoIPage(equipmentSpecificDto);
    }

    @RequestMapping(value = "/getAirEquipSpecificDetail", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取设备详情", notes = "获取特定条件设备集合")
    public ResponseModel getAirEquipSpecificDetail(@RequestParam Long stockDetailId) {
        return CommonResponseUtil.success(equipmentSpecificSerivce.getAirEquipSpecificDetail(stockDetailId));
    }

    /**
     * 根据specificId删除装备相关数据
     *
     * @param specificId id
     * @return ResponseModel
     */
    @DeleteMapping(value = "/delEquipmentBySpecificId")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "删除装备相关所有数据", notes = "删除装备相关所有数据")
    public ResponseModel delEquipmentBySpecificId(@RequestParam Long specificId) {
        EquipmentSpecific equipmentSpecific = equipmentSpecificSerivce.getById(specificId);
        Boolean result = equipmentSpecificSerivce.delEquipmentBySpecificId(specificId);
        // 同步刷新，不在异步，原因速度3秒左右
        this.refreshCount(equipmentSpecific.getBizOrgCode());
        return CommonResponseUtil.success(result);
    }

    private void refreshCount(String bizOrgCode) {
        try {
            equipmentSpecificSerivce.refreshStaData();
            fireFightingSystemServiceImpl.refreshEquipmentTypeAndCount(bizOrgCode);
        } catch (Exception e) {
            log.error("刷新装备分类树缓存失败" + e.getMessage());
        }
    }

    /**
     * 根据specificIds删除装备相关数据
     *
     * @param specificIds id
     * @return ResponseModel
     */
    @DeleteMapping(value = "/delAllEquipmentBySpecificIds")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "批量删除装备相关所有数据", notes = "批量删除装备相关所有数据")
    public ResponseModel delEquipmentBySpecificId(@RequestBody List<Long> specificIds) {
        if (ObjectUtils.isEmpty(specificIds)) {
            return CommonResponseUtil.failure("参数为空");
        }
        specificIds.forEach(specificId -> {
            equipmentSpecificSerivce.delEquipmentBySpecificId(specificId);
            EquipmentSpecific equipmentSpecific = equipmentSpecificSerivce.getById(specificId);
            // 同步刷新，不在异步，原因速度3秒左右
            this.refreshCount(equipmentSpecific.getBizOrgCode());
        });
        return CommonResponseUtil.success();
    }

    @RequestMapping(value = "/getFessIndexDetails", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取中州环境监测指标详情", notes = "获取中州环境监测指标详情")
    public ResponseModel getFessIndexDetails() {
        return CommonResponseUtil.success(equipmentSpecificSerivce.getFessIndexDetails());
    }

    @RequestMapping(value = "/videoOnEquipmentSpecific", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "摄像头绑定设备", notes = "摄像头绑定设备")
    public ResponseModel videoOnEquipmentSpecific(@RequestBody VideoOnEquipmentSpecificVo videoOnEquipmentSpecificVo) {
        return CommonResponseUtil.success(equipmentSpecificSerivce.videoOnEquipmentSpecific(videoOnEquipmentSpecificVo));
    }
    @RequestMapping(value = "/delVideoOnEquipmentSpecific/{equipmentSpecificId}/{videoId}", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "摄像头解绑设备", notes = "摄像头绑定设备")
    public ResponseModel delVideoOnEquipmentSpecific( @PathVariable Long equipmentSpecificId, @PathVariable Long videoId) {

        return CommonResponseUtil.success(equipmentSpecificSerivce.delVideoOnEquipmentSpecific(equipmentSpecificId,videoId));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/{buildingId}/list")
    @ApiOperation(httpMethod = "GET", value = "查询指定建筑下的装备列表", notes = "查询指定建筑下的装备列表")
    public List<EquiplistSpecificBySystemVO> getListByWarehouseStructureId( @PathVariable Long buildingId){
        return equipmentSpecificMapper.getListByWarehouseStructureId(buildingId);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getListByEquipmentCode/{code}")
    @ApiOperation(httpMethod = "GET", value = "根据装备分类code获取装备list", notes = "根据装备分类code获取装备list")
    public List<Map<String, Object>> getListByEquipmentCode( @PathVariable String code){
        return equipmentSpecificSerivce.getListByEquipmentCode(code);
    }

    @GetMapping(value = "/index/normal")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询非告警指标list", notes = "查询非告警指标list")
    public ResponseModel normalIndexInfoList(@RequestParam(required = false) String startDate,
                                             @RequestParam(required = false) String endDate){
        return CommonResponseUtil.success(equipmentSpecificSerivce.normalIndexInfoList(startDate, endDate));
    }

    @GetMapping(value = "/info/fire")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询火报系统指标", notes = "查询火报系统指标")
    public ResponseModel getFireAutoSysInfo(@RequestParam(required = false) String startDate,
                                             @RequestParam(required = false) String endDate){
        return CommonResponseUtil.success(equipmentSpecificSerivce.getFireAutoSysInfo(startDate, endDate));
    }

    @GetMapping(value = "/info/paomo")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询泡沫系统指标", notes = "查询泡沫系统指标")
    public ResponseModel getPaomoSysInfo(@RequestParam(required = false) String startDate,
                                             @RequestParam(required = false) String endDate){
        return CommonResponseUtil.success(equipmentSpecificSerivce.getPaomoSysInfo(startDate, endDate));
    }

    @GetMapping(value = "/info/water")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询给水系统指标", notes = "查询给水系统指标")
    public ResponseModel getWaterSysInfo(@RequestParam(required = false) String startDate,
                                             @RequestParam(required = false) String endDate){
        return CommonResponseUtil.success(equipmentSpecificSerivce.getWaterSysInfo(startDate, endDate));
    }

    @RequestMapping(value = "/equipment/iotIndexInfo/{equipSpeId}", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据装备id获取物联日志", notes = "根据装备id获取物联日志")
    public ResponseModel getEquipmentIotIndexInfo(@PathVariable String equipSpeId, @RequestParam String beginDate,  @RequestParam String endDate,
                                                  @RequestParam(required = false) Integer isTrend, @RequestParam(required = false) String fieldKey) {

        // 1.根据 equipSpeId 查询装备iotCode
        EquipmentSpecific equipmentSpecific = equipmentSpecificMapper.selectById(equipSpeId);
        if (ObjectUtils.isEmpty(equipmentSpecific)) {
            return CommonResponseUtil.failure("未查询到装备信息!");
        }
        String iotCode = equipmentSpecific.getIotCode();
        String prefix = null;
        String suffix = null;
        if (StringUtil.isNotEmpty(iotCode) && iotCode.length() > 8) {
            prefix = iotCode.substring(0, 8);
            suffix = iotCode.substring(8);
        } else {
            return CommonResponseUtil.failure("装备物联编码错误，请确认！");
        }
        ResponseModel entity = null;
        try {
            entity = iotFeign.selectList(getAppKey(), getProduct(), getToken(), beginDate, endDate, prefix, suffix, null);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("调用iot服务出错");
            return CommonResponseUtil.failure("请求失败");
        }

        if (RESULT_SUCCESS_CODE != entity.getStatus() && ObjectUtils.isEmpty(entity.getResult())) {
            log.error("查询物联日志数据为空或iotCode为 (" + iotCode + ") 的装备不存在于物联系统中！");
            return CommonResponseUtil.failure("物联日志数据为空");
        }

        return CommonResponseUtil.success(equipmentSpecificSerivce.getIndexInfoList(iotCode, entity, isTrend, fieldKey));
    }



}
