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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.sun.xml.bind.v2.TODO;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.rule.action.MessageAction;
import com.yeejoin.amos.boot.biz.common.dto.PermissionModelDto;
import com.yeejoin.amos.boot.biz.common.enums.HomePageEnum;
import com.yeejoin.amos.boot.biz.common.service.IDataDictionaryService;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.WordConverterUtils;
import com.yeejoin.amos.boot.module.command.api.dto.CarTaskDto;
import com.yeejoin.amos.boot.module.command.api.dto.SeismometeorologyDto;
import com.yeejoin.amos.boot.module.command.api.entity.Gps;
import com.yeejoin.amos.boot.module.command.biz.service.impl.RemoteSecurityService;
import com.yeejoin.amos.boot.module.command.biz.utils.PositionUtil;
import com.yeejoin.amos.boot.module.common.api.dto.*;
import com.yeejoin.amos.boot.module.common.api.entity.FireTeam;
import com.yeejoin.amos.boot.module.common.api.entity.Firefighters;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.api.feign.EquipFeignClient;
import com.yeejoin.amos.boot.module.common.api.feign.IotFeignClient;
import com.yeejoin.amos.boot.module.common.api.feign.VideoFeignClient;
import com.yeejoin.amos.boot.module.common.api.mapper.OrgUsrMapper;
import com.yeejoin.amos.boot.module.common.api.service.*;
import com.yeejoin.amos.boot.module.jcs.api.dto.*;
import com.yeejoin.amos.boot.module.jcs.api.entity.*;
import com.yeejoin.amos.boot.module.jcs.api.enums.AlertStageEnums;
import com.yeejoin.amos.boot.module.jcs.api.enums.FireCarStatusEnum;
import com.yeejoin.amos.boot.module.jcs.api.mapper.AirportStandMapper;
import com.yeejoin.amos.boot.module.jcs.api.mapper.PowerTransferCompanyResourcesMapper;
import com.yeejoin.amos.boot.module.jcs.api.mapper.PowerTransferMapper;
import com.yeejoin.amos.boot.module.jcs.api.service.*;
import com.yeejoin.amos.component.rule.config.RuleConfig;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.MessageModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.exception.BaseException;
import org.typroject.tyboot.core.foundation.utils.DateUtil;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
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.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;

/**
 * *指挥资源Api
 *
 * <PRE>
 * author tw
 * date 2021/7/15
 * </PRE>
 */
@RestController
@Api(tags = "指挥资源Api")
@RequestMapping(value = "/command")
public class CommandController extends BaseController {

    @Autowired
    IAlertCalledService iAlertCalledService;
    @Autowired
    IFireStationService iFireStationService;
    @Autowired
    IFireTeamService iFireTeamService;
    @Autowired
    IWaterResourceService iWaterResourceService;
    @Autowired
    IOrgUsrService iOrgUsrService;
    @Autowired
    ILinkageUnitService iLinkageUnitService;
    @Autowired
    IAlertSubmittedService alertSubmittedService;
    @Autowired
    IDataDictionaryService dataDictionaryService;
    @Autowired
    IFireChemicalService fireChemicalService;
    @Autowired
    IDutyCarService dutyCarService;
    @Autowired
    IFireExpertsService fireExpertsService;
    @Autowired
    IFirefightersService firefightersService;
    @Autowired
    private IAlertFormValueService iAlertFormValueService;
    @Autowired
    private IAircraftService aircraftService;
    @Autowired
    IPowerTransferService powerTransferService;
    @Autowired
    RemoteSecurityService remoteSecurityService;
    @Autowired
    private IAircraftService ircraftService;
    @Autowired
    IAlertFormValueService alertFormValueService;
    // 文件读取参数
    @Value("${file.url}")
    private String readUrl;
    @Autowired
    EquipFeignClient equipFeignClient;
    @Autowired
    PowerTransferMapper powerTransferMapper;
    @Autowired
    VideoFeignClient videoFeignClient;
    @Autowired
    IKeySiteService keySiteService;
    @Autowired
    EquipFeignClient equipFeignService;
    @Autowired
    IPowerTransferCompanyService powerTransferCompanyService;

    @Autowired
    IPowerTransferCompanyResourcesService powerTransferCompanyResourcesService;

    @Autowired
    PowerTransferCompanyResourcesMapper powerTransferCompanyResourcesMapper;

    @Autowired
    ISourceFileService sourceFileService;

    @Value("${video.url}")
    private String videoUrl;

    @Autowired
    IDutyPersonService iDutyPersonService;

    @Autowired
    IDutyCarService iDutyCarService;
    @Autowired
    IotFeignClient iotFeignClient;

    @Autowired
    IUserCarService userCarService;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    IESCarService esCarService;

    @Autowired
    private EmqKeeper emqKeeper;

    @Autowired
    AirportStandMapper airportStandMapper;
    private static final String JW = "mechinePosition";
    private static final String KEYSITE = "keySiteExcle";
    private static final String VIDEO = "video";
    private static final String OPENURL = "openUrl";
    private static final String BUILDDATE = "buildDate";
    private static final String FILEPATH = "filePath";
    private static final String CARSTATE = "carState";
    private static final String USERNAME = "userName";
    public static final Logger log = LoggerFactory.getLogger(CommandController.class);


    private OrgUsrMapper orgUsrMapper;

    @Value("${mqtt.topic.command.car.jw}")
    private String topic;

