package com.yeejoin.amos.fas.business.controller;

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

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.ObjectUtils;
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.PutMapping;
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 com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.fas.business.action.model.FireEquimentDataRo;
import com.yeejoin.amos.fas.business.action.model.ProtalDataRo;
import com.yeejoin.amos.fas.business.bo.DangerResultBo;
import com.yeejoin.amos.fas.business.bo.RiskSourceSynBo;
import com.yeejoin.amos.fas.business.param.AlarmParam;
import com.yeejoin.amos.fas.business.param.FmeaBindParam;
import com.yeejoin.amos.fas.business.service.intfc.IRiskFactorService;
import com.yeejoin.amos.fas.business.service.intfc.IRiskSourceService;
import com.yeejoin.amos.fas.business.service.model.ContingencyDeviceStatus;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import com.yeejoin.amos.fas.core.common.request.CommonPageable;
import com.yeejoin.amos.fas.core.common.response.RiskSourceTreeResponse;
import com.yeejoin.amos.fas.core.enums.ReserveEnum;
import com.yeejoin.amos.fas.core.util.CommonResponse;
import com.yeejoin.amos.fas.core.util.CommonResponseUtil;
import com.yeejoin.amos.fas.core.util.CommonResponseUtil2;
import com.yeejoin.amos.fas.core.util.ResponseModel;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping("/api/risksource")
@Api(tags = "风险点API")
public class RiskSourceController extends AbstractBaseController {
    private final Logger log = LoggerFactory.getLogger(RiskSourceController.class);

    @Autowired
    IRiskFactorService iRiskFactorService;

