package com.yeejoin.equipmanage.controller;

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

import com.yeejoin.equipmanage.common.entity.vo.EquiplistSpecificBySystemVO;
import com.yeejoin.equipmanage.common.utils.SpringUtils;
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.utils.CommonResponseUtil;
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 {

    @Autowired
    IEquipmentSpecificSerivce equipmentSpecificSerivce;

    @Autowired
    EquipmentSpecificMapper equipmentSpecificMapper;

    @Autowired
    IEquipmentDetailService equipmentDetailService;

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

    @Autowired
    FireFightingSystemServiceImpl fireFightingSystemServiceImpl;

    /**
     * 补码页面分页
     *
     * @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));
    }

    /**
     * @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));
    }


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

}