    /**
     * 警情列表
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "JQ/list")
    @ApiOperation(httpMethod = "GET", value = "警情列表查询", notes = "警情列表查询")
    public ResponseModel<Object> listPage(RequestData par) {
        par.setStatus(0);
        List<AlertCalledZhDto> list = iAlertCalledService.alertCalledListByAlertStatus(null, null, par);
        return ResponseHelper.buildResponse(list);
    }



    /**
     * 分页警情列表
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "history/list")
    @ApiOperation(httpMethod = "GET", value = "警情列表查询", notes = "警情列表查询")
    public ResponseModel<Page<AlertCalledZhDto>> listhistoryPage(Integer pageNum, Integer pageSize, RequestData par) {


        if (par.getStatus() != null && par.getStatus() == -1) {

            AgencyUserModel agencyUserModel = getUserInfo();
            Long id = null;
            //获取用户已绑定车辆id、
            UserCar userCar = userCarService.selectByAmosUserId(Long.valueOf(agencyUserModel.getUserId()));
            //获取正在进行的灾情null
            if (userCar != null) {
                AlertCalled alertCalled = powerTransferCompanyResourcesService.getByPowerTransferCompanyResourId(userCar.getCarId());
                if (alertCalled != null) {
                    par.setAlertId(alertCalled.getSequenceNbr());
                    par.setStatus(null);
                } else {
                    return ResponseHelper.buildResponse(null);
                }

            } else {
                return ResponseHelper.buildResponse(null);
            }
        } else {
            if (par.getStatus() == null) {
                par.setStatus(1);
            }
        }


        if (null == pageNum || null == pageSize) {
            pageNum = 1;
            pageSize = Integer.MAX_VALUE;
        } else {
            pageNum = (pageNum - 1) * pageSize;
        }
        List<AlertCalledZhDto> list = iAlertCalledService.alertCalledListByAlertStatus(pageNum, pageSize, par);
        Page<AlertCalledZhDto> pageBean = new Page<>(pageNum, pageSize);
        Integer num = iAlertCalledService.alertCalledListByAlertStatusCount(par);
        pageBean.setRecords(list);
        pageBean.setTotal(num);
        return ResponseHelper.buildResponse(pageBean);
    }

    /**
     * 120警情列表
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "JQ/listBy120")
    @ApiOperation(httpMethod = "GET", value = "警情列表查询", notes = "警情列表查询")
    public ResponseModel<Object> listPageByAid(RequestData par) {
        par.setStatus(0);
        List<AlertCalledZhDto> list = iAlertCalledService.alertCalledListByAlertStatusByAid(null, null, par);
        return ResponseHelper.buildResponse(list);
    }

    /**
     * 分页警情列表
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "history/listBy120")
    @ApiOperation(httpMethod = "GET", value = "警情列表查询", notes = "警情列表查询")
    public ResponseModel<Page<AlertCalledZhDto>> listhistoryPageByAid(Integer pageNum, Integer pageSize, RequestData par) {


        if (par.getStatus() != null && par.getStatus() == -1) {

            AgencyUserModel agencyUserModel = getUserInfo();
            Long id = null;
            //获取用户已绑定车辆id、
            UserCar userCar = userCarService.selectByAmosUserId(Long.valueOf(agencyUserModel.getUserId()));
            //获取正在进行的灾情null
            if (userCar != null) {
                AlertCalled alertCalled = powerTransferCompanyResourcesService.getByPowerTransferCompanyResourId(userCar.getCarId());
                if (alertCalled != null) {
                    par.setAlertId(alertCalled.getSequenceNbr());
                    par.setStatus(null);
                } else {
                    return ResponseHelper.buildResponse(null);
                }

            } else {
                return ResponseHelper.buildResponse(null);
            }
        } else {
            if (par.getStatus() == null) {
                par.setStatus(1);
            }
        }


        if (null == pageNum || null == pageSize) {
            pageNum = 1;
            pageSize = Integer.MAX_VALUE;
        } else {
            pageNum = (pageNum - 1) * pageSize;
        }
        List<AlertCalledZhDto> list = iAlertCalledService.alertCalledListByAlertStatusByAid(pageNum, pageSize, par);
        Page<AlertCalledZhDto> pageBean = new Page<>(pageNum, pageSize);
        Integer num = iAlertCalledService.alertCalledListByAlertStatusCountByAid(par);
        pageBean.setRecords(list);
        pageBean.setTotal(num);
        return ResponseHelper.buildResponse(pageBean);
    }


    /**
     * 保卫目标分页查询
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "ZDDW/list")
    @ApiOperation(httpMethod = "GET", value = "保卫目标列表分页查询", notes = "保卫目标列表分页查询")
    public ResponseModel<IPage<CompanyDto>> listPageZDDW(Integer pageNum, Integer pageSize, RequestData par) {
        Page<CompanyDto> pageBean = new Page<>(pageNum, pageSize);
        List<CompanyDto> list = iOrgUsrService.listContractDto(pageNum, pageSize, par);
        Integer num = iOrgUsrService.listContractDtoCount(par);
        pageBean.setRecords(list);
        pageBean.setTotal(num);
        return ResponseHelper.buildResponse(pageBean);
    }

    /**
     * * @param null
     *
     * @return <PRE>
     * author tw
     * date 2021/7/21
     * </PRE>
     * 保卫目标详情
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/ZDDW", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "保卫目标详情", notes = "保卫目标详情")
    public ResponseModel<OrgUsrFormDto> selectZDDWById(Long id) throws Exception {
        OrgUsrFormDto orgUsrFormDto = iOrgUsrService.selectCompanyById(id);
        return ResponseHelper.buildResponse(orgUsrFormDto);
    }


    /**
     * 微型消防站列表分页查询
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "WX/list")
    @ApiOperation(httpMethod = "GET", value = "微型消防站列表分页查询", notes = "微型消防站列表分页查询")
    public ResponseModel<IPage<FireStationzhDto>> listPageWx(Integer pageNum, Integer pageSize, RequestData par) {
        Page<FireStationzhDto> pageBean = new Page<>(pageNum, pageSize);
        List<FireStationzhDto> list = iFireStationService.getStationList(pageNum, pageSize, par);
        Integer num = iFireStationService.getStationListCount(par);
        pageBean.setRecords(list);
        pageBean.setTotal(num);
        return ResponseHelper.buildResponse(pageBean);
    }

    /**
     * 水源列表分页查询
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "SY500/list")
    @ApiOperation(httpMethod = "GET", value = "500水源列表分页查询", notes = "500水源列表分页查询")
    public ResponseModel<IPage<WaterResourceZhDto>> listPageSY500(Integer pageNum, Integer pageSize, RequestData par) {

        par.setDistance(500D);

        Page<WaterResourceZhDto> pageBean = new Page<>(pageNum, pageSize);
        List<WaterResourceZhDto> list = iWaterResourceService.getWaterResourceList(pageNum, pageSize, par);
        Integer num = iWaterResourceService.getWaterResourceListCount(par);
        pageBean.setRecords(list);
        pageBean.setTotal(num);
        return ResponseHelper.buildResponse(pageBean);
    }


    /**
     * 水源列表分页查询
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "video/listNew")
    @ApiOperation(httpMethod = "GET", value = " 视频分页查询88", notes = "视频分页查询88")
    public ResponseModel<Object> getVideoNew(Integer pageNum, Integer pageSize, RequestData par) {
        par.setDistance(500D);
        ResponseModel<Map<String, Object>> result = null;
        if (par.getAlertId() != null) {

            AlertCalled alertCalled = iAlertCalledService.getAlertCalledById(par.getAlertId());
            List<AlertFormValue> list = alertFormValueService.getzqlist(alertCalled.getSequenceNbr());
            switch (alertCalled.getAlertTypeCode()){
                case "230":
                case "237":
                case "238":
                    for (AlertFormValue alertFormValue : list) {
                        if (alertFormValue.getFieldCode().equals(JW) && !StringUtils.isEmpty(alertFormValue.getFieldValue())){

                            QueryWrapper<AirportStand> queryWrapper = new QueryWrapper<>();
                            queryWrapper.eq("stand_code",alertFormValue.getFieldValue());
                            AirportStand airportStand = airportStandMapper.selectOne(queryWrapper);

                            par.setLatitude(Double.valueOf(airportStand.getLatitude()));
                            par.setLongitude(Double.valueOf(airportStand.getLongitude()));
                        }

                    }
                    par.setLatitudeTwo(alertCalled.getCoordinateX());
                    par.setLongitudeTwo(alertCalled.getCoordinateY());
                    break;
                case "229":
                    if (alertCalled.getAlertSourceCode().equals("1326")){
                        result =   this.getDetailsById(Long.valueOf(alertCalled.getRelationId()),null,null,null);
                        par.setLatitudeTwo(alertCalled.getCoordinateX());
                        par.setLongitudeTwo(alertCalled.getCoordinateY());
                    }else {
                    for (AlertFormValue alertFormValue : list) {
                        if (alertFormValue.getFieldCode().equals(KEYSITE) && !StringUtils.isEmpty(alertFormValue.getFieldValueCode())) {
                            KeySiteDto keySiteDto = keySiteService.getSequenceNbr(Long.parseLong(alertFormValue.getFieldValueCode()));
                            par.setBuildingId( keySiteDto.getBuildingId().toString()) ;
                        }
                    }
                    }
                break;
                case "235":
                    par.setLatitude(alertCalled.getCoordinateX());
                    par.setLongitude(alertCalled.getCoordinateY());
                    break;
                default:
                    break;
            }
        }
        ResponseModel<Page<Map<String, Object>>> data = null;
        if (ValidationUtil.isEmpty(par.getLatitudeTwo()) ){
            data =  equipFeignClient.getVideopagList( String.valueOf((pageNum - 1) * pageSize), pageSize.toString(),par.getBuildingId(),par.getCode(),par.getEquipmentName(),par.getBizOrgCode(),par.getType());
        }else {
            data = equipFeignClient.pageVideoByAlertType( pageNum, pageSize, par);
        }


        if (result != null&&!ObjectUtils.isEmpty(result)&&!ObjectUtils.isEmpty(result.getResult().get(VIDEO))){
            List<Map<String, Object>> records = result != null ? (List<Map<String, Object>>) result.getResult().get(VIDEO) : null;
            Page<Map<String, Object>> page = data.getResult();
            records.addAll(data.getResult().getRecords());
            page.setRecords(records);
            data.setResult(page);
        }

        Page<Map<String, Object>> pag = data != null ? data.getResult() : null;
        List<Map<String, Object>> records = pag != null ? pag.getRecords() : null;
        if (records != null && records.size() > 0) {
            for (Map<String, Object> rec : records) {
                ResponseModel<String> da = videoFeignClient.videoUrlByIndexCode(rec.get("code") + "");
                String url = da != null ? da.getResult().substring(da.getResult().indexOf(OPENURL)) : null;
                rec.put("url", url);
            }
            pag.setRecords(records);
        }
        return ResponseHelper.buildResponse(pag);
    }



    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "video/list")
    @ApiOperation(httpMethod = "GET", value = " 视频分页查询88", notes = "视频分页查询88")
    public ResponseModel<Object> getVideo(Integer pageNum, Integer pageSize, RequestData par) {
        if (par.getAlertId() != null) {
            AlertCalled alertCalled = iAlertCalledService.getAlertCalledById(par.getAlertId());
            par.setLatitude(alertCalled.getCoordinateX());
            par.setLongitude(alertCalled.getCoordinateY());
        }
        ResponseModel<Page<Map<String, Object>>> data = equipFeignClient.pageVideo(pageNum == 0 ? 1 : pageNum, pageSize, par.getLongitude(), par.getLatitude(), par.getDistance());
        Page<Map<String, Object>> pag = data != null ? data.getResult() : null;
        List<Map<String, Object>> records = pag != null ? pag.getRecords() : null;
        if (records != null && records.size() > 0) {
            for (Map<String, Object> rec: records) {
                ResponseModel<String> da = videoFeignClient.videoUrlByIndexCode(rec.get("code") + "");
                String url = da != null ? da.getResult().substring(da.getResult().indexOf(OPENURL)) : null;
                rec.put("url", url);
            }
            pag.setRecords(records);
        }
        return ResponseHelper.buildResponse(pag);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/video/page", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "分页获取视频", notes = "分页获取视频")
    public ResponseModel<Object> getVideopage(String current,
                                              String size,
                                              String equipmentName,
                                              String code,
                                              String buildingId,
                                              String bizOrgCode
    ) {

        ResponseModel<Page<Map<String, Object>>> data = equipFeignClient.getVideopag(current, size, buildingId, code, equipmentName, bizOrgCode,null);
        Page<Map<String, Object>> pag = data != null ? data.getResult() : null;
        List<Map<String, Object>> records = pag != null ? pag.getRecords() : null;
        if (records != null && records.size() > 0) {
            for (Map<String, Object> rec : records) {
                ResponseModel<String> da = videoFeignClient.videoUrlByIndexCode(rec.get("code") + "");
                String url = da != null ? da.getResult().substring(da.getResult().indexOf(OPENURL)) : null;
                rec.put("url", url);
            }
            pag.setRecords(records);
        }
        return ResponseHelper.buildResponse(pag);
    }


    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "分页查询视图下的视频列表")
    @RequestMapping(value = "monitorView/video/page", method = RequestMethod.GET)
    public ResponseModel<Page<Map<String, Object>>> queryUncheckedVideoList(
            @RequestParam(value = "nodeId") Long nodeId,
            @RequestParam(value = "nodeType", required = false) String nodeType,
            @RequestParam(value = "current") int current,
            @RequestParam(value = "size") int size
    ) throws BaseException {
        ResponseModel<Page<Map<String, Object>>> data = equipFeignClient.queryVideoPage(nodeId, nodeType, current, size);
        Page<Map<String, Object>> pag = data != null ? data.getResult() : null;
        List<Map<String, Object>> records = pag != null ? pag.getRecords() : null;
        if (records != null && records.size() > 0) {
            for (Map<String, Object> rec : records) {
                ResponseModel<String> da = videoFeignClient.videoUrlByIndexCode(rec.get("code") + "");
                String url = da != null ? da.getResult().substring(da.getResult().indexOf(OPENURL)) : null;
                rec.put("url", url);
            }
            pag.setRecords(records);
        }
        return ResponseHelper.buildResponse(pag);
    }

    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "confirmAlarm/getDetailsById")
    @ApiOperation(value = "根据id，type查询确警页面相关数据")
    public ResponseModel<Map<String, Object>> getDetailsById(@RequestParam Long alamId, @RequestParam Long equipId, @RequestParam String type, @RequestParam String area) {
        ResponseModel<Map<String, Object>> response = equipFeignClient.getDetailsById(alamId, equipId, type, area);
        Map<String, Object> data = response.getResult();
        List<Map<String, Object>> records = data != null ? (List<Map<String, Object>>) data.get(VIDEO) : null;
        if (records != null && records.size() > 0) {
            for (Map<String, Object> rec : records) {
                ResponseModel<String> da = videoFeignClient.videoUrlByIndexCode(rec.get("code") + "");
                String url = da != null ? da.getResult().substring(da.getResult().indexOf(OPENURL)) : null;
                rec.put("url", url);
            }
            data.put(VIDEO, records);
        }
        return ResponseHelper.buildResponse(data);
    }


    /**
     * 水源列表分页查询
     *
     * @returngetVideo
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @PostMapping(value = "video/pageList")
    @ApiOperation(httpMethod = "POST", value = " app视频分页查询88", notes = "app视频分页查询88")
    public ResponseModel<Object> pageList(@RequestBody PageDto pageDto) {
        ResponseModel<Page<VideoDto>> data = equipFeignClient.pageList(pageDto.getCurrent(),
                pageDto.getSize(),
                pageDto.getCode() == null ? "" : pageDto.getCode(),
                pageDto.getName() == null ? "" : pageDto.getName(),
                pageDto.getTypeCode() == null ? "" : pageDto.getTypeCode());
        Page<VideoDto> pag = data != null ? data.getResult() : null;
        List<VideoDto> records = pag != null ? pag.getRecords() : null;
        if (records != null && records.size() > 0) {
            for (VideoDto rec : records) {
                ResponseModel<String> da = videoFeignClient.videoUrlByIndexCode(rec.getCode());
                String url = da != null ? da.getResult() : null;
                rec.setUrl(url);
            }
            pag.setRecords(records);
        }
        return ResponseHelper.buildResponse(pag);
    }


    /**
     * 水源列表分页查询
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "video/{id}")
    @ApiOperation(httpMethod = "GET", value = " 视频详情88", notes = "视频详情88")
    public ResponseModel<Object> getVideoByid(@PathVariable Long id) {
        ResponseModel<Map<String, Object>> data = equipFeignClient.getByid(id);
        Map<String, Object> records = data != null ? data.getResult() : null;
        if (records != null && records.size() > 0) {
            ResponseModel<String> da = videoFeignClient.videoUrlByIndexCode(records.get("code") + "");
            String url = da != null ? da.getResult().substring(da.getResult().indexOf(OPENURL)) : null;
            records.put("url", url);
            data.setResult(records);
        }

        return ResponseHelper.buildResponse(data != null ? data.getResult() : null);
    }

    /**
     * 水源列表分页查询
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "SY1000/list")
    @ApiOperation(httpMethod = "GET", value = "1000水源列表分页查询", notes = "1000水源列表分页查询")
    public ResponseModel<IPage<WaterResourceZhDto>> listPageSY1000(Integer pageNum, Integer pageSize, RequestData par) {
        par.setDistance(1000D);
        Page<WaterResourceZhDto> pageBean = new Page<>(pageNum, pageSize);
        List<WaterResourceZhDto> list = iWaterResourceService.getWaterResourceList(pageNum, pageSize, par);
        Integer num = iWaterResourceService.getWaterResourceListCount(par);
        pageBean.setRecords(list);
        pageBean.setTotal(num);
        return ResponseHelper.buildResponse(pageBean);
    }



    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/seismometeorology120", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "跑马灯", notes = "跑马灯")
    public ResponseModel<Object> seismometeorology120() throws Exception {
        RequestData requestData = new RequestData();
        requestData.setWhether24(true);
        List<AlertCalledZhDto> list = iAlertCalledService.alertCalledListByAlertStatus120(null, null, requestData);

        List<SeismometeorologyDto> li =new ArrayList<>();
        //数据组装
        for (AlertCalledZhDto alertCalledZhDto : list) {

            StringBuilder st = new StringBuilder();

            String time = DateUtil.formatDate(alertCalledZhDto.getCallTime(), "yyyy-MM-dd HH:mm:ss");

            st.append("【").append(alertCalledZhDto.getAlertType()).append("】").append(" ").append(time).append(" ").append(alertCalledZhDto.getAddress()!=null?alertCalledZhDto.getAddress():"");

            SeismometeorologyDto sto = new SeismometeorologyDto(alertCalledZhDto.getSequenceNbr(), "1", "警情通知", null, alertCalledZhDto.getCallTime(), null, st.toString());
            li.add(sto);
        }
        return ResponseHelper.buildResponse(li);
    }


    /**
     * 消防队伍列表分页查询
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "DW/list")
    @ApiOperation(httpMethod = "GET", value = "消防队伍列表分页查询", notes = "消防队伍列表分页查询")
    public ResponseModel<IPage<FireTeamZhDto>> listPage(Integer pageNum, Integer pageSize, RequestData par) {
        par.setTypeCode(AlertStageEnums.YWDD.getCode());
        Page<FireTeamZhDto> pageBean = new Page<>(pageNum, pageSize);
        List<FireTeamZhDto> list = iFireTeamService.getFireTeamList(pageNum, pageSize, par);
        Integer num = iFireTeamService.getFireTeamListCount(par);
        pageBean.setRecords(list);
        pageBean.setTotal(num);
        return ResponseHelper.buildResponse(pageBean);
    }

    /**
     * 联动力量列表分页查询
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "linkageForce/list")
    @ApiOperation(httpMethod = "GET", value = "联动力量列表分页查询", notes = "联动力量列表分页查询")
    public ResponseModel<IPage<LinkageUnitZhDto>> linkageForcelistPage(Integer pageNum, Integer pageSize, RequestData par) {
        Page<LinkageUnitZhDto> pageBean = new Page<>(pageNum, pageSize);
        List<LinkageUnitZhDto> list = iLinkageUnitService.listLinkageUnitZhDto(pageNum, pageSize, par);
        Integer num = iLinkageUnitService.listLinkageUnitZhDtoCount(par);
        pageBean.setRecords(list);
        pageBean.setTotal(num);
        return ResponseHelper.buildResponse(pageBean);
    }

    /**
     * * @param null
     *
     * @return <PRE>
     * author tw
     * date 2021/7/21
     * </PRE>
     * 联动单位详情
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/linkageForce")
    @ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个联动单位", notes = "根据sequenceNbr查询单个联动单位")
    public ResponseModel<LinkageUnitDto> selectlinkageForceOne(Long id) {
        return ResponseHelper.buildResponse(iLinkageUnitService.queryOne(id));
    }


    /**
     * 消防队伍列表分页查询
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "ZQ/list")
    @ApiOperation(httpMethod = "GET", value = "执勤实力列表分页查询", notes = "执勤实力列表分页查询")
    public ResponseModel<IPage<FireTeamZhDto>> ZQlistPage(Integer pageNum, Integer pageSize, RequestData par) {
        Page<FireTeamZhDto> pageBean = new Page<>(pageNum, pageSize);
        List<FireTeamZhDto> list = iFireTeamService.getFireTeamList(pageNum, pageSize, par);
        Integer num = iFireTeamService.getFireTeamListCount(par);
        pageBean.setRecords(list);
        pageBean.setTotal(num);
        return ResponseHelper.buildResponse(pageBean);
    }

    /**
     * 根据id查询警情详情
     **/

    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "JQ/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据id查询灾情详情", notes = "根据id查询灾情详情")
    public ResponseModel<Object> selectById(@PathVariable Long id) {

        return ResponseHelper.buildResponse(iAlertCalledService.selectAlertCalledKeyValueLabelById(id));

    }


    /**
     * 根据id查询微型消防站
     *
     * @param id 主键
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/WX")
    @ApiOperation(httpMethod = "GET", value = "根据id查询微型消防站", notes = "根据id查询微型消防站")
    public ResponseModel<FireStationDto> seleteOne(Long id) {
        return ResponseHelper.buildResponse(iFireStationService.selectBySequenceNbr(id));
    }


    /**
     * 根据id查询水源
     *
     * @param id 主键
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/SY")
    @ApiOperation(httpMethod = "GET", value = "根据id查询水源", notes = "根据id查询水源")
    public ResponseModel<JSONObject> selectOne(Long id) {
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(iWaterResourceService.selectBySequenceNbr(id)));

        if (!ValidationUtil.isEmpty(jsonObject.get(BUILDDATE))) {
            String str = jsonObject.get(BUILDDATE).toString();
            Date date = new Date(Long.parseLong(str));
            jsonObject.put(BUILDDATE, DateUtils.convertDateToString(date, DateUtils.DATE_TIME_PATTERN));
        } else {
            jsonObject.put(BUILDDATE, "");
        }

        if (ValidationUtil.isEmpty(jsonObject.get("intakeHeight"))) {
            jsonObject.put("intakeHeight", "");
        }

        return ResponseHelper.buildResponse(jsonObject);
    }


    /**
     * 根据id查询队伍信息
     *
     * @param id
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/DW", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据id查询队伍信息", notes = "根据id查询队伍信息")
    public ResponseModel<FireTeam> selectById(HttpServletRequest request, Long id) {
        return ResponseHelper.buildResponse(iFireTeamService.getFireTeamBySequenceNbr(id));
    }


    /**
     * 跑马灯
     *
     * @param
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/seismometeorology", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "跑马灯", notes = "跑马灯")
    public ResponseModel<Object> seismometeorology() throws Exception {
        RequestData requestData = new RequestData();
        requestData.setWhether24(true);
        List<AlertCalledZhDto> list = iAlertCalledService.alertCalledListByAlertStatus(null, null, requestData);
        List<SeismometeorologyDto> li =new ArrayList<>();
        //数据组装
        for (AlertCalledZhDto alertCalledZhDto : list) {

            StringBuilder st = new StringBuilder();

            String time = DateUtil.formatDate(alertCalledZhDto.getCallTime(), "yyyy-MM-dd HH:mm:ss");

            st.append("【").append(alertCalledZhDto.getAlertType()).append("】").append(" ").append(time).append(" ").append(alertCalledZhDto.getAddress()!=null?alertCalledZhDto.getAddress():"");

            SeismometeorologyDto sto = new SeismometeorologyDto(alertCalledZhDto.getSequenceNbr(), "1", "警情通知", null, alertCalledZhDto.getCallTime(), null, st.toString());
            li.add(sto);
        }
        return ResponseHelper.buildResponse(li);
    }


    /**
     * 根据id指令
     *
     * @param id
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "ZL/{id}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据警情id查询指令信息", notes = "根据警情id查询指令信息")
    public ResponseModel<List<InstructionsZHDto>> selectZL(@PathVariable Long id) {
        return ResponseHelper.buildResponse(alertSubmittedService.getInstructionsZHDtoList(id));
    }


    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/gwmcDataDictionary/FireChemical/{type}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据字典类型查询危险品字典", notes = "根据字典类型查询危险品字典")
    public ResponseModel<Object> gwmcDataDictionaryFireChemical(@PathVariable String type) throws Exception {
        Object list = dataDictionaryService.getFireChemical(type);
        return ResponseHelper.buildResponse(list);
    }

    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/page")
    @ApiOperation(httpMethod = "GET", value = "危化品分页查询", notes = "危化品分页查询")
    public ResponseModel<Page<FireChemicalDto>> queryForPage(@RequestParam(value = "pageNum") int pageNum,
                                                             @RequestParam(value = "pageSize") int pageSize, String casNo,
                                                             String formula, String name, String typeCode) {
        Page<FireChemicalDto> page = new Page<FireChemicalDto>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        boolean isDelete = false;
        return ResponseHelper.buildResponse(fireChemicalService.queryForFireChemicalPage(page, casNo, formula,
                name, typeCode, isDelete));
    }


    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/gwmcDataDictionary/{type}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据字典类型查询字典", notes = "根据字典类型查询字典")
    public ResponseModel<Object> gwmcDataDictionary(@PathVariable String type) throws Exception {

        Object list = dataDictionaryService.gwmcDataDictionary(type);
        return ResponseHelper.buildResponse(list);

    }

    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "fireExperts/page")
    @ApiOperation(httpMethod = "GET", value = "外部专家分页查询", notes = "外部专家分页查询")
    public ResponseModel<IPage<FireExpertsDto>> queryForPage(@RequestParam(value = "pageNum") int pageNum,
                                                             @RequestParam(value = "pageSize") int pageSize,
                                                             FireExpertsDto fireExpertsDto,
                                                             @RequestParam(required = false, value = "companyCode") String companyCode) {
        if (!StringUtils.isEmpty(companyCode)) {
            OrgUsr orgUsr = orgUsrMapper.queryByCompanyCode(companyCode);
            if (org.apache.commons.lang3.ObjectUtils.isNotEmpty(orgUsr)) {
                fireExpertsDto.setBizOrgCode(orgUsr.getBizOrgCode());
            }
        }
        Page<FireExpertsDto> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        Page<FireExpertsDto> fireExpertsDtoPage = fireExpertsService.queryForFireExpertsPage(page, false,
                fireExpertsDto.getName(), fireExpertsDto.getExpertCode(), fireExpertsDto.getBizOrgCode());
        return ResponseHelper.buildResponse(fireExpertsDtoPage);
    }


    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "LinkageUnitDto/page")
    @ApiOperation(httpMethod = "GET", value = "联动单位分页查询", notes = "联动单位分页查询")
    public ResponseModel<Page<LinkageUnitDto>> LinkageUnitDtoQueryForPage(@RequestParam(value = "pageNum") int pageNum, @RequestParam(value = "pageSize") int pageSize, String unitName, String linkageUnitTypeCode, String linkageUnitType, String inAgreement,  @RequestParam(required = false) String bizOrgCode) {
        Page<LinkageUnitDto> page = new Page<LinkageUnitDto>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        Page<LinkageUnitDto> linkageUnitDtoPage = iLinkageUnitService.queryForLinkageUnitPage(page, false, unitName, linkageUnitTypeCode, linkageUnitType, null, inAgreement, bizOrgCode);
        return ResponseHelper.buildResponse(linkageUnitDtoPage);
    }


    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getFirefighters", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "内部专家列表分页查询", notes = "内部专家列表分页查询")
    public ResponseModel<Page<FirefightersZhDto>> getFirefighters(Integer pageNum, Integer pageSize,
                                                                  FirefightersDto firefighters,
                                                                  @RequestParam(required = false) String companyCode) {

        if (!StringUtils.isEmpty(companyCode)) {
            OrgUsr orgUsr = orgUsrMapper.queryByCompanyCode(companyCode);
            if (org.apache.commons.lang3.ObjectUtils.isNotEmpty(orgUsr)) {
                firefighters.setBizOrgCode(orgUsr.getBizOrgCode());
            }
        }
        if (firefighters.getAreasExpertiseCode() == null) {
            firefighters.setAreasExpertiseCode("0");
        }
        //条件分页
        if (null == pageNum || null == pageSize) {
            pageNum = 1;
            pageSize = Integer.MAX_VALUE;
        }
        List<FirefightersZhDto> list = firefightersService.getFirefighters((pageNum - 1) * pageSize, pageSize,
                firefighters);
        Map<String, Long> num = firefightersService.getFirefightersCount((pageNum - 1) * pageSize, pageSize,
                firefighters);
        Page<FirefightersZhDto> pageBean = new Page<>(pageNum, pageSize, num.get("num"));
        pageBean.setRecords(list);
        return ResponseHelper.buildResponse(pageBean);
    }


    /**
     * 火灾现场统计
     **/

    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "statistics/{id}")
    @ApiOperation(httpMethod = "GET", value = "火灾现场统计", notes = "火灾现场统计")
    public ResponseModel<Object> getStatistics(@PathVariable Long id) {
        return ResponseHelper.buildResponse(iAlertCalledService.selectAlertCalledcount(id));
    }

    /**
     * * @param null
     *
     * @return <PRE>
     * author tw
     * date 2021/7/22
     * </PRE>
     * 到场力量统计
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "getpower/{id}")
    @ApiOperation(httpMethod = "GET", value = "到场力量统计", notes = "到场力量统计")
    public ResponseModel<Object> getpower(@PathVariable Long id) {
        return ResponseHelper.buildResponse(iAlertCalledService.powercount(id));
    }

    /**
     * * @param null
     *
     * @return <PRE>
     * author tw
     * date 2021/7/22
     * </PRE>
     * 到场力量统计列表
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "getPowerDataList/{id}")
    @ApiOperation(httpMethod = "GET", value = "到场力量统计列表", notes = "到场力量统计列表")
    public ResponseModel<Object> getPowerDataList(@PathVariable Long id) {
        return ResponseHelper.buildResponse(iAlertCalledService.getPowerDataList(id));
    }

    /**
     * 力量统计当前灾情阶段
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "getstate/{id}")
    @ApiOperation(httpMethod = "GET", value = "获取灾情当前阶段", notes = "获取灾情当前阶段")
    public ResponseModel<Object> getstate(@PathVariable Long id) {
        AlertCalled AlertCalled = iAlertCalledService.getAlertCalledById(id);
        List<StateDot> list = new ArrayList<>();
        list.add(new StateDot("警情接报"));
        list.add(new StateDot("力量调派"));
        list.add(new StateDot("值班确警"));
        list.add(new StateDot("处置跟踪"));
        list.add(new StateDot("处置结束"));
        list.stream().forEach(stateDot -> {
            if (AlertCalled.getAlertStage().equals(stateDot.getName())) {
                stateDot.setFlag(true);
            }
        });
        return ResponseHelper.buildResponse(list);
    }

    /**
     * * @param null
     *
     * @return <PRE>
     * author tw
     * date 2021/7/22
     * </PRE>
     * 到场力量 列表统计
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "getPowerCompanyCountDtocount/{id}")
    @ApiOperation(httpMethod = "GET", value = "到场力量 列表统计", notes = "到场力量 列表统计")
    public ResponseModel<Object> getPowerCompanyCountDtocount(@PathVariable Long id) {
        return ResponseHelper.buildResponse(powerTransferService.getPowerCompanyCountDtocount(id));
    }


    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "currentPermissionTree")
    @ApiOperation(httpMethod = "GET", value = "用户菜单", notes = "用户菜单")
    public ResponseModel<List<PermissionModelDto>> currentPermissionTree() {
        //获取用户app 菜单
        List<PermissionModelDto> list = remoteSecurityService.currentPermissionTree();
        List<PermissionModelDto> listdate = getHomePermissionModel(list);
        getPermissionModel(listdate);
        return ResponseHelper.buildResponse(listdate);
    }

    public List<PermissionModelDto> getHomePermissionModel(List<PermissionModelDto> list) {
        if (list != null && !list.isEmpty()) {
            for (PermissionModelDto itme : list) {
                if ("Home".equals(itme.getFrontComponent())) {
                    String userStr = JSON.toJSONString(itme.getChildren());
                    List<PermissionModelDto> userList = JSON.parseArray(userStr, PermissionModelDto.class);
                    return userList;
                }
                if (itme.getChildren() != null && !itme.getChildren().isEmpty()) {
                    String userStr = JSON.toJSONString(itme.getChildren());
                    List<PermissionModelDto> userList = JSON.parseArray(userStr, PermissionModelDto.class);
                    return getHomePermissionModel(userList);
                }
            }

        }
        return Collections.emptyList();
    }


    public void getPermissionModel(List<PermissionModelDto> list) {
        if (list != null && !list.isEmpty()) {
            list.forEach(itme -> {
                HomePageEnum homePageEnum = HomePageEnum.statOf(itme.getFrontComponent());
                if (itme.getFrontComponent() != null && homePageEnum != null) {
                    try {
                        Class clz = Class.forName(homePageEnum.getUrl());
                        Object entity = clz.newInstance();
                        Method repay1 = clz.getDeclaredMethod("getHomePageData");
                        Object value = repay1.invoke(entity);
                        itme.setValue(value != null ? Double.valueOf(value.toString()) : 0);
                        if (itme.getChildren() != null && !itme.getChildren().isEmpty()) {
                            String userStr = JSON.toJSONString(itme.getChildren());
                            List<PermissionModelDto> userList = JSON.parseArray(userStr, PermissionModelDto.class);
                            getPermissionModel(userList);
                            itme.setChildren(userList);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    if (itme.getChildren() != null && !itme.getChildren().isEmpty()) {
                        String userStr = JSON.toJSONString(itme.getChildren());
                        List<PermissionModelDto> userList = JSON.parseArray(userStr, PermissionModelDto.class);
                        getPermissionModel(userList);
                        itme.setChildren(userList);
                    }
                }
            });
        }
    }


    /**
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/lookHtmlText")
    @ApiOperation(value = "查看文件内容", notes = "查看文件内容")
    public ResponseModel<Object> lookHtmlText(HttpServletResponse response, @RequestParam(value = "fileUrl") String fileUrl, @RequestParam(value = "product") String product, @RequestParam(value = "appKey") String appKey, @RequestParam(value = "token") String token /* @PathVariable String fileName */)
            throws BaseException {
        String fileName = readUrl + fileUrl; //目标文件
        if (fileName.endsWith(".doc") || fileName.endsWith(".docx")) {
            String htmlPath = System.getProperty("user.dir") + File.separator + "lookHtml" + File.separator + "file" + File.separator;
            String imagePathStr = System.getProperty("user.dir") + File.separator + "lookHtml" + File.separator + "image" + File.separator;
            String name = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
            String htmlFileName = htmlPath + name.substring(0, name.indexOf(".")) + ".html";
            File htmlP = new File(htmlPath);
            if (!htmlP.exists()) {
                htmlP.mkdirs();
            }
            File htmlFile = new File(htmlFileName);
            WordConverterUtils.wordToHtml(fileName, htmlFileName, imagePathStr, readUrl, remoteSecurityService, product, appKey, token);
            try (FileInputStream fis = new FileInputStream(htmlFile);
                 ServletOutputStream out = response.getOutputStream();) {
                int b = 0;
                byte[] buffer = new byte[1024];
                while ((b = fis.read(buffer)) != -1) {
                    // 4.写到输出流(out)中
                    out.write(buffer, 0, b);
                }
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ResponseHelper.buildResponse("");
        } else {
            return null;
        }

    }

    /**
     * 根据sequenceNbr查询
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "GET", value = "根据灾情查询单个航空器信息", notes = "根据灾情查询单个航空器信息")
    public ResponseModel<AircraftDto> seleteaircraftOne(@PathVariable Long sequenceNbr) {
        // 警情动态表单数据
        List<AlertFormValue> list = alertFormValueService.getzqlist(sequenceNbr);
        for (AlertFormValue alertFormValue : list) {
            if ("aircraftModel".equals(alertFormValue.getFieldCode())) {
                String aircraftModel = alertFormValue.getFieldValue();
                if (aircraftModel != null && !"".equals(aircraftModel)) {
                    AircraftDto aircraftDto = aircraftService.queryByAircraftSeq(RequestContext.getAgencyCode(), 1411994005943717890L);
                    //现场照片 待完成，
                    return ResponseHelper.buildResponse(aircraftDto);
                }
            }
        }
        return ResponseHelper.buildResponse(null);
    }

    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getOrgUsrzhDto/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据灾情id处置对象单位详情", notes = "根据灾情id处置对象单位详情")
    public ResponseModel<Object> getOrgUsrzhDto(@PathVariable Long id) {
        AlertCalled AlertCalled = iAlertCalledService.getAlertCalledById(id);

       if("230".equals(AlertCalled.getAlertTypeCode())){
           AircraftDto aircraftDto=aircraftService.queryByAircraftSeq(RequestContext.getAgencyCode(),id);
           return ResponseHelper.buildResponse(aircraftDto);
       }else{
           String buildId = null;
           OrgusrDataxDto orgusrDataxDto = new OrgusrDataxDto();
           if (AlertCalled.getUnitInvolved() != null && !"".equals(AlertCalled.getUnitInvolved())) {
               List<OrgUsrzhDto> orgUsrzhDto = iOrgUsrService.getOrgUsrzhDto(AlertCalled.getUnitInvolved());
               orgusrDataxDto.setOrgUsrzhDto(orgUsrzhDto != null && orgUsrzhDto.size() > 0 ? orgUsrzhDto.get(0) : null);
               if (orgUsrzhDto != null && orgUsrzhDto.size() > 0 && orgUsrzhDto.get(0) != null) {
                   buildId = orgUsrzhDto.get(0).getBuildId();
               }
           }
           if (buildId != null) {
               List<Map<String, Object>> list = equipFeignClient.findImgByFileCategory(buildId, "fourImg").getResult();
               List<String> url = new ArrayList<>();
               if (list != null && list.size() > 0) {
                   list.stream().forEach(map -> {
                       url.add(map.get(FILEPATH).toString());
                   });
               }

               //通道
               List<Map<String, Object>> list1 = equipFeignClient.findImgByFileCategory(buildId, "secondImg").getResult();
               List<String> url1 = new ArrayList<>();
               if (list1 != null && list1.size() > 0) {
                   list1.stream().forEach(map -> {
                       url1.add(map.get(FILEPATH).toString());
                   });
               }
               //立面
               List<Map<String, Object>> list2 = equipFeignClient.findImgByFileCategory(buildId, "threeImg").getResult();
               List<String> url2 = new ArrayList<>();
               if (list2 != null && list2.size() > 0) {
                   list2.stream().forEach(map -> {
                       url2.add(map.get(FILEPATH).toString());
                   });
               }
               orgusrDataxDto.setPlanePicture(url);
               orgusrDataxDto.setScenePicture(url1);
               orgusrDataxDto.setFacadePicture(url2);
           }
           return ResponseHelper.buildResponse(orgusrDataxDto);
       }
    }


    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/AlertCalledcountTime")
    @ApiOperation(httpMethod = "GET", value = "执勤动态警情信息统计", notes = "执勤动态警情信息统计")
    public ResponseModel<Object> AlertCalledcountTime() {
        List<KeyValueLabel> listdate = new ArrayList<>();
        listdate.add(new KeyValueLabel("今年警情数量", "", iAlertCalledService.AlertCalledcountTime(1)));
        listdate.add(new KeyValueLabel("当月警情数量", "", iAlertCalledService.AlertCalledcountTime(2)));
        listdate.add(new KeyValueLabel("昨天警情数量", "", iAlertCalledService.AlertCalledcountTime(4)));
        listdate.add(new KeyValueLabel("今天警情数量", "", iAlertCalledService.AlertCalledcountTime(3)));
        return ResponseHelper.buildResponse(listdate);
    }


    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getTodayPowerTransferCompany")
    @ApiOperation(httpMethod = "GET", value = "当天力量调派", notes = "当天力量调派")
    public ResponseModel<Object> getTodayPowerTransferCompany() {
        return ResponseHelper.buildResponse(powerTransferCompanyService.getTodayPowerTransferCompany());
    }

    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getTodayAlertCalled")
    @ApiOperation(httpMethod = "GET", value = "当天接警记录", notes = "当天接警记录")
    public ResponseModel<Object> getTodayAlertCalled() {
        return ResponseHelper.buildResponse(iAlertCalledService.getTodayAlertCalled());
    }

    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getFireTeamCountList")
    @ApiOperation(httpMethod = "GET", value = "执勤力量", notes = "执勤力量")
    public ResponseModel<Object> getFireTeamCountList() {
        return ResponseHelper.buildResponse(iFireTeamService.getFireTeamCountList());
    }

    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @ApiOperation("当天值班人信息列表")
    @GetMapping("/getonDuty/list")
    public ResponseModel<Object> listOnDutyPerson() {
        return ResponseHelper.buildResponse(iDutyPersonService.listOnDutyPerson());
    }

    /**
     * 跑马灯
     *
     * @param
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/findDutyCarStateBy", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "当日气象预警", notes = "当日气象预警")
    public ResponseModel<Object> findDutyCarStateBy() throws BaseException {
        return ResponseHelper.buildResponse(null);
    }

    /**
     * 分页获取视频
     *
     * @param
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getVideo", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "分页获取视频", notes = "分页获取视频")
    public ResponseModel<Object> getVideo(long current, long size) throws BaseException {
        ResponseModel<Page<Map<String, Object>>> data = equipFeignClient.getVideo(current, size, 0L);
        Page<Map<String, Object>> pag = data != null ? data.getResult() : null;
        List<Map<String, Object>> records = pag != null ? pag.getRecords() : null;
        if (records != null && records.size() > 0) {
            for (Map<String, Object> rec: records) {
                ResponseModel<String> da = videoFeignClient.videoUrlByIndexCode(rec.get("code") + "");
                String url = da != null ? da.getResult().substring(da.getResult().indexOf(OPENURL)) : null;
                rec.put("url", url);
            }
            pag.setRecords(records);
        }
        return ResponseHelper.buildResponse(pag);
    }


    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "fireCar/list")
    @ApiOperation(httpMethod = "GET", value = "车辆资源", notes = "车辆资源")
    public ResponseModel<Object> getTeamCarList(RequestData par) {
        /*bug 2583 地图屏，消防车辆类型时，左侧车辆状态显示错误 陈召 开始 */
        ResponseModel<List<Map<String, Object>>> date = equipFeignClient.getTeamCarList(par.getCarId(),par.getLongitude(), par.getLatitude());
        List<Map<String, Object>> result = date.getResult();
        QueryWrapper<PowerTransferCompanyResources> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", FireCarStatusEnum.执行中.getCode());
        List<PowerTransferCompanyResources> alertFormValue = powerTransferCompanyResourcesMapper.selectList(queryWrapper);
        result.stream().forEach(e -> {
            if (e.get(CARSTATE).equals("在位")) {
                e.put(CARSTATE, FireCarStatusEnum.执勤.getName());
            }

            String sequenceNbr = e.get("sequenceNbr").toString();

            //查询最新的经纬度
            ESCar es= esCarService.findAllByCarId(Long.valueOf(sequenceNbr));
            if(es!=null){
                e.put("longitude", es.getLongitude());
                e.put("latitude",es.getLatitude());
            }

            //同步力量调派车辆任务状态
            alertFormValue.stream().forEach(v -> {
                if (v.getResourcesId().equals(sequenceNbr)) {
                    String carStatus = v.getCarStatus();
                    e.put(CARSTATE, carStatus != null ? FireCarStatusEnum.getEnum(carStatus).getName() : null);
                }
            });
        });
        return ResponseHelper.buildResponse( date.getResult());
        /*bug 2583 地图屏，消防车辆类型时，左侧车辆状态显示错误 2021-10-26 陈召 结束 */
    }

    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/fireCar")
    @ApiOperation(httpMethod = "GET", value = "车辆资源详情", notes = "车辆资源详情")
    public ResponseModel<Map<String, Object>> getCarDetailById(Long id) {
        ResponseModel<Map<String, Object>> date = equipFeignClient.getCarDetailById(id);

        Map<String, Object> map = date != null ? date.getResult() : null;
        if (map != null) {
            int num = 0;
            num = iDutyCarService.getDutyCarCount(id);
            map.put("personNum", num);
        }
        return ResponseHelper.buildResponse(map);
    }



    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据灾情id建筑部位树", notes = "根据灾情id建筑部位树")
    @GetMapping(value = "/getBuildTree/{id}")
    public ResponseModel<List<OrgMenuDto>> getBuildTree(@PathVariable Long id) throws BaseException {

        AlertCalled AlertCalled = iAlertCalledService.getAlertCalledById(id);
        Long buildId = null;
        String buildIdName = "";
        Long zdid = null;
        String zdname = "";
        if (AlertCalled.getUnitInvolved() != null && !"".equals(AlertCalled.getUnitInvolved())) {
            List<OrgUsrzhDto> orgUsrzhDto = iOrgUsrService.getOrgUsrzhDto(AlertCalled.getUnitInvolved());
            if (orgUsrzhDto != null && orgUsrzhDto.size() > 0 && orgUsrzhDto.get(0) != null) {
                buildId = orgUsrzhDto.get(0).getBuildId() == null ? null : Long.valueOf(orgUsrzhDto.get(0).getBuildId());
                buildIdName = orgUsrzhDto.get(0).getBuildId() == null ? null : orgUsrzhDto.get(0).getBuildName();
            }
        }


        // 警情动态表单数据
        List<AlertFormValue> list = buildId == null ? null : iAlertFormValueService.getzqlist(id);
        if (list != null && list.size() > 0) {
            for (AlertFormValue alertFormValue : list) {
                if (KEYSITE.equals(alertFormValue.getFieldCode()) && alertFormValue.getFieldValue() != null) {
                    List<OrgMenuDto> list1 = new ArrayList<OrgMenuDto>();
                    List<OrgMenuDto> children = new ArrayList<OrgMenuDto>();
                    OrgMenuDto date = new OrgMenuDto(Long.valueOf(alertFormValue.getFieldValueCode()), Long.valueOf(alertFormValue.getFieldValueCode()), alertFormValue.getFieldValue(), alertFormValue.getFieldValue(), null);
                    children.add(date);
                    OrgMenuDto orgMenuDto = new OrgMenuDto();
                    orgMenuDto.setKey(buildId);
                    orgMenuDto.setValue(buildId);
                    orgMenuDto.setChildren(children);
                    orgMenuDto.setName(buildIdName);
                    orgMenuDto.setTitle(buildIdName);
                    list1.add(orgMenuDto);
                    return ResponseHelper.buildResponse(list1);
                }
            }
        }
        return ResponseHelper.buildResponse(buildId == null ? null : keySiteService.getBuildAndKeyTree(buildId));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据bizOrgCode建筑部位树", notes = "根据bizOrgCode建筑部位树")
    @GetMapping(value = "/getBuildTreeCcs/{buildId}")
    public ResponseModel<List<OrgMenuDto>> getBuildTreeCcs(@PathVariable Long buildId) throws BaseException {

        return ResponseHelper.buildResponse(keySiteService.getBuildAndKeyTree(buildId));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据重点部位id查询详情", notes = "根据重点部位id查询详情")
    @GetMapping(value = "/getkeySite/{sequenceNbr}")
    public ResponseModel<KeySiteDto> getkeySite(@PathVariable Long sequenceNbr) {
        Map<String, List<AttachmentDto>> files = sourceFileService.getAttachments(sequenceNbr);
        KeySiteDto dto = keySiteService.getSequenceNbr(sequenceNbr);
        List<String> list = new ArrayList<String>();
        if (files != null && dto != null) {
                dto.setAttachments(files);
                JSONArray array = JSON.parseArray(JSON.toJSONString(files.get("keySitePhoto")));
                if (array != null && array.size() > 0) {
                    for (Object i : array) {
                        JSONObject object = JSON.parseObject(JSON.toJSONString(i));
                        list.add(object.getString("url"));
                    }
                }
            dto.setAttachmentsList(list);
        }
        return ResponseHelper.buildResponse(dto);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "app-根据警情id查询力量调派列表", notes = "app-根据警情id查询力量调派列表")
    @GetMapping(value = "/app/transferList")
    public ResponseModel<Object> getPowerTransferList(@RequestParam String alertId, @RequestParam(defaultValue = "team") String type, @RequestParam(value = "current") int current, @RequestParam(value = "size") int size) {
        Page<PowerTransferResourceDto> page = new Page<>();
        page.setSize(size);
        page.setCurrent(current);
        return ResponseHelper.buildResponse(powerTransferService.getPowerTransferPageByParam(Long.valueOf(alertId), type, page));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "app-根据警情id查询力量调派资源统计", notes = "app-根据警情id查询力量调派资源统计")
    @GetMapping(value = "/app/transfer/statistics")
    public ResponseModel<List<ResourceStatisticsDto>> getPowerTransferStatistics(@RequestParam String alertId, @RequestParam(defaultValue = "team") String type) {
        return ResponseHelper.buildResponse(powerTransferService.getPowerTransferStatistics(Long.valueOf(alertId), type));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "PUT", value = "app-更新车辆状态", notes = "app-更新车辆状态")
    @PutMapping(value = "/app/carStatus")
    public ResponseModel<Boolean> updateCarStatus(@RequestParam String carId, @RequestParam String carStatus) {
        CarStatusInfoDto carStatusInfoDto = new CarStatusInfoDto();
        carStatusInfoDto.setSequenceNbr(carId);
        carStatusInfoDto.setStatus(carStatus);
        try {
            equipFeignClient.updateCarStatus(Lists.newArrayList(carStatusInfoDto));
        } catch (Exception e) {
            throw new BaseException("更新车辆状态异常", "", e.getMessage());
        }
        return ResponseHelper.buildResponse(true);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "app-警情详情-处置对象", notes = "app-警情详情-处置对象")
    @GetMapping(value = "/app/disposalObject")
    public ResponseModel<List<JSONObject>> queryDisposalObject(@RequestParam String alertId) {
        List<JSONObject> resultList;
        try {
            resultList = iAlertCalledService.queryDisposalObjectList(alertId);
        } catch (Exception e) {
            throw new BaseException("获取处置对象异常", "", e.getMessage());
        }
        return ResponseHelper.buildResponse(resultList);
    }

    /**
     * app-根据id查询警情详情
     **/
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "alertCalled/{id}")
    @ApiOperation(httpMethod = "GET", value = "app-根据id查询灾情详情", notes = "app-根据id查询灾情详情")
    public ResponseModel<Object> selectByAlertCalledId(@PathVariable Long id) {
        return ResponseHelper.buildResponse(iAlertCalledService.queryAlertCalledById(id));
    }

    /**
     * app-根据id查询警情力量统计
     **/
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "alertCalled/statistics/{alertId}")
    @ApiOperation(httpMethod = "GET", value = "app-根据id查询警情力量统计", notes = "app-根据id查询警情力量统计")
    public ResponseModel<Object> statisticsByAlertCalledId(@PathVariable Long alertId) {
        return ResponseHelper.buildResponse(powerTransferService.getPowerTransferCarResourceStatistics(alertId));
    }

    /**
     * app-车辆状态列表
     **/
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/app/carStatus/list")
    @ApiOperation(httpMethod = "GET", value = "app-车辆状态列表", notes = "app-车辆状态列表")
    public ResponseModel<Object> carStatusList() {
        return ResponseHelper.buildResponse(powerTransferService.getFireCarStatusList());
    }

    /**
     * app-调派任务状态列表
     **/
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/app/dispatchTaskStatus/list")
    @ApiOperation(httpMethod = "GET", value = "app-调派任务状态列表", notes = "app-调派任务状态列表")
    public ResponseModel<Object> powerTransferResourceStatusList() {
        return ResponseHelper.buildResponse(powerTransferService.getDispatchTaskStatusList());
    }

    /**
     * app-当前登陆人是否是驾驶员
     **/
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/app/personPost")
    @ApiOperation(httpMethod = "GET", value = "app-当前登陆人是否是驾驶员", notes = "app-当前登陆人是否是驾驶员")
    public ResponseModel<Object> isFireCarDriver() {
        return ResponseHelper.buildResponse(iDutyCarService.isFireCarDriver());
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/DynamicFlightInfo/{dynamicFlightId}")
    @ApiOperation(httpMethod = "GET", value = "航班信息", notes = "航班信息")
    public ResponseModel<Object> DynamicFlightInfo(@PathVariable String dynamicFlightId) {
        ResponseModel<Object> dataModel = iotFeignClient.DynamicFlightInfo(dynamicFlightId);
        if (dataModel != null) {
            return ResponseHelper.buildResponse(dataModel.getResult());
        }
        return ResponseHelper.buildResponse(null);
    }


    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "AlertCalledStatusPage")
    @ApiOperation(httpMethod = "GET", value = "未结束的灾情列表", notes = "未结束的灾情列表")
    public ResponseModel<Page<AlertCalled>> AlertCalledStatusPage(@RequestParam(value = "current") Integer current, @RequestParam(value = "size") Integer size) {
        if (null == current || null == size) {
            current = 1;
            size = Integer.MAX_VALUE;
        }
        List<AlertCalled> list = iAlertCalledService.AlertCalledStatusPage(current, size);
        int num = iAlertCalledService.AlertCalledcount(0);
        Page<AlertCalled> pageBean = new Page<>(current, size, num);
        pageBean.setRecords(list);
        return ResponseHelper.buildResponse(pageBean);
    }


    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "equipmentCarList")
    @ApiOperation(httpMethod = "GET", value = "车辆列表", notes = "车辆列表")
    public ResponseModel<Object> equipmentCarList(String name,
                                                  String code,
                                                  String pageNum,
                                                  String pageSize,
                                                  Boolean isNo) {
        //获取用户所属单位id
        AgencyUserModel agencyUserModel = getUserInfo();
        Long teamId = null;
        Firefighters orgUsr= firefightersService.selectByAmosOrgId(Long.valueOf(agencyUserModel.getUserId()));
        teamId=orgUsr!=null?Long.valueOf(orgUsr.getFireTeamId()):null;
        Long id = null;
        //获取用户已绑定车辆id、
        UserCar userCar = userCarService.selectByAmosUserId(Long.valueOf(agencyUserModel.getUserId()));

        List<UserCar> listcar = userCarService.selectList();

        id = userCar != null ? userCar.getCarId() : null;
        if (id == null && isNo != null && isNo) {
            Map<String,Object> map = new HashMap<>();
            map.put("select", null);
            map.put("data", null);
            return ResponseHelper.buildResponse(null);
        }

        if(teamId==null){
            return ResponseHelper.buildResponse(null);
        }
        ResponseModel<Page<CarInfoDto>> data = equipFeignClient.equipmentCarList(teamId, name, code, pageNum, pageSize, id, isNo);
        List<CarInfoDto> array=null;
        if(data != null && data.getResult()!=null){
            array = data.getResult().getRecords();
            if(listcar!=null&&listcar.size()>0){
                for (CarInfoDto carInfoDto : array) {
                    for (UserCar car : listcar) {
                        if(car.getCarId().longValue()==carInfoDto.getId().longValue()){
                            carInfoDto.setUserName(car.getAmosUserName());
                        }
                    }
                }
            }
            data.getResult().setRecords(array);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("select", userCar != null ? userCar.getCarId() : null);
        map.put("data", data != null ? data.getResult() : null);
        return ResponseHelper.buildResponse(map);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "countUserCarExecuting")
    @ApiOperation(httpMethod = "GET", value = "获取用户绑定的车辆的状态为执行中的数量", notes = "获取用户绑定的车辆的状态为执行中的数量")
    public ResponseModel<Object> countUserCarExecuting() {
        return ResponseHelper.buildResponse(userCarService.countUserCarExecuting(Long.valueOf(getUserId())));
    }

    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "gettree")
    @ApiOperation(httpMethod = "GET", value = "车辆分类", notes = "车辆分类")
    public ResponseModel<Object> gettree() {

        ResponseModel<Object> data = equipFeignClient.gettree();
        return ResponseHelper.buildResponse(data != null ? data.getResult() : null);
    }


    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "adduserCar/{type}", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "增加绑定", notes = "增加绑定")
    public ResponseModel<Object> adduserCar(@PathVariable String type, @RequestBody UserCar userCar) {
        AgencyUserModel agencyUserModel = getUserInfo();
        userCar.setAmosUserId(Long.valueOf(agencyUserModel.getUserId()));
        userCar.setAmosUserName(agencyUserModel.getRealName());

        if ("1".equals(type)) {
            Firefighters orgUsr= firefightersService.selectByAmosOrgId(Long.valueOf(agencyUserModel.getUserId()));
            userCar.setTeamId(orgUsr.getFireTeamId()+"");
            userCarService.add(userCar);
        } else {
            userCarService.delete(userCar);
        }
        return ResponseHelper.buildResponse(true);
    }


    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "getAlertCalledId", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取绑定车辆装", notes = "获取绑定车辆装")
    public ResponseModel<UserCar> getAlertCalledId() {
        AgencyUserModel agencyUserModel = getUserInfo();
        Long id = null;
        //获取用户已绑定车辆id、
        UserCar userCar = userCarService.selectByAmosUserId(Long.valueOf(agencyUserModel.getUserId()));
        return ResponseHelper.buildResponse(userCar);
    }

    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "getAlertCalledData", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取当前执行灾情", notes = "获取当前执行灾情")
    public ResponseModel<Object> getAlertCalled() {
        AgencyUserModel agencyUserModel = getUserInfo();
        Long id = null;
        //获取用户已绑定车辆id、
        UserCar userCar = userCarService.selectByAmosUserId(Long.valueOf(agencyUserModel.getUserId()));
        //获取正在进行的灾情null
        if (userCar != null) {
            AlertCalled alertCalled = powerTransferCompanyResourcesService.getByPowerTransferCompanyResourId(userCar.getCarId());
            if(alertCalled!=null) {
                alertCalled.setLatitude(alertCalled.getCoordinateX() != null ? alertCalled.getCoordinateX().toString() : null);
                alertCalled.setLongitude(alertCalled.getCoordinateY() != null ? alertCalled.getCoordinateY().toString() : null);
                return ResponseHelper.buildResponse(alertCalled);
            }
        }
        return ResponseHelper.buildResponse(null);
    }


    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "getPowerTransferCompanyResourcesService/{carid}/{alertCalledId}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取当前任务，车辆状态", notes = "获取当前任务，车辆状态")
    public ResponseModel<Object> getPowerTransferCompanyResourcesService(@PathVariable Long carid,
                                                                         @PathVariable Long alertCalledId) {
        //获取正在进行的灾情
        PowerTransferCompanyResources powerTransferCompanyResources = powerTransferCompanyResourcesService.getByAlertCalledIdCarId(alertCalledId, carid);

        return ResponseHelper.buildResponse(powerTransferCompanyResources);
    }

    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "getTaskFeedback/{carid}/{alertCalledId}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取当前车辆任务反馈", notes = "获取当前车辆任务反馈")
    public ResponseModel<List<JcSituationDetail>> getTaskFeedback(@PathVariable Long carid,
                                                                         @PathVariable Long alertCalledId) {

        return ResponseHelper.buildResponse(powerTransferCompanyResourcesService.getTaskFeedback(carid,alertCalledId));
    }





    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "getPowerTransferCompanyResourcesServiceNew", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取当前任务，车辆状态,随车人员，任务详情", notes = "获取当前任务，车辆状态,随车人员，任务详情")
    public ResponseModel<Object> getPowerTransferCompanyResourcesNewService(@RequestParam String id
    ) {

        PowerTransferCompanyResources powerTransferCompanyResources = new PowerTransferCompanyResources();
        // 根据车牌查询车辆调派信息级警情id

        List<PowerData> pw = powerTransferMapper.getPowerDataCar(id);
        if (null != pw && pw.size() > 0) {
            Long alertCalledId = Long.valueOf(pw.get(0).getAlertCallId());
            Long carid = Long.valueOf(pw.get(0).getResourcesId());
            //获取正在进行的灾情
            powerTransferCompanyResources = powerTransferCompanyResourcesService.getByAlertCalledIdCarId(alertCalledId, carid);
            // 随车人员
            List<Map<String, Object>> equipmentList = iDutyCarService.getDutyCaruser(carid);

            if (!ValidationUtil.isEmpty(equipmentList)) {
                String str = "";
                String newStr = "";
                for (int i = 0; i < equipmentList.size(); i++) {
                    if (i == equipmentList.size() - 1) {
                        newStr =newStr+ str.concat(equipmentList.get(i).get(USERNAME) + "");
                    } else {
                        newStr = newStr+str.concat(equipmentList.get(i).get(USERNAME) + ",");
                    }
                }
                powerTransferCompanyResources.setPw(newStr);
            } else {
                powerTransferCompanyResources.setPw("无");
            }

            //任务详情
            PowerData powerData = powerTransferMapper.getPowerDataOther(alertCalledId, carid);
            if (null != powerData) {
                powerTransferCompanyResources.setTaskInformation(powerData.getTaskInformation());
            }
        } else {
           ResponseModel<Map<String, Object>> equipmentIndexDto = equipFeignClient.getCarDetailByCarNum(id);
            if (equipmentIndexDto.getResult().size() == 0) {
                return ResponseHelper.buildResponse(null);
            }
            if (!ValidationUtil.isEmpty(equipmentIndexDto.getResult())) {
                Map<String, Object> map = equipmentIndexDto.getResult();
                // 随车人员
                List<Map<String, Object>> equipmentList = iDutyCarService.getDutyCaruser(Long.valueOf(map.get("id").toString()));
                powerTransferCompanyResources.setResourcesName(map.get("name").toString());
                powerTransferCompanyResources.setResourcesNum(map.get("carNum").toString());

              if (!ValidationUtil.isEmpty(equipmentList)) {
                    String str = "";
                    String newStr = "";
                    for (int i = 0; i < equipmentList.size(); i++) {
                        if (i == equipmentList.size() - 1) {
                            newStr = newStr+str.concat(equipmentList.get(i).get(USERNAME) + "");
                        } else {
                            newStr =newStr+ str.concat(equipmentList.get(i).get(USERNAME) + ",");
                        }
                    }
                    powerTransferCompanyResources.setPw(newStr);
                } else {
                    powerTransferCompanyResources.setPw("无");
                }

                powerTransferCompanyResources.setStatusName("无任务");
                powerTransferCompanyResources.setCarStatusName("执勤");
                powerTransferCompanyResources.setTaskInformation("无");
            }
        }
        return ResponseHelper.buildResponse(powerTransferCompanyResources);
    }


    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "updatePowerTransferCompanyResourcesService", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "修改任务，车辆状态", notes = "修改任务，车辆状态")
    public ResponseModel<Object> updatePowerTransferCompanyResourcesService(@RequestBody CarTaskDto carTaskDto) {
        //获取正在进行的灾情
        powerTransferCompanyResourcesService.updatePowerTransferCompanyResourcesService(
                carTaskDto.getAlertCalledId(),
                carTaskDto.getCarid(),
                carTaskDto.getCode(),
                carTaskDto.getType(),
                carTaskDto.getRemarks(),carTaskDto.getPhotos());

        ReginParams reginParams = getSelectedOrgInfo();
        String userId = reginParams.getUserModel().getUserId();
        // 执行任务完成反馈，同步修改待办任务状态
        if (carTaskDto.getType() == 2 && FireCarStatusEnum.已完成.getCode().equals(carTaskDto.getCode())){
            MessageModel model = new MessageModel();
            model.setRelationId(String.valueOf(carTaskDto.getAlertCalledId()));
            model.setIsRead(true);
            model.setMsgType("jcs119");
            if (!ObjectUtils.isEmpty(userId)){
                model.setUserId(userId);
            }
            Systemctl.messageClient.update(model);
        }
        return ResponseHelper.buildResponse(null);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "getAMapWeather", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取百度地图天气", notes = "获取百度地图天气")
    public ResponseModel<Object> getAMapWeather() {
        ResponseEntity<HashMap> weather = restTemplate.getForEntity(
                "https://restapi.amap.com/v3/weather/weatherInfo?key=4bee67717254d93067fdbc09cd61c7d9&city=610100&extensions=all",
                HashMap.class);
        return ResponseHelper.buildResponse(weather);
    }



    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getuserBJ", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取当前登录人员是否绑定车辆", notes = "获取当前登录人员是否绑定车辆")
    public ResponseModel<UserCar> getuserBJ() {
                return  this.getAlertCalledId() ;
    }

    //存储啊手机上报的车辆信息
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/addESCar", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "手机上报", notes = "手机上报")
    public ResponseModel<Object> addESCar( @RequestBody ESCarDto esCarDto) {

        try {
            Date date1=  new Date();
            ESCar esCar = new ESCar();
            BeanUtils.copyProperties(esCarDto,esCar);
            esCar.setId(UUID.randomUUID().toString().trim().replace("-",""));
            esCar.setTime(date1.getTime());
            Gps gps = PositionUtil.gcj02_To_Gps84(Double.valueOf(esCar.getLatitude()), Double.valueOf(esCar.getLongitude()));
            esCar.setLongitude(String.valueOf(gps.getWgLon()));
            esCar.setLatitude(String.valueOf(gps.getWgLat()));
            esCarService.saveESCar(esCar);
            //给App端发送
            ResponseModel<List<Map<String, Object>>> date = equipFeignClient.getTeamCarList(esCar.getSequenceNbr().toString(),null,null);
            List<Map<String, Object>> result = date.getResult();
            QueryWrapper<PowerTransferCompanyResources> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", FireCarStatusEnum.执行中.getCode());
            List<PowerTransferCompanyResources> alertFormValue = powerTransferCompanyResourcesMapper.selectList(queryWrapper);
            if(result!=null&&result.size()>0){
                result.stream().forEach(e -> {
                    if (e.get(CARSTATE).equals("在位")) {
                        e.put(CARSTATE, FireCarStatusEnum.执勤.getName());
                    }

                    String sequenceNbr = e.get("sequenceNbr").toString();
                    //同步力量调派车辆任务状态
                    alertFormValue.stream().forEach(v -> {
                        if (v.getResourcesId().equals(sequenceNbr)) {
                            String carStatus = v.getCarStatus();
                            e.put(CARSTATE, carStatus != null ? FireCarStatusEnum.getEnum(carStatus).getName() : null);
                        }
                    });

                    e.put("latitude", String.valueOf(gps.getWgLat()));
                    e.put("longitude", String.valueOf(gps.getWgLon()));
                });

                emqKeeper.getMqttClient().publish(topic,JSON.toJSONString(result.get(0)).getBytes(), RuleConfig.DEFAULT_QOS, false);

                String msg = "消息推送成功,数据: %s"+ JSON.toJSONString(result.get(0));
                log.info(msg);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseHelper.buildResponse(true);
    }

    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getEsCar", produces = "application/json;charset=UTF-8", method = RequestMethod.GET
    )
    @ApiOperation(httpMethod = "get", value = "手机上报", notes = "手机上报")
    public ResponseModel<Object> getEsCar(Long sequenceNbr) throws BaseException {
        Iterable<ESCar> allById = esCarService.findAllById(Arrays.asList(sequenceNbr));
        List<ESCar> esCars = new ArrayList<>();
        allById.forEach(e -> {
            ESCar esCar = new ESCar();
            BeanUtils.copyProperties(e,esCar);
            esCars.add(esCar);
        });
        ESCar esCar = esCars.stream().sorted(Comparator.comparing(ESCar::getTime).reversed()).collect(Collectors.toList()).get(0);
        return  ResponseHelper.buildResponse(esCar);

    }


}