    @Autowired
    IRiskSourceService riskSourceService;

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    //@Authorization(ingore = true)
    @ApiOperation(httpMethod = "GET", value = "查询风险点子项", notes = "查询风险点子项")
    @RequestMapping(value = "/children/list", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryRiskSourceByPage() {
        return CommonResponseUtil.success(riskSourceService.queryForRegion());
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    //@Authorization(ingore = true)
    @ApiOperation(httpMethod = "GET", value = "三维图统计", notes = "三维图统计")
    @RequestMapping(value = "/collection3d", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse collection3d() {
        return CommonResponseUtil.success(riskSourceService.queryFor3DStatistics());
    }


    /**
     * 查询风险点RPN统计
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询风险点RPN统计", notes = "查询风险点RPN统计")
    @RequestMapping(value = "/rpn/list", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryRPNReport() {
        return CommonResponseUtil.success(riskSourceService.queryRPNReport());
    }


    /**
     * 风险上升率
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "风险上升率", notes = "风险上升率")
    @RequestMapping(value = "/riseuprate", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryForRiseUp() throws Exception {
        return CommonResponseUtil.success(riskSourceService.queryForRiseUp());
    }


    /**
     * 发生率严重度矩阵
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "发生率严重度矩阵", notes = "发生率严重度矩阵")
    @RequestMapping(value = "/matrix", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryForMatrix() throws Exception {
        return CommonResponseUtil.success(riskSourceService.queryForMatrix());
    }

    /**
     * 获取风险点树型结构
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    //@Authorization(ingore = true)
    @ApiOperation(httpMethod = "GET", value = "获取风险点树型结构", notes = "获取风险点树型结构")
    @RequestMapping(value = "/riskSourceTress", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse getRiskSourceTress() {
        ReginParams reginParams = getSelectedOrgInfo();
        String compCode = getOrgCode(reginParams);
        List<RiskSourceTreeResponse> riskSources = riskSourceService.findRiskSourceTrees(compCode);
        return CommonResponseUtil.success(getRiskSourcesTree(riskSources));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "远程同步", notes = "将本地 风险模型推送到远程同步")
    @PutMapping(value = "/synToEquipManage")
    public CommonResponse synToEquipManage() {
        ReginParams reginParams = getSelectedOrgInfo();
        String compCode = getOrgCode(reginParams);
//        if (!riskSourceService.isSynEquipManage()) {
            return CommonResponseUtil.failure("同步功能未开启");
//        }
//        List<RiskSourceTreeResponse> riskSources = riskSourceService.findRiskSourceTrees(compCode).stream().filter(source -> IS_RISK_AREA.equalsIgnoreCase(source.getIsRegion())).collect(Collectors.toList());
//        String synMsg = riskSourceService.synToEquipManage(getAppKey(), getProduct(), getToken(), SUCCESS, getRiskSourcesTree(riskSources));
//        if (synMsg != null) {
//            return CommonResponseUtil.failure(synMsg);
//        }
//        return CommonResponseUtil.success();
    }

    /**
     * 获取区域树型结构
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    //@Authorization(ingore = true)
    @ApiOperation(httpMethod = "GET", value = "获取区域树型结构", notes = "获取区域树型结构")
    @RequestMapping(value = "/regionTress", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse getRegionTress() {
        ReginParams reginParams = getSelectedOrgInfo();
        String compCode = getOrgCode(reginParams);
        List<RiskSourceTreeResponse> riskSources = riskSourceService.findRiskSourceTrees(compCode);
        return CommonResponseUtil.success(getRegionTree(riskSources));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    //@Authorization(ingore = true)
    @ApiOperation(httpMethod = "GET", value = "统计级别为1的风险点下面", notes = "获取风险点树型结构")
    @RequestMapping(value = "/query3DStatistics/{markerType}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse query3DStatistics(@PathVariable(value = "markerType", required = true) String markerType) throws Exception {
        if ("riskSource".equals(markerType)) {
            return riskSourceStatistics();
        } else if ("risk".equals(markerType)) {
            return riskStatistics();
        } else if ("impEquipment".equals(markerType)) {
            return equipStatistics();
        } else if ("fireResource".equals(markerType)) {
            String[] type = {"4", "3"};
            return equipStatistics(type);
        } else if ("monitorEquipment".equals(markerType)) {
            String[] type = {"0"};
            return equipStatistics(type);
        } else if ("video".equals(markerType)) {
            String[] type = {"2"};
            return equipStatistics(type);
        }
        return CommonResponseUtil.failure("未定义类型");
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    //@Authorization(ingore = true)
    @ApiOperation(httpMethod = "GET", value = "统计级别为1的风险点下面", notes = "获取风险点树型结构")
    @RequestMapping(value = "/riskSourceStatistics", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse riskSourceStatistics() throws Exception {
        ReginParams reginParams = getSelectedOrgInfo();
        String compCode = getOrgCode(reginParams);
        List<RiskSourceTreeResponse> riskSources = riskSourceService.findRiskSourceTrees(compCode);
        List<RiskSourceTreeResponse> treeRiskSources = getRiskSourcesTree(riskSources);
        return CommonResponseUtil.success(riskSourceStatistics(treeRiskSources));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    //@Authorization(ingore = true)
    @ApiOperation(httpMethod = "GET", value = "统计级别为1的风险点下面设备统计", notes = "统计级别为1的风险点下面设备统计")
    @RequestMapping(value = "/equipStatistics", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse equipStatistics() throws Exception {
        List<RiskSourceTreeResponse> riskSources = riskSourceService.findRiskSourceEquipStatistics();
        List<RiskSourceTreeResponse> treeRiskSources = getRiskSourcesEquipTree(riskSources);
        return CommonResponseUtil.success(riskSourceEquipStatistics(treeRiskSources, true, 0));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    //@Authorization(ingore = true)
    @ApiOperation(httpMethod = "GET", value = "统计级别为1的巡检点统计", notes = "统计级别为1的巡检点统计")
    @RequestMapping(value = "/checkPointStatistics", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse riskStatistics() throws Exception {
        List<RiskSourceTreeResponse> riskSources = riskSourceService.getCheckPointRiskSources();
        List<RiskSourceTreeResponse> treeRiskSources = getRiskSourcesEquipTree(riskSources);
        return CommonResponseUtil.success(checkPointEquipStatistics(treeRiskSources, false, 0));
    }


    private Object checkPointEquipStatistics(List<RiskSourceTreeResponse> list, boolean isLevel, int level) {
        List<Map<String, Object>> treeList = new ArrayList<Map<String, Object>>();
        if (!ObjectUtils.isEmpty(list)) {
            Map<String, Object> map = new HashMap<>();

//        	List<RiskSourceTreeResponse> firstChildrens = list.get(0).getChildren();
            list.forEach(item -> {
//        		if (!ObjectUtils.isEmpty(item.getPosition3d())) {
                Map<String, Object> itemMap = (Map<String, Object>) map.get(item.getId());
                if (ObjectUtils.isEmpty(itemMap)) {
                    itemMap = new HashMap<>();
                    itemMap.put("id", item.getId());
                    itemMap.put("key", "key" + item.getId());
                    itemMap.put("name", item.getName());
                    if (isLevel) {
                        itemMap.put("level", level);
                    } else {
                        itemMap.put("level", item.getLevel());
                    }

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

                    if (!ObjectUtils.isEmpty(item.getPosition3d())) {
                        String[] pos = item.getPosition3d().split(",");
                        position.put("x", pos[0]);
                        position.put("y", pos[1]);
                        position.put("z", pos[2]);
                    }
                    Map<String, Object> rotation = new HashMap<>();
                    rotation.put("x", 0);
                    rotation.put("y", 0);
                    rotation.put("z", 0);
                    Map<String, Object> scale = new HashMap<>();
                    scale.put("x", 1);
                    scale.put("y", 1);
                    scale.put("z", 1);

                    itemMap.put("position", position);
                    itemMap.put("scale", scale);
                    itemMap.put("rotation", rotation);
                }
                List<Map> itemCountList = new ArrayList<>();
                Map<String, Object> ItemCount = new HashMap<>();
                ItemCount.put("name", "合格");
                ItemCount.put("count", getPointChildrenCount(item, "Qualified"));
                itemCountList.add(ItemCount);

                Map<String, Object> ItemCount1 = new HashMap<>();
                ItemCount1.put("name", "不合格");
                ItemCount1.put("count", getPointChildrenCount(item, "Unqualified"));
                itemCountList.add(ItemCount1);


                Map<String, Object> ItemCount2 = new HashMap<>();
                ItemCount2.put("name", "漏检");
                ItemCount2.put("count", getPointChildrenCount(item, "Omission"));
                itemCountList.add(ItemCount2);

//        			Map<String, Object> ItemCount3 = new HashMap<>();
//        			ItemCount.put("name", "合格");
//        			ItemCount3.put("count", getPointChildrenCount(item, "Unplan"));
//        			itemCountList.add(ItemCount3);

                itemMap.put("statisticsData", itemCountList);
                map.put(item.getId() + "", itemMap);
//        		}
            });
            for (String key : map.keySet()) {
                treeList.add((Map<String, Object>) map.get(key));
            }

        }

        return treeList;
    }

    private static int getPointChildrenCount(RiskSourceTreeResponse riskSource, String status) {
        if (ObjectUtils.isEmpty(riskSource.getChildren())) {
            return 0;
        }
        int count = 0;
        if (status.equals("Qualified")) {
            count += riskSource.getQualified();
        } else if (status.equals("Unqualified")) {
            count += riskSource.getUnqualified();
        } else if (status.equals("Omission")) {
            count += riskSource.getOmission();
        } else if (status.equals("Unplan")) {
            count += riskSource.getUnplan();
        }
        for (RiskSourceTreeResponse action : riskSource.getChildren()) {
            if (ObjectUtils.isEmpty(action.getPosition3d())) {
                continue;
            }
            count = count + getPointChildrenCount(action, status);
            if (status.equals("Qualified")) {
                count += action.getQualified();
            } else if (status.equals("Unqualified")) {
                count += action.getUnqualified();
            } else if (status.equals("Omission")) {
                count += action.getOmission();
            } else if (status.equals("Unplan")) {
                count += action.getUnplan();
            }
        }

        return count;
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    // @Authorization(ingore = true)
    @ApiOperation(httpMethod = "GET", value = "统计级别为1的风险点下面设备统计", notes = "统计级别为1的风险点下面设备统计")
    @RequestMapping(value = "/equipStatistics/{type}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse equipStatistics(@PathVariable(value = "type", required = true) String[] type) throws Exception {
        List<RiskSourceTreeResponse> riskSources = riskSourceService.findRiskSourceEquipStatistics(type);
        List<RiskSourceTreeResponse> treeRiskSources = getRiskSourcesEquipTree(riskSources);
        return CommonResponseUtil.success(riskSourceEquipStatistics(treeRiskSources, true, 0));
    }

    private static List<RiskSourceTreeResponse> getRiskSourcesEquipTree(List<RiskSourceTreeResponse> list) {
        List<RiskSourceTreeResponse> treeList = new ArrayList<RiskSourceTreeResponse>();
        for (RiskSourceTreeResponse tree : list) {
            if (tree.getParentId() != null && tree.getParentId() == 1) {
                treeList.add(tree);
            }
            for (RiskSourceTreeResponse treeNode : list) {
                if (treeNode.getParentId().longValue() == tree.getId()) {
                    if (tree.getChildren() == null) {
                        tree.setChildren(new ArrayList<RiskSourceTreeResponse>());
                    }
                    tree.getChildren().add(treeNode);
                }
            }
        }
        return treeList;
    }


    private Object riskSourceEquipStatistics(List<RiskSourceTreeResponse> list, Boolean isLevel, int level) {
        List<Map<String, Object>> treeList = new ArrayList<Map<String, Object>>();
        if (!ObjectUtils.isEmpty(list)) {
            Map<String, Object> map = new HashMap<>();

//        	List<RiskSourceTreeResponse> firstChildrens = list.get(0).getChildren();
            list.forEach(item -> {
//        		if (!ObjectUtils.isEmpty(item.getPosition3d())) {
                Map<String, Object> itemMap = (Map<String, Object>) map.get(item.getId());
                if (ObjectUtils.isEmpty(itemMap)) {
                    itemMap = new HashMap<>();
                    itemMap.put("id", item.getId());
                    itemMap.put("key", "key" + item.getId());
                    itemMap.put("name", item.getName());
                    if (isLevel) {
                        itemMap.put("level", level);
                    } else {
                        itemMap.put("level", item.getLevel());
                    }

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

                    if (!ObjectUtils.isEmpty(item.getPosition3d())) {
                        String[] pos = item.getPosition3d().split(",");
                        position.put("x", pos[0]);
                        position.put("y", pos[1]);
                        position.put("z", pos[2]);
                    }
                    Map<String, Object> rotation = new HashMap<>();
                    rotation.put("x", 0);
                    rotation.put("y", 0);
                    rotation.put("z", 0);
                    Map<String, Object> scale = new HashMap<>();
                    scale.put("x", 1);
                    scale.put("y", 1);
                    scale.put("z", 1);

                    itemMap.put("position", position);
                    itemMap.put("scale", scale);
                    itemMap.put("rotation", rotation);
                }
                List<Map> itemCountList = new ArrayList<>();
                Map<String, Object> ItemCount = new HashMap<>();
                itemCountList.add(ItemCount);
                ItemCount.put("count", getRiskSourceEquipChildrenCount(item));
                itemMap.put("statisticsData", itemCountList);
                map.put(item.getId() + "", itemMap);
//        		}
            });
            for (String key : map.keySet()) {
                treeList.add((Map<String, Object>) map.get(key));
            }

        }

        return treeList;
    }


    private static int getRiskSourceEquipChildrenCount(RiskSourceTreeResponse item) {
        if (ObjectUtils.isEmpty(item.getChildren())) {
            return item.getCount();
        }
        int count = item.getCount();
        for (RiskSourceTreeResponse action : item.getChildren()) {
            count = count + getRiskSourceChildrenCount(action, null);
            count += action.getCount();
        }

        return count;
    }


    private static List<Map<String, Object>> riskSourceStatistics(List<RiskSourceTreeResponse> list) {
        List<Map<String, Object>> treeList = new ArrayList<Map<String, Object>>();
        if (!ObjectUtils.isEmpty(list)) {
            Map<String, Object> map = new HashMap<>();

            List<RiskSourceTreeResponse> firstChildrens = list.get(0).getChildren();
            firstChildrens.forEach(item -> {
//        		if (!ObjectUtils.isEmpty(item.getPosition3d())) {
                Map<String, Object> itemMap = (Map<String, Object>) map.get(item.getId());
                if (ObjectUtils.isEmpty(itemMap)) {
                    itemMap = new HashMap<>();
                    itemMap.put("id", item.getId());
                    itemMap.put("key", "key" + item.getId());
                    itemMap.put("name", item.getName());
                    itemMap.put("level", item.getLevel());
                    Map<String, Object> position = new HashMap<>();

                    if (!ObjectUtils.isEmpty(item.getPosition3d())) {
                        String[] pos = item.getPosition3d().split(",");
                        position.put("x", pos[0]);
                        position.put("y", pos[1]);
                        position.put("z", pos[2]);
                    }
                    Map<String, Object> rotation = new HashMap<>();
                    rotation.put("x", 0);
                    rotation.put("y", 0);
                    rotation.put("z", 0);
                    Map<String, Object> scale = new HashMap<>();
                    scale.put("x", 1);
                    scale.put("y", 1);
                    scale.put("z", 1);

                    itemMap.put("position", position);
                    itemMap.put("scale", scale);
                    itemMap.put("rotation", rotation);
                }
                List<Map> itemCountList = new ArrayList<>();
                Map<String, Object> ItemCount = new HashMap<>();
                ItemCount.put("name", "告警");
                ItemCount.put("count", getRiskSourceChildrenCount(item, "ANOMALY"));
                itemCountList.add(ItemCount);
                Map<String, Object> ItemCount1 = new HashMap<>();
                ItemCount1.put("name", "风险点");
                ItemCount1.put("count", getRiskSourceChildrenCount(item, null));
                itemCountList.add(ItemCount1);
                itemMap.put("statisticsData", itemCountList);
                map.put(item.getId() + "", itemMap);
//        		}
            });
            for (String key : map.keySet()) {
                treeList.add((Map<String, Object>) map.get(key));
            }

        }

        return treeList;
    }

    private static int getRiskSourceChildrenCount(RiskSourceTreeResponse riskSource, String status) {
        if (ObjectUtils.isEmpty(riskSource.getChildren())) {
            return 0;
        }
        int count = 0;
        if ("ANOMALY".equals(status)) {
            count += (riskSource.getQualified() == null ? 0 : riskSource.getQualified());
        } else {
            count += (riskSource.getUnplan() == null ? 0 : riskSource.getUnplan());
        }
        for (RiskSourceTreeResponse action : riskSource.getChildren()) {
            if (ObjectUtils.isEmpty(action.getPosition3d())) {
                continue;
            }
            count = count + getRiskSourceChildrenCount(action, status);
            if (status != null) {
                if (status.equals(action.getStatus())) {
                    count++;
                }
            } else {
                count++;
            }
        }

        return count;
    }

    private static List<RiskSourceTreeResponse> getRiskSourcesTree(List<RiskSourceTreeResponse> list) {
        List<RiskSourceTreeResponse> treeList = new ArrayList<RiskSourceTreeResponse>();
        for (RiskSourceTreeResponse tree : list) {
            if (tree.getParentId() != null && tree.getParentId() == 0) {
                treeList.add(tree);
            }
            for (RiskSourceTreeResponse treeNode : list) {
                if (treeNode.getParentId().longValue() == tree.getId()) {
                    if (tree.getChildren() == null) {
                        tree.setChildren(new ArrayList<>());
                    }
                    tree.getChildren().add(treeNode);
                }
            }
        }
        return treeList;
    }

    private static List<RiskSourceTreeResponse> getRegionTree(List<RiskSourceTreeResponse> list) {
        List<RiskSourceTreeResponse> treeList = new ArrayList<RiskSourceTreeResponse>();
        for (RiskSourceTreeResponse tree : list) {
            if (tree.getParentId() != null && tree.getParentId() == 0) {
                treeList.add(tree);
            }
            for (RiskSourceTreeResponse treeNode : list) {
                if (treeNode.getParentId().longValue() == tree.getId() && "TRUE".equals(treeNode.getIsRegion())) {
                    if (tree.getChildren() == null) {
                        tree.setChildren(new ArrayList<>());
                    }
                    tree.getChildren().add(treeNode);
                }
            }
        }
        return treeList;
    }

    /**
     * 根据风险点查询关联巡检点
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "根据风险点查询关联巡检点", notes = "根据风险点查询关联巡检点")
    @GetMapping(value = "/getBindPoints", produces = "application/json;charset=UTF-8")
    public CommonResponse listFmeaPointInputitem(@ApiParam(value = "fmeaId", required = true) @RequestParam Long fmeaId,
                                                 @ApiParam(value = "分页参数", required = true) @RequestParam Integer pageNumber,
                                                 @ApiParam(value = "分页参数", required = true) @RequestParam Integer pageSize) {
        try {
            Page<Map<String, Object>> list = riskSourceService.listFmeaPointInputitem(getToken(), getProduct(), getAppKey(), fmeaId, pageNumber, pageSize);
            return CommonResponseUtil.success(list);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure("查询巡检点信息失败");
        }
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询指定风险点绑定关系", notes = "查询指定风险点绑定关系")
    @RequestMapping(value = "/{fmeaId}/fireequiment/relations", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryBoundRelation(@PathVariable Long fmeaId,
                                             @RequestParam int pageNumber,
                                             @RequestParam int pageSize) {
        return CommonResponseUtil.success(riskSourceService.listFeamEquipmentPoint(fmeaId, pageNumber, pageSize));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "绑定巡检点检查项", notes = "绑定巡检点检查项")
    @PostMapping(value = "/bindFmea/pointInputitem")
    public CommonResponse bindFmeaPointInputitem(@RequestBody FmeaBindParam pointInputitems) {
        return CommonResponseUtil.success(riskSourceService.bindPointInputitem(pointInputitems));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "绑定消防设备指标", notes = "绑定消防设备指标")
    @PostMapping(value = "/bingFmea/equimentPoint")
    public CommonResponse bindFmeaEquimentPoint(@RequestBody FmeaBindParam fmeaBindParam) {
        return CommonResponseUtil.success(riskSourceService.bindFireEquiment(fmeaBindParam));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询绑定关系设备", notes = "查询绑定关系包含已绑定和未绑定")
    @RequestMapping(value = "/fireequiment/relation/all", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryRelationWithNoBound(
            @RequestParam String equimentId,
            @RequestParam(value = "fname", required = false) String fname,
            @RequestParam int pageNumber,
            @RequestParam int pageSize) throws Exception {

        CommonPageable commonPageable = new CommonPageable(pageNumber, pageSize);
        fname = StringUtils.trimToNull(fname);
        return CommonResponseUtil.success(riskSourceService.queryEquimentRelation(commonPageable, equimentId, fname));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "查询设备指标", notes = "查询设备指标")
    @GetMapping(value = "/listEquipmentPointById")
    public CommonResponse listEquipmentPointById(@RequestParam Long fmeaId,
                                                 @RequestParam Long importantEquipId,
                                                 @RequestParam Long equimentId,
                                                 @RequestParam(required = false) String equipmentPointName) {
        return CommonResponseUtil.success(riskSourceService.listEquipmentPointById(fmeaId, importantEquipId, equimentId, equipmentPointName));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "PUT", value = "上传消防设备数据", notes = "上传消防设备数据")
    @RequestMapping(value = "/data/fireqeuiment", produces = "application/json;charset=UTF-8", method = RequestMethod.PUT)
    public CommonResponse postFireEqumentData(@RequestBody FireEquimentDataRo deviceData) throws Exception {
        return CommonResponseUtil.success(riskSourceService.processFireEqumtData(deviceData));
    }

    @ApiOperation(httpMethod = "POST", value = "上传消防设备数据", notes = "上传消防设备数据")
    @RequestMapping(value = "/data/fireqeuiment/soe", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse postFireEqumentData(@RequestBody AlarmParam alarm) throws Exception {
        log.debug("pointCode=soe=" + alarm.getPointCode() + " InformationAddress=soe=" + alarm.getInformationAddress());
        riskSourceService.processFireEqumtData(alarm);
        return CommonResponseUtil.success();
    }


    @ApiOperation(httpMethod = "GET", value = "重点设备启动预案", notes = "重点设备启动预案")
    @RequestMapping(value = "/startEquipReserve", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public ResponseModel startEquipReserve(@RequestParam Long id, @RequestParam String typeCode) {

        ReserveEnum reserveEnum = riskSourceService.startEquipReserve(id, typeCode);
        Integer status = reserveEnum.getStatus();
        String text = reserveEnum.getText();
        if (status == 1) {
            return CommonResponseUtil2.success(text);
        } else {
            return CommonResponseUtil2.failure(text);
        }
    }


     @TycloudOperation(ApiLevel = UserType.AGENCY)
//  @Authorization(ingore = true)
    @ApiOperation(httpMethod = "PUT", value = "上传巡检数据", notes = "上传巡检数据")
    @RequestMapping(value = "/data/patroldata", produces = "application/json;charset=UTF-8", method = RequestMethod.PUT)
    public CommonResponse postPatrolData(@RequestBody ProtalDataRo protalData) throws Exception {
        log.info("上传巡检数据" + JSONObject.toJSONString(protalData));
        ReginParams reginParams = getSelectedOrgInfo();
        String compCode = getOrgCode(reginParams);
        riskSourceService.processProtalData(getToken(), getProduct(), getAppKey(), protalData, compCode);
        return CommonResponseUtil.success();
    }

    @ApiOperation(httpMethod = "PUT", value = "隐患治理更新State、rpn值", notes = "隐患治理更新State、rpn值")
    @RequestMapping(value = "/data/danger/state", produces = "application/json;charset=UTF-8", method = RequestMethod.PUT)
    public CommonResponse processProtalDataFromDanger(@RequestBody DangerResultBo data) throws Exception {
        log.info("隐患治理完成更新rpn值" + JSONObject.toJSONString(data));
        riskSourceService.processProtalDataFromDanger(data);
        return CommonResponseUtil.success();
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "PUT", value = "上传巡检任务数据", notes = "上传巡检任务数据")
    @RequestMapping(value = "/data/task", produces = "application/json;charset=UTF-8", method = RequestMethod.PUT)
    public CommonResponse postTaskData(@RequestBody ProtalDataRo taskData) throws Exception {

        return CommonResponseUtil.success(riskSourceService.processTaskData(taskData));
    }

    /**
     * 查询风险点明细
     *
     * @param id
     * @return
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "查询风险点明细", notes = "查询风险点明细")
    @GetMapping(value = "/detailById/{id}", produces = "application/json;charset=UTF-8")
    public CommonResponse queryRiskSourceDetailById(@PathVariable Long id) {
        RiskSourceTreeResponse det = riskSourceService.queryRiskSourceDetailById(id);
        return CommonResponseUtil.success(det);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "风险预警详情", notes = "风险预警详情")
    @GetMapping(value = "/warning/detail", produces = "application/json;charset=UTF-8")
    public CommonResponse earlyWarning(@RequestParam String riskSourceId) {
        Map map = riskSourceService.earlyWarning(Long.valueOf(riskSourceId));
        return CommonResponseUtil.success(map);
    }

    /**
     * 获取厂区下所有区域的风险点的rpn值
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取厂区下所有区域的风险点的rpn值", notes = "获取厂区下所有区域的风险点的rpn值")
    @RequestMapping(value = "/queryRiskAreaRpn", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryRiskAreaRpn() {

        return CommonResponseUtil.success(riskSourceService.queryRiskAreaRpn());
    }


    /**
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "设置预案节点自动执行", notes = "设置预案节点自动执行")
    @RequestMapping(value = "/contingency/setup", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public CommonResponse queryRiskSourceSecondLevel(@RequestBody ContingencyDeviceStatus contingencyDeviceStatus) {
        riskSourceService.queryContingencyDeviceStatus(contingencyDeviceStatus);
        return CommonResponseUtil.success();
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "初始化預案水資源", notes = "初始化預案水資源")
    @RequestMapping(value = "/contingency/water", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryContingencyWater() {
        return CommonResponseUtil.success(riskSourceService.queryContingencyWater());
    }

    /**
     * 获取危险因素树二级节点
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取危险因素树二级节点", notes = "获取危险因素树二级节点")
    @RequestMapping(value = "/riskSourceSecondLevel", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryRiskSourceSecondLevel() {
        ReginParams reginParams = getSelectedOrgInfo();
        String compCode = getOrgCode(reginParams);
        return CommonResponseUtil.success(riskSourceService.queryRiskSourceSecondLevel(compCode));
    }

    /**
     * 获取巡检点FMEA
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取危险因素树二级节点", notes = "获取危险因素树二级节点")
    @RequestMapping(value = "/queryFmea/point/{pointId}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public CommonResponse queryFmeaByPointId(@PathVariable Long pointId) {
        return CommonResponseUtil.success(riskSourceService.queryFmeaByPointId(pointId));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "同步风险区域",notes = "创建或者更新，对站调用")
    @PostMapping("/syn/region")
    public CommonResponse synRegion(@RequestBody RiskSourceSynBo synBo){
        ReginParams reginParams = getSelectedOrgInfo();
        String compCode = getOrgCode(reginParams);
        return CommonResponseUtil.success(riskSourceService.synRegion(getUserId(),compCode,synBo));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "删除建筑与风险区域关系",notes = "对站调用")
    @PutMapping("/remove/bind")
    public CommonResponse removeBind(@RequestParam Long instanceId){
        return CommonResponseUtil.success(riskSourceService.removeBind(instanceId));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "物理区域修改同步到风险区域",notes = "修改物理区域")
    @PostMapping("/syn/updateAreaSyn")
    public CommonResponse updateAreaSyn(@RequestBody RiskSourceSynBo synBo){
        ReginParams reginParams = getSelectedOrgInfo();
        String compCode = getOrgCode(reginParams);
        return CommonResponseUtil.success(riskSourceService.updateAreaSyn(getUserId(),compCode,synBo));
    }
}
