package com.yeejoin.equipmanage.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.dto.OrgMenuDto;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.equipmanage.common.dto.CarInfoDto;
import com.yeejoin.equipmanage.common.dto.CarStatusInfoDto;
import com.yeejoin.equipmanage.common.entity.*;
import com.yeejoin.equipmanage.common.entity.dto.CarEquipAlarmInfoDto;
import com.yeejoin.equipmanage.common.entity.dto.CarEquipStateInfoDto;
import com.yeejoin.equipmanage.common.entity.dto.CommonFile;
import com.yeejoin.equipmanage.common.entity.publics.CommonResponse;
import com.yeejoin.equipmanage.common.entity.vo.CarIndexVo;
import com.yeejoin.equipmanage.common.entity.vo.CarMessage;
import com.yeejoin.equipmanage.common.entity.vo.EquipmentOnCarAppVO;
import com.yeejoin.equipmanage.common.enums.*;
import com.yeejoin.equipmanage.common.utils.*;
import com.yeejoin.equipmanage.common.vo.*;
import com.yeejoin.equipmanage.dto.*;
import com.yeejoin.equipmanage.fegin.JcsFeign;
import com.yeejoin.equipmanage.mapper.*;
import com.yeejoin.equipmanage.service.*;
import com.yeejoin.equipmanage.service.impl.FireFightingSystemServiceImpl;
import com.yeejoin.equipmanage.service.impl.SourcesStatisticsImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 消防车信息
 *
 * @author wujiang
 * @date 2020-07-07
 */
@RestController
@Api(tags = "消防车信息Api")
@RequestMapping(value = "/car", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Slf4j
public class CarController extends AbstractBaseController {

    @Autowired
    @Lazy
    ICarService iCarService;
    @Autowired
    private EquipmentMapper equipmentMapper;
    @Autowired
    ISystemDicService iSystemDicService;
    @Autowired
    private EquipmentCategoryMapper equipmentCategoryMapper;
    @Autowired
    ICarInfoService iCarInfoService;
    @Autowired
    ICarPropertyService iCarPropertyService;
    @Autowired
    CarInfoMapper carInfoMapper;
    @Autowired
    private ManufacturerInfoMapper manufacturerInfoMapper;
    @Autowired
    private CarPropertyMapper carPropertyMapper;
    @Autowired
    IEquipmentOnCarService iEquipmentOnCarService;
    @Autowired
    ExtinguishantOnCarMapper extinguishantOnCarMapper;
    @Autowired
    SystemDicMapper systemDicMapper;
    @Autowired
    CarMapper carMapper;
    @Autowired
    private EquipmentIndexMapper equipmentIndexMapper;
    @Autowired
    EquipmentDetailMapper equipmentDetailMapper;
    @Autowired
    EquipmentQrcodeMapper equipmentQrcodeMapper;
    @Resource(name = "productionQRCodeFactoryMap")
    private Map<String, ProductionQRCode> messageHandMap;

    @Autowired
    ICarLonAndLatDataService iCarLonAndLatDataService;

    @Lazy
    @Autowired
    IEquipmentService iEquipmentService;

    @Autowired
    IEquipmentDetailService iEquipmentDetailService;

    @Autowired
    IEquipmentQrcodeService iEquipmentQrcodeService;

    @Autowired
    IEquipmentIndexService iEquipmentIndexService;

    @Autowired
    private ISyncDataService syncDataService;
    @Value("${redis_equip_type_count}")
    private String equipTypeAndCount;

    @Value("${redis_car_type_count}")
    private String carTypeAndCount;
    @Autowired
    private RestTemplate restTemplate;
    @Value("${security.productApp}")
    private String productApp;
    @Value("${amos.system.user.app-key}")
    private String appKeyApp;
    @Value("${iot.vehicle.track}")
    private String iotServerName;

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

    @Value("${auth-key-fire-car}")
    private String carAuthKey;

    @Value("${auth-key-fire-iot-equip:fire_iot-equip_info}")
    private String iotAuthKey;

    @Autowired
    ISourceStatistics iSourceStatistics;

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    JcsFeign jcsFeign;
    @Autowired
    FireFightingSystemServiceImpl fireFightingSystemServiceImpl;

    @Value("${iot.code.prefix.have.used:20210003,20210004,20210005}")
    private String haveUsedIotPrefix;

    /**
     * 新增消防车信息
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "新增消防车信息", notes = "新增消防车信息")
    public Car saveCar(HttpServletRequest request, @RequestBody Car car) {
//		Car car = carRequest.getCar();
//		if (carRequest == null || carRequest.getCar() == null) {
//			return new CommonResponse(FAILED, "参数有误");
//		}
//		AgencyUserModel user = getUserInfo();
//		CarInfo carInfo = carRequest.getCarInfo();
//		Set<CarProperty> carpList = carRequest.getCarPropertyList();
//		Car carInstance = iCarService.saveCar(user, car, carInfo, carpList);

        // saveFile(carInstance); 图片视频后期统一处理
        //如果默认有id值则认为是更新
        if (car.getId() != null) {
            Car car1 = this.iCarService.getById(car.getId());
            if (car.getOrgCode() != null && !car.getBizOrgCode().equals(car1.getBizOrgCode())) {
                FeignClientResult<Map<String, Object>> result = Privilege.companyClient
                        .queryByOrgcode(car.getBizOrgCode());
                System.out.println("==============================" + JSONObject.toJSONString(result.getResult()));
                if (result.getResult() != null && result.getResult().containsKey("compnay")) {
                    Map<String, String> map = (Map<String, String>) result.getResult().get("compnay");
                    car.setBizOrgName(map.get("companyName"));
                }
            }
            Car car2 = updateCar(car);
            CarController controllerProxy = SpringUtils.getBean(CarController.class);
            controllerProxy.refreshAllCount();
            return car2;
        }
        // 验证车辆code唯一性
        String iotCode = car.getIotCode();
        if(StringUtils.isNotEmpty(iotCode) && StringUtils.isNotEmpty(iotCode.trim())){
            Car ar= carMapper.getCarsByIotCode(car.getIotCode());
            if(ar!=null){
                throw new BadRequest("物联编码重复");
            }
            if(StringUtils.isNotEmpty(haveUsedIotPrefix) && Arrays.stream(haveUsedIotPrefix.split(",")).anyMatch(iotCode::startsWith)){
                throw new BadRequest("物联编码航班已占用");
            }
        }
        car.setQrCode(QRCodeUtil.generateQRCode());
        List<CarProperty> carPropertyList = car.getCarPropertyList();
        if (carPropertyList != null && carPropertyList.size() > 0) {
            carPropertyList.forEach(x -> {
                QueryWrapper<EquipmentIndex> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("id", x.getEquipmentIndexId());
                EquipmentIndex equipmentIndex = iEquipmentIndexService.getOne(queryWrapper);
                String state = equipmentIndex.getPerfQuotaDefinitionId();
                if ("state".equals(state)) {
                    if ("是".equals(x.getValue())) {
                        x.setValue(TrueOrFalseEnum.real.value);
                    } else {
                        x.setValue(TrueOrFalseEnum.fake.value);
                    }
                }
            });
        }
        if (!ObjectUtils.isEmpty(car.getEquipmentId())) {
            Equipment equipment = iEquipmentService.getById(car.getEquipmentId());
            car.setName(equipment != null ? equipment.getName() : null);
        }
        if (ObjectUtils.isEmpty(car.getBizOrgName()) && !ObjectUtils.isEmpty(car.getBizOrgCode())) {
            FeignClientResult<Map<String, Object>> result = Privilege.companyClient.queryByOrgcode(car.getBizOrgCode());
            System.out.println("==============================" + JSONObject.toJSONString(result.getResult()));
            if (result.getResult() != null && result.getResult().containsKey("compnay")) {
                Map<String, String> map = (Map<String, String>) result.getResult().get("compnay");
                car.setBizOrgName(map.get("companyName"));
            }
        }
        Car car2 = iCarService.saveOne(car);
        CarController controllerProxy = SpringUtils.getBean(CarController.class);
        controllerProxy.refreshAllCount();
        return car2;
    }

//    @Async
//    public void refreshCount(String... bizOrgCodes) {
//        try {
//            // 刷新分类数量缓存
//            iCarService.refreshStaData();
//            // 去重逻辑,目的时资源调整归属单位后 新单元和就单位都刷新单位分类数量统计
//            Set<String> repeatBizOrgCodes = new HashSet<>(Arrays.asList(bizOrgCodes));
//            repeatBizOrgCodes.forEach(bizOrgCode -> {
//                fireFightingSystemServiceImpl.refreshCarTypeAndCount(bizOrgCode);
//            });
//        } catch (Exception e) {
//            log.error("刷新车辆分类树缓存失败" + e.getMessage());
//        }
//    }

//    @Async
//    public void refreshCount(List<Car> list) {
//        list.forEach(i -> {
//            iCarService.refreshStaData();
//            try {
//                fireFightingSystemServiceImpl.refreshCarTypeAndCount(i.getBizOrgCode());
//            } catch (Exception e) {
//                log.error("刷新车辆分类树缓存失败" + e.getMessage());
//            }
//        });
//    }



    @Async("equipAsyncExecutor")
    public void refreshAllCount() {
        // 清空单位装备分类树缓存
        redisUtils.getAndDeletePatternKeys(carTypeAndCount + "*");
        // 清空车辆分类树缓存
        redisUtils.getAndDeletePatternKeys(equipTypeAndCount + "*");
        redisUtils.getAndDeletePatternKeys("iotTypeAndCount" + "*");
        // 清空单位分类数量统计缓存
        redisUtils.getAndDeletePatternKeys(SourcesStatisticsImpl.PREFIX_CATEGORY_COUNT + "*");
        // 刷新装备单位分类数量缓存
        iSourceStatistics.initAllCategoryStatisticsData(SourceTypeEnum.EQUIPMENT);
        // 刷新车辆单位分类数量缓存
        iSourceStatistics.initAllCategoryStatisticsData(SourceTypeEnum.CAR);

        iSourceStatistics.initAllCategoryStatisticsData(SourceTypeEnum.IOT);
    }


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

    /**
     * 编辑消防车
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @Transactional
    @ApiOperation(httpMethod = "PUT", value = "编辑车辆信息(<font color='blue'>release</font>)", notes = "编辑车辆信息")
    @PostMapping(value = "/update", produces = "application/json;charset=UTF-8")
    public Car updateCar(@ApiParam(value = "车辆对象", required = true) @RequestBody Car car) {
//		Car car = iCarService.getById(carRequest.getCar().getId());
//		if (null == car) {
//			return new CommonResponse(FAILED, "未查询到该车辆！");
//		}
//		CarInfo carInfo = carRequest.getCarInfo();
//		Car carInstance = carRequest.getCar();
//		carInstance.setDateCreated(car.getDateCreated());
//		carInstance.setCarCode(car.getCarCode());
//		carInstance.setImUsername(car.getImUsername());
//		carInstance.setImPassword(car.getImPassword());
//		Set<CarProperty> carpList = carRequest.getCarPropertyList();
//		carInstance = iCarService.saveCar(getUserInfo(), carInstance, carInfo, carpList);
        // saveFile(carInstance);视频图片文件后期统一处理

        String iotCode = car.getIotCode();
        if(StringUtil.isNotEmpty(iotCode) && StringUtils.isNotEmpty(iotCode.trim())){
            Car ar= carMapper.getCarsByIotCodeExcludeCarId(car.getIotCode(),car.getId());
            if(ar != null){
                throw new BadRequest("物联编码重复");
            }
            if(StringUtils.isNotEmpty(haveUsedIotPrefix) && Arrays.stream(haveUsedIotPrefix.split(",")).anyMatch(iotCode::startsWith)){
                throw new BadRequest("物联编码航班已占用");
            }
        }



        //用来解绑车辆
        if (!ObjectUtils.isEmpty(car.getTeamId())){
            jcsFeign.getUserCar(car.getId(),car.getTeamId());
        }
        if (ObjectUtils.isEmpty(car.getName())) {
            Equipment equipment = iEquipmentService.getById(car.getEquipmentId());
            car.setName(equipment != null ? equipment.getName() : null);
        }
        if (ObjectUtils.isEmpty(car.getBizOrgName()) && !ObjectUtils.isEmpty(car.getBizOrgCode())) {
            FeignClientResult<Map<String, Object>> result = Privilege.companyClient.queryByOrgcode(car.getBizOrgCode());
            System.out.println("==============================" + JSONObject.toJSONString(result.getResult()));
            if (result.getResult() != null && result.getResult().containsKey("compnay")) {
                Map<String, String> map = (Map<String, String>) result.getResult().get("compnay");
                car.setBizOrgName(map.get("companyName"));
            }
        }
        Car car1 = iCarService.updateOneById(car);
        CarController controllerProxy = SpringUtils.getBean(CarController.class);
        controllerProxy.refreshAllCount();
        return car1;
    }

    /**
     * 根据id删除
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    public CommonResponse deleteById(@ApiParam(value = "车辆管理id", required = true) @RequestParam("ids") String... ids) {
        List<String> idStrings = Arrays.asList(ids);
        QueryWrapper<EquipmentOnCar> queryWrapper = new QueryWrapper<EquipmentOnCar>();
        queryWrapper.lambda().in(EquipmentOnCar::getCarId, idStrings);
        List<EquipmentOnCar> result = iEquipmentOnCarService.list(queryWrapper);
        if (!result.isEmpty()) {
            return new CommonResponse(FAILED, "无法删除已有车载装备的数据！");
        } else {
            boolean b = iCarService.removeByIds(idStrings);
            // AST数据同步
            if (b && syncSwitch) {
                List<Long> carIds = idStrings.stream().map(id -> Long.parseLong(id.trim()))
                        .collect(Collectors.toList());
                syncDataService.syncDeletedFireVehicle(carIds);
                iCarService.dataSyncDeletedIds(carIds);
            }
            CarController controllerProxy = SpringUtils.getBean(CarController.class);
            controllerProxy.refreshAllCount();
            return new CommonResponse(SUCCESS);
        }
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public Car selectById(HttpServletRequest request, @PathVariable Long id) {
        return iCarService.selectOneById(id);
    }

    /**
     * 电建项目-车辆信息详情（表单组件格式导致白屏修复）
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "getMessage/{id}", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public CarMessage getMessage(HttpServletRequest request, @PathVariable Long id) {
        CarMessage carMessage = new CarMessage();
        Car car = iCarService.selectOneById(id);
        BeanUtils.copyProperties(car, carMessage, "img");
        ArrayList<CommonFile> commonFiles = new ArrayList<>();
        car.getImg().forEach(item -> {
            CommonFile commonFile = new CommonFile();
            BeanUtils.copyProperties(item, commonFile);
            commonFiles.add(commonFile);
        });
        ArrayList<CommonFile> certifications = new ArrayList<>();
        car.getCertification().forEach(item -> {
            CommonFile commonFile = new CommonFile();
            BeanUtils.copyProperties(item, commonFile);
            certifications.add(commonFile);
        });
        carMessage.setImg(commonFiles);
        carMessage.setCertification(certifications);
        return carMessage;
    }

    /**
     * 根据id查询
     *
     * @param carIds
     * @return
     */
    @RequestMapping(value = "/peoperty", method = RequestMethod.POST)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "根据id查询", notes = "根据id查询")
    public Map<String, Object>  getCarPropertyByCarIds(@RequestBody List<Long> carIds) {
        return iCarPropertyService.getCarPropertyByCarIds(carIds);
    }

    /**
     * 根据id查询车辆详情信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/getCarDetailById/{id}", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public Car getCarDetailById(HttpServletRequest request, @PathVariable Long id) {
        return iCarService.getCarDetailById(id);
    }

    /**
     * 根据车辆id查询车辆详情信息，供iot_tree展示
     *
     * @param carNum
     * @return
     */
    @RequestMapping(value = "/threeDimensional/getCarDetailById/{id}", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据车辆id查询", notes = "根据车辆id查询")
    public CarForUE4VO getCarDetailByCarNumToThreeDimensional(HttpServletRequest request, @PathVariable Long id) {
        String orgCode = getOrgCode();
        return iCarService.getCarDetailByCarNumToThreeDimensional(id, orgCode);
    }

    /**
     * 根据车牌号查询车辆详情信息
     *
     * @param carNum
     * @return
     */
    @RequestMapping(value = "/getCarDetailByCarNum/{carNum}", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据车牌号查询", notes = "根据车牌号查询")
    public Car getCarDetailByCarNum(HttpServletRequest request, @PathVariable String carNum) {
        String orgCode = getOrgCode();
        return iCarService.getCarDetailByCarNum(carNum, orgCode);
    }

    /**
     * 列表分页查询
     *
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
    public IPage<Car> listPage(String pageNum, String pageSize, Car car) {

        Page<Car> pageBean;
        QueryWrapper<Car> carQueryWrapper = new QueryWrapper<>();
        Class<? extends Car> aClass = car.getClass();
        Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
            try {
                field.setAccessible(true);
                Object o = field.get(car);
                if (o != null) {
                    Class<?> type = field.getType();
                    String name = NameUtils.camel2Underline(field.getName());
                    if (type.equals(Integer.class)) {
                        Integer fileValue = (Integer) field.get(car);
                        carQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(Long.class)) {
                        Long fileValue = (Long) field.get(car);
                        carQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(String.class)) {
                        String fileValue = (String) field.get(car);
                        carQueryWrapper.eq(name, fileValue);
                    } else {
                        String fileValue = (String) field.get(car);
                        carQueryWrapper.eq(name, fileValue);
                    }
                }
            } catch (Exception e) {
            }
        });
        IPage<Car> page;
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            pageBean = new Page<>(0, Long.MAX_VALUE);
        } else {
            pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        }
        page = iCarService.page(pageBean, car);
        return page;
    }

    /**
     * http://172.16.11.15:8080/carmanager/create
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "创建车辆初始化(<font color='blue'>release</font>)", notes = "创建车辆初始化")
    @GetMapping(value = "/init", produces = "application/json;charset=UTF-8")
    public CommonResponse createInit() {
        List<SystemDic> carStatusList = iSystemDicService.findAllByType(SystemDicTypeEum.carState.getType());
        List<SystemDic> dropDownPerformance = iSystemDicService.findAllByType(SystemDicTypeEum.perfQuotaType.getType());
        Map<String, Object> result = new HashMap<>();
        result.put("performances", dropDownPerformance);
        result.put("carStatus", carStatusList);
        return new CommonResponse(SUCCESS, result);

    }

    /**
     * <pre>
     * 获取车辆国别数据
     * </pre>
     *
     * @return CommonResponse
     * @throws @version: 1.0
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取车辆国别数据(<font color='blue'>release</font>)", notes = "获取车辆国别数据")
    @RequestMapping(value = "/countrys", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public CommonResponse getCountrys() {
        List<SystemDic> countryList = iSystemDicService.findAllByType(SystemDicTypeEum.country.getType());
        return new CommonResponse(SUCCESS, countryList);
    }

    /**
     * <pre>
     * 车辆分类列表
     * </pre>
     *
     * @return CommonResponse
     * @throws @version: 1.0
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "车辆分类列表(<font color='blue'>release</font>)", notes = "按装备分类，获取该分类下级树")
    @RequestMapping(value = "/query/carCategory", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public CommonResponse queryCarCategory() {

        List<EquipmentCategory> results = iCarService.getCarCategory();
        List<EquipmentCategory> list = new ArrayList<>();
        for (EquipmentCategory instance : results) {
            if (instance.getParentId() == null || instance.getLevel().equals("1")) {
                list.add(instance);
            } else {
                getChildren(list, instance.getParentId().toString()).add(instance);
            }
        }
        return new CommonResponse(SUCCESS, list);

    }

    /**
     * 根据装备分类list，递归找到对应的分类子集。
     *
     * @param list
     * @param id
     * @return
     */
    private List<EquipmentCategory> getChildren(List<EquipmentCategory> list, String id) {
        List<EquipmentCategory> temp = null;
        for (EquipmentCategory instance : list) {
            if (instance.getId() != null && !instance.getId().toString().equals(id)) {
                temp = getChildren(instance.getChildren(), id);
                if (null != temp) {
                    break;
                }
            } else {
                instance.setHasLowerClassification(true);
                temp = instance.getChildren();
                break;
            }
        }
        return temp;

    }

    /**
     * 获取损耗车辆列表
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "装备药剂的车辆列表-APP", notes = "装备药剂的车辆列表")
    @RequestMapping(value = "/queryExtinguishantOnCarlist", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public List<Map<String, Object>> queryExtinguishantOnCarlist() {
        try {
            ArrayList<String> strings = new ArrayList<>();
            strings.add(CarStatusEnum.WX.getCode());
            strings.add(CarStatusEnum.TY.getCode());
            strings.add(CarStatusEnum.BF.getCode());
            List<Map<String, Object>> list = extinguishantOnCarMapper.queryExtinguishantOnCarlist(strings);
            return list;
        } catch (Exception e) {
            throw new RuntimeException("查询异常！");
        }
    }

    /**
     * 获取车辆车载
     *
     * @param carId
     * @param pageNum
     * @param pageSize
     * @param code
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取车辆装载灭火药剂(<font color='blue'>release</font>)", notes = "获取车辆装载")
    @RequestMapping(value = "/car/extinguishants", method = RequestMethod.GET)
    public Page getCarExtinguishants(Long carId, String pageNum, String pageSize, String code) {
        try {

            if (code != null && !"".equals(code)) {
                code = code.substring(0, 2);
            }
            Page pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
            List<Map<String, Object>> list = extinguishantOnCarMapper.getCarExtinguishants(null, carId,
                    pageBean.offset(), pageBean.getSize(), code);
            int count = extinguishantOnCarMapper.getCarExtinguishantscount(null, carId, code);
            if (list != null && list.size() > 0) {
                for (Map<String, Object> map : list) {
                    String img = (String) map.get("img");
                    if (img != null && !"".equals(img)) {
                        map.put("img", img);
                    }
                }
            }
            pageBean.setTotal(count);
            pageBean.setRecords(list);
            return pageBean;

        } catch (Exception e) {
            throw new RuntimeException("查询异常！");
        }
    }

    // 车辆灭火药剂损耗
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "损耗车载灭火剂(<font color='blue'>release</font>)", notes = "损耗车载灭火剂")
    @RequestMapping(value = "/{carId}/loss-extinguishants", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public Map<String, String> lossCarExtinguishants(
            @ApiParam(value = "车辆Id", required = true) @PathVariable(value = "carId") String carId,
            @ApiParam(value = "灭火剂损耗请求条件", required = false) @RequestBody(required = false) List<ExtinguishantLossRequest> requests) {
        try {
            return iCarService.lossExtinguishants(Long.valueOf(carId), requests);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("车载灭火药剂损耗失败，请联系管理员！");
        }
    }

    /**
     * 根据车辆id，查询车辆信息
     **/
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据车辆id，查询车辆信息(<font color='blue'>release</font>)", notes = "根据车辆id，查询车辆信息")
    @RequestMapping(value = "/cars/{id}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public CarInfosResponse show(@ApiParam(value = "车辆管理id", required = true) @PathVariable Long id) {
        try {
            Car car = iCarService.getById(id);
            if (null == car) {
                throw new RuntimeException("该车辆不存在!");
            }
            Map<String, Object> columnMap = new HashMap<>();
            columnMap.put("car_id", car.getId());
            List<CarProperty> carPropertyList = carPropertyMapper.selectByMap(columnMap);
            return this.createCarInfosResponse(car, carPropertyList);
        } catch (Exception e) {
            throw new RuntimeException("查询异常！");
        }
    }

    public CarInfosResponse createCarInfosResponse(Car car, List<CarProperty> carPropertyList) {

        CarInfosResponse response = new CarInfosResponse();
        // 根据车辆获取装备信息
        Equipment equipment = equipmentMapper.selectById(car.getEquipmentId());
        // 分类
        EquipmentCategory equipmentCategory = equipmentCategoryMapper.selectById(equipment.getCategoryId());
        // 生产商
        ManufacturerInfo manufacturerInfo = manufacturerInfoMapper.selectById(car.getManufacturerId());
        ParsePropertyUtil.setting(response::setManufacturerInfo, () -> manufacturerInfo);
        // 等级
        // 国别
        SystemDic systemDic1 = systemDicMapper.selectById(car.getCountry());
        // 车牌类型
        // 车辆状态
        SystemDic systemDic3 = systemDicMapper.selectById(car.getCarState());

        ParsePropertyUtil.setting(response::setCarPropertyList, () -> createCarPropertyList(carPropertyList));
        ParsePropertyUtil.setting(response::setId, () -> car.getId().toString());
        ParsePropertyUtil.setting(response::setCarNum, car::getCarNum);
        ParsePropertyUtil.setting(response::setCarState, () -> systemDic3.getName());
        ParsePropertyUtil.setting(response::setEquipType, () -> equipmentCategory.getCode());
        ParsePropertyUtil.setting(response::setEquipTypeName, () -> equipmentCategory.getName());
        ParsePropertyUtil.setting(response::setEquipName, () -> equipment.getName());
        ParsePropertyUtil.setting(response::setEquipCode, () -> equipment.getCode());
        ParsePropertyUtil.setting(response::setEquipmentId, () -> car.getEquipmentId());
        // ParsePropertyUtil.setting(response::setStandard, car::getStandard);
        ParsePropertyUtil.setting(response::setOrgCode, car::getOrgCode);
        ParsePropertyUtil.setting(response::setManufacturer, () -> manufacturerInfo.getName());
        ParsePropertyUtil.setting(response::setManufacturerId, () -> manufacturerInfo.getId());
        ParsePropertyUtil.setting(response::setRemark, car::getRemark);
        ParsePropertyUtil.setting(response::setCompanyName, () -> car.getCompanyName());
        ParsePropertyUtil.setting(response::setCountry, () -> systemDic1.getName());
        ParsePropertyUtil.setting(response::setBrand, car::getBrand);
        ParsePropertyUtil.setting(response::setChassisBrand, car::getChassisBrand);
        // 车牌类型
        ParsePropertyUtil.setting(response::setQrCode, car::getQrCode);
        ParsePropertyUtil.setting(response::setImg, () -> car.getImg().get(0).getUrl());
        ParsePropertyUtil.setting(response::setFilm, () -> car.getVideo().get(0).getUrl());
        ParsePropertyUtil.setting(response::setDefaultImg, () -> equipment.getImg());
        // ParsePropertyUtil.setting(response::setChassisType, car::getChassisType);
        // ParsePropertyUtil.setting(response::setChassisCountry,
        // car::getChassisCountry);
        return response;
    }

    private List<CarProperty> createCarPropertyList(List<CarProperty> carPropertyList) {
        List<CarProperty> carProList = new ArrayList<CarProperty>();
        if (!carPropertyList.isEmpty()) {
            carPropertyList.forEach(action -> {
//				PerfQuotaDefinition perfQuotaDefinition = perfQuotaDefinitionMapper
//						.selectById(action.getPerfQuotaDefinitionId());
                CarProperty carProperty = new CarProperty();
                carProperty.setId(action.getId());
                carProperty.setCarId(action.getCarId());
//				carProperty.setPerfQuotaDefinitionId(action.getPerfQuotaDefinitionId());
//				carProperty.setPerfQuotaDefinitionName(perfQuotaDefinition.getName());
                carProperty.setRemark(action.getRemark());
                carProperty.setValue(action.getValue());
                EquipmentIndex equipmentIndex = equipmentIndexMapper.selectById(action.getEquipmentIndexId());
                if (equipmentIndex.getUnitName() != null) {
                    carProperty.setUnitName(equipmentIndex.getUnitName());
                }
                carProList.add(carProperty);
            });
        }
        return carProList;
    }

    /*
     * 向车辆上装载灭火药剂
     *
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "向车辆上装载灭火药剂(<font color='blue'>release</font>)", notes = "向车辆上装载灭火药剂")
    @RequestMapping(value = "/{carId}/loading-extinguishant", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public Map<String, String> loadingExtinguishant(
            @ApiParam(value = "车辆Id", required = true) @PathVariable(value = "carId") Long carId,
            @ApiParam(value = "灭火药剂明细账列表", required = true) @RequestBody List<ExtinguishantRequeset> extinguishants) {
        try {
            return iCarService.loadingExtinguishants(carId, extinguishants);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 装卸载装备
     **/
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "装卸载装备(<font color='blue'>release</font>)", notes = "装载装备")
    @RequestMapping(value = "/loading-equipments", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public Map<String, Object> loadingEquipment(
            @ApiParam(value = "提交的装备", required = true) @RequestBody(required = true) OnBoardEquipment params) {
        try {
            if (OnBoardEquipmentEnum.LOAD == OnBoardEquipmentEnum.getEnum(params.getType())) {
                iCarService.loadingEquipment(params, getUserInfo());
            } else if (OnBoardEquipmentEnum.UNLOAD == OnBoardEquipmentEnum.getEnum(params.getType())) {
                iCarService.unloadEquipment(params, getUserInfo());
            } else {
                throw new RuntimeException("参数传入失败！无法进行装备装卸车！");
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("person", getUserInfo().getRealName());
            map.put("time", DateUtils.getNowStrLong());
            return map;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    // 获取九大类
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "装卸载装备(<font color='blue'>release</font>)", notes = "装载装备")
    @RequestMapping(value = "/getEquipmentType", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public List<EquipmentCategory> getEquipmentType() {
        try {

            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.isNull("parent_id");
            queryWrapper.eq("industry_code", IndustryEnum.EQUIP.getCode());
            List<EquipmentCategory> list = equipmentCategoryMapper.selectList(queryWrapper);
            return list;
        } catch (Exception e) {
            throw new RuntimeException("系统异常！");
        }
    }
    // 获取九大类二级统计

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取九大类二级统计")
    @RequestMapping(value = "/getEquipmentTypeCount/{id}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public List<Map<String, Object>> getEquipmentTypeCount(@PathVariable(value = "id") Long id,
                                                           String warehouseStructureId, String standard, String StateName, String brand) {
        try {

            QueryWrapper<EquipmentCategory> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parent_id", id);
            queryWrapper.eq("industry_code", IndustryEnum.EQUIP.getCode());
            List<EquipmentCategory> list = equipmentCategoryMapper.selectList(queryWrapper);
            String type = list.get(0).getCode().substring(0, 1);
            // 获取二级code前两位
            List<String> listd = new ArrayList<>();
            List<Map<String, Object>> listr = new ArrayList<>();
            for (EquipmentCategory equipmentCategory : list) {
                listd.add(equipmentCategory.getCode().substring(0, 2));
                Map<String, Object> map = new HashMap<>();
                map.put("name", equipmentCategory.getName());
                map.put("ercode", equipmentCategory.getCode().substring(0, 2));
                map.put("amount", 0);
                if ("21".equals(equipmentCategory.getCode().substring(0, 2))) {
                    map.put("type", "car");
                } else {
                    map.put("type", "equipment");
                }
                listr.add(map);
            }
            Map<String, Object> mape = new HashMap<>();
            mape.put("ids", listd);
            mape.put("id", id);
            mape.put("warehouseStructureId", warehouseStructureId);
            mape.put("standard", standard);
            mape.put("StateName", StateName);
            mape.put("brand", brand);
            // 根据二级分类查询统计
            List<Map<String, Object>> listdate = equipmentCategoryMapper.getEquipCategoryListcount(mape);
            mape.clear();
            for (Map<String, Object> map : listr) {
                mape.putAll(map);
                for (Map<String, Object> map1 : listdate) {
                    if (map.get("ercode").toString().equals(map1.get("ercode").toString())) {
                        if (type.equals("4")) {
                            map.put("amount", map1.get("amount"));
                        } else {
                            double dou = Double.parseDouble(map1.get("amount").toString());
                            int i = new Double(dou).intValue();
                            map.put("amount", i);
                        }
                        map.put("type", map1.get("type"));
                    }
                }
            }
            return listr;
        } catch (Exception e) {
            System.err.println(e.getMessage());
            throw new RuntimeException("系统异常！");
        }
    }

    // 三级按模板名称统计
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取九大类二级统计")
    @RequestMapping(value = "/getEquipmentCount/{ercode}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public List<Map<String, Object>> getEquipmentCount(@PathVariable(value = "ercode") String ercode,
                                                       String warehouseStructureId, String standard, String StateName, String brand) {
        try {
            List<Map<String, Object>> listdate = null;
            Map<String, Object> mape = new HashMap();
            mape.put("ercode", ercode);
            mape.put("warehouseStructureId", warehouseStructureId);
            mape.put("standard", standard);
            mape.put("StateName", StateName);
            mape.put("brand", brand);
            listdate = equipmentCategoryMapper.getEquipmentCount(mape);
            for (Map<String, Object> map : listdate) {
                map.put("img", map.get("img"));
                Object amount = map.get("amount");
                String unit = map.get("unit").toString();
                if (ercode.substring(0, 1).equals("4")) {
                    map.put("amount", map.get("amount").toString() + " " + map.get("unit").toString());
                } else {
                    double dou = Double.parseDouble(map.get("amount").toString());
                    int i = new Double(dou).intValue();
                    map.put("amount", i + " " + map.get("unit").toString());
                }
            }
            return listdate;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("系统异常！");
        }
    }

    // 九大类详情列表
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "详情列表")
    @RequestMapping(value = "/getEquipmentlist/{ercode}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public List<Map<String, Object>> getEquipmentlist(@PathVariable(value = "ercode") String ercode,
                                                      String warehouseStructureId, String standard, String StateName, String brand, String name) {
        try {
            List<Map<String, Object>> listdate = null;
            Map<String, Object> mape = new HashMap();
            mape.put("ercode", ercode);
            mape.put("warehouseStructureId", warehouseStructureId);
            mape.put("standard", standard);
            mape.put("StateName", StateName);
            mape.put("brand", brand);
            mape.put("name", name);
            listdate = equipmentCategoryMapper.getDetailed(mape);
            for (Map<String, Object> map : listdate) {
                String utname = map.get("utname").toString();
                String eqCode = map.get("ercode").toString();
                String amount = map.get("amount").toString();
                if (StringUtil.isNotEmpty(eqCode) && !eqCode.startsWith("4")) {
                    amount = amount.split("\\.")[0] + utname;
                } else {
                    amount = amount + utname;
                }
                map.put("amount", amount);
                map.put("img", map.get("img"));
            }
            return listdate;
        } catch (Exception e) {
            throw new RuntimeException("系统异常！");
        }
    }

    // 三级按模板名称统计
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取九大类二级统计")
    @RequestMapping(value = "/getCarList/{ercode}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public IPage<Car> getCarList(@PathVariable(value = "ercode") String ercode, String orgcode, Car car, String
            pageNum,
                                 String pageSize) {
        Page<Car> pageBean;
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            pageBean = new Page<>(0, Long.MAX_VALUE);
        } else {
            pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        }
        return iCarService.getCarList(ercode, orgcode, car, pageBean);
    }

    /**
     * 车辆装备品牌 下拉框
     **/
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "车辆装备品牌 下拉框")
    @RequestMapping(value = "/getbrandlist/{type}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public List<String> getbrandlist(@PathVariable(value = "type") String type, String name) {
        List<String> result = new ArrayList<String>();

        if ("car".equals(type)) {
            QueryWrapper<Car> queryWrapper = new QueryWrapper<Car>();
            queryWrapper.ne("brand", "");
            queryWrapper.isNotNull("brand");
            if (name != null && !"".equals(name)) {
                queryWrapper.like("brand", name);
            }
            List<Car> list = carMapper.selectList(queryWrapper.groupBy("brand"));
            for (Car car : list) {
                result.add(car.getBrand());
            }
            return result;
        } else {
            QueryWrapper<EquipmentDetail> queryWrapper = new QueryWrapper<EquipmentDetail>();
            queryWrapper.ne("brand", "");
            queryWrapper.isNotNull("brand");
            if (name != null && !"".equals(name)) {
                queryWrapper.like("brand", name);
            }
            List<EquipmentDetail> list = equipmentDetailMapper.selectList(queryWrapper.groupBy("brand"));
            for (EquipmentDetail equipmentDetail : list) {
                result.add(equipmentDetail.getBrand());
            }
            return result;
        }
    }

    /**
     * 车辆装备状态
     **/
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "车辆装备状态")
    @RequestMapping(value = "/getStatuslist/{type}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public List<SystemDic> getStatuslist(@PathVariable(value = "type") String type) {
        try {

            Map<String, Object> columnMap = new HashMap<String, Object>();
            if ("car".equals(type)) {
                columnMap.put("type", SystemDicTypeEum.carState.getType());
                List<SystemDic> listd = systemDicMapper.selectByMap(columnMap);
                return listd;
            } else {
                columnMap.put("type", SystemDicTypeEum.equipStatus.getType());
                List<SystemDic> listd = systemDicMapper.selectByMap(columnMap);
                return listd;
            }

        } catch (Exception e) {
            throw new RuntimeException("系统异常！");
        }
    }

    /**
     * 规格型号
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "规格型号")
    @RequestMapping(value = "/getstandardlist/{type}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public List<String> getstandardlist(@PathVariable(value = "type") String type, String name) {
        try {

            List<String> result = new ArrayList<String>();
            if ("car".equals(type)) {
                QueryWrapper<Car> queryWrapper = new QueryWrapper<Car>();
                queryWrapper.ne("model", "");
                queryWrapper.isNotNull("model");
                if (name != null && !"".equals(name)) {
                    queryWrapper.like("model", name);
                }
                List<Car> list = carMapper.selectList(queryWrapper.groupBy("model"));
                for (Car car : list) {
                    result.add(car.getStandard());
                }
                return result;
            } else {
                QueryWrapper<EquipmentDetail> queryWrapper = new QueryWrapper<EquipmentDetail>();
                queryWrapper.ne("standard", "");
                queryWrapper.isNotNull("standard");
                if (name != null && !"".equals(name)) {
                    queryWrapper.like("standard", name);
                }
                List<EquipmentDetail> list = equipmentDetailMapper.selectList(queryWrapper.groupBy("standard"));
                for (EquipmentDetail equipmentDetail : list) {
                    result.add(equipmentDetail.getStandard());
                }
                return result;
            }

        } catch (Exception e) {
            throw new RuntimeException("系统异常！");
        }
    }

    /**
     * <pre>
     * 打印车辆二维码
     * </pre>
     *
     * @param id     车辆ID
     * @param amount 打印数量
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "打印车辆二维码(<font color='blue'>release</font>)", notes = "打印车辆二维码")
    @RequestMapping(value = "/generate/qrCode/{type}/{id}/{amount}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public List<EquipmentQrcode> printQRCode(@PathVariable("id") Long id, @PathVariable("amount") Integer amount,
                                             @PathVariable("type") String type, @DateTimeFormat(pattern = "yyyy-MM-dd") Date productDate) {
        try {
            ProductionQRCode productionQRCode = messageHandMap.get(type);
            List<EquipmentQrcode> list = productionQRCode.getProductionQRCode(id, amount, productDate);
            return list;
        } catch (Exception e) {
            throw new RuntimeException("系统异常！");
        }
    }

    /**
     * 批量删除
     *
     * @param idList
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    public boolean delete(HttpServletRequest request, @RequestBody List<Long> idList) throws Exception {

        List<Car> cars = iCarService.list(new QueryWrapper<Car>().in("id", idList));
        cars.forEach(car -> {
            List<EquipmentOnCarAppVO> equipmentOnCarAppVOS = carMapper.selectEquipmentOnCarAppList(car.getId());
            if (equipmentOnCarAppVOS.size() > 0) {
                throw new BadRequest("有车载装备的车辆不能删除，请先卸载装备！");
            }
        });
        boolean flag = iCarService.removeOneByIds(idList);
        if (flag) {
            CarController controllerProxy = SpringUtils.getBean(CarController.class);
            controllerProxy.refreshAllCount();
        }
        return flag;
    }

    /**
     * 获取车辆物联信息
     *
     * @return
     */
    @RequestMapping(value = "/getCarsIotInfo", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取车辆物联信息", notes = "获取车辆物联信息")
    public Map<Long, List<CarIndexVo>> getCarsIotInfo() {
        Map<Long, List<CarIndexVo>> map = null;
//        String orgCode = getOrgCode();

        ReginParams ReginParams=getSelectedOrgInfo();
        String   orgCode= ReginParams.getPersonIdentity().getBizOrgCode();

        List<CarIndexVo> carVoList = iCarService.getCarsIotInfo(orgCode);
        if (!carVoList.isEmpty()) {
            map = carVoList.stream().collect(Collectors.groupingBy(vo -> vo.getId()));
        }
        return map;
    }

    /**
     * 根据车辆ID，获取车载装备及状态
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/getCarEquipmentsById/{id}/state", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取车辆车载装备状态", notes = "获取车辆车载装备状态")
    public List<EquipStateOnCarVo> getCarEquipmentsById(@PathVariable(value = "id") Long id) {
        return iCarService.getCarEquipmentsById(id);
    }

    /**
     * <pre>
     * 车辆历史轨迹数据
     * </pre>
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "模拟车辆历史轨迹数据(<font color='blue'>release</font>)", notes = "模拟车辆历史轨迹数据")
    @RequestMapping(value = "/history/{iotCode}/{timeStart}/{timeEnd}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public ResponseModel getCarHistoryTrackAndTrendById(@PathVariable("iotCode") String iotCode,
                                                        @PathVariable("timeStart") String timeStart, @PathVariable("timeEnd") String timeEnd) {
        String prefix = null;
        String suffix = null;
        if (iotCode.length() > 8) {
            prefix = iotCode.substring(0, 8);
            suffix = iotCode.substring(8);
        } else {
            return CommonResponseUtil.failure("车辆物联编码错误，请确认！");
        }
        LonAndLatEntityVo lonAndLatEntityVo = new LonAndLatEntityVo();
        String url = iotServerName;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Content-Type", "application/json");
        headers.set("product", getProduct());
        headers.set("token", getToken());
        headers.set("appKey", getAppKey());
        HttpEntity httpEntity = new HttpEntity<>(lonAndLatEntityVo, headers);
        ResponseEntity<FeignClientResult> feignClientResult = null;
        try {
            feignClientResult = restTemplate.exchange(
                    "http://" + url + "/iot/v1/livedata/list?timeStart=" + timeStart + "&timeEnd=" + timeEnd
                            + "&productKey=" + prefix + "&deviceName=" + suffix,
                    HttpMethod.GET, httpEntity, FeignClientResult.class);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        if (null != feignClientResult && feignClientResult.getBody().getStatus() == 200) {
            return CommonResponseUtil.success(feignClientResult.getBody().getResult());
        } else {
            log.error("注：iotCode为 (" + iotCode + ") 的车辆不存在于物联系统或物联系统车辆历史轨迹接口出错！");
            return CommonResponseUtil.success();
        }
    }

    /**
     * <pre>
     * 模拟车辆历史运动趋势数据
     * </pre>
     */
//	    @TycloudOperation(ApiLevel = UserType.AGENCY)
//	@RequestMapping(value = "/history/trend/{iotCode}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
//	public List<SpeedAndTimeEntityVo> getCarHistoryTrendById(@PathVariable("iotCode") String iotCode) {
//		try {
//			List<SpeedAndTimeEntityVo> list = iCarLonAndLatDataService.listCarSpeedAndGround();
//			return list;
//		} catch (Exception e) {
//			throw new RuntimeException("系统异常！");
//		}
//	}

    /**
     * 查询车辆-共共接口
     *
     * @param teamId 队伍id
     * @param name   车辆名称
     * @return List<CarInfoVo>
     */
    @GetMapping(value = "/list-all")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "车辆列表", notes = "车辆列表")
    public List<CarInfoDto> equipmentList(@RequestParam(required = false) Long teamId,
                                          @RequestParam(required = false) String name) {
        return iCarService.carInfoList(teamId, name);
    }

    /**
     * 查询车辆-共共接口
     *
     * @param teamId 队伍id
     * @param name   车辆名称
     * @return List<CarInfoVo>
     */
    @GetMapping(value = "/list-allpag")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "车辆列表", notes = "车辆列表")
    public Page<CarInfoDto> equipmentCarList(@RequestParam(required = false) Long teamId,
                                             @RequestParam(required = false) String name, @RequestParam(required = false) String code,
                                             @RequestParam(required = false) String pageNum, @RequestParam(required = false) String pageSize,
                                             @RequestParam(required = false) Long id, @RequestParam(required = false) Boolean isNo

    ) {
        Page<CarInfoDto> pageBean;
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            pageBean = new Page<>(0, Long.MAX_VALUE);
        } else {
            pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        }

        return iCarService.equipmentCarList(pageBean, teamId, name, code, id, isNo);
    }

    /**
     * 机场查询队伍与车辆数量
     *
     * @return List<Map < String, Object>>
     */
    @GetMapping(value = "/list-info")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "队伍与车辆数量", notes = "队伍与车辆数量")
    public List<Map<String, Object>> carList() {
        return iCarService.teamCarList();
    }

    @PostMapping(value = "/status")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "更新车辆状态", notes = "更新车辆状态")
    public ResponseModel updateCarStatus(@RequestBody List<CarStatusInfoDto> cars) {
        return ResponseHelper.buildResponse(iCarService.updateCarStatus(cars));
    }

    /**
     * 获取消防队伍的消防车辆
     *
     * @param id 队伍ID，非必填
     * @return
     */
    @GetMapping(value = "/getTeamCarList")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取消防队伍的消防车辆", notes = "获取消防队伍的消防车辆")
    public ResponseModel getTeamCarList(@RequestParam(required = false) Long id,
                                        @RequestParam(required = false) String sequenceNbr,
                                        @RequestParam(required = false) Double longitude, @RequestParam(required = false) Double latitude) {
        return CommonResponseUtil.success(iCarService.getTeamCarList(sequenceNbr,id, longitude, latitude));
    }

    /**
     * 根据id查询车辆简要信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/simple/{id}", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据id查询车辆简要信息", notes = "根据id查询车辆简要信息")
    public Car selectById(@PathVariable Long id) {
        return iCarService.querySimpleInfoById(id);
    }

    /**
     * 根据查询车辆简要信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/state/info", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(value = "根据车牌号查询车辆信息", notes = "根据车牌号查询车辆信息")
    public ResponseModel getCarStateInfoByCarNum(@RequestParam(required = false) String carNum) {
        return CommonResponseUtil.success(iCarService.getCarStateInfoByCarNum(carNum));
    }

    /**
     * 查询所有融合终端车辆
     *
     * @return
     */
    @RequestMapping(value = "/all/fusion", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "查询所有融合终端车辆", notes = "查询所有融合终端车辆")
    public ResponseModel<List> getCarFusionList() {
        return CommonResponseUtil.success(iCarService.getCarFusionList());
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/user/companyTreeByUserAndType", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据登录人及类型获取公司部门树", notes = "根据登录人及类型获取公司部门树")
    public ResponseModel<Object> companyTreeByUserAndType() throws Exception {
        FeignClientResult<List<OrgMenuDto>> menusList = jcsFeign.getCompanyDeptTreeWithAuth(carAuthKey, null);
        return ResponseHelper.buildResponse(menusList.getResult());
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/iot/companyTreeByUserAndType", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据登录人及类型获取公司部门树", notes = "根据登录人及类型获取公司部门树")
    public ResponseModel<Object> iotcompanyTreeByUserAndType() throws Exception {
        FeignClientResult<List<OrgMenuDto>> menusList = jcsFeign.getCompanyDeptTreeWithAuth(iotAuthKey, null);
        return ResponseHelper.buildResponse(menusList.getResult());
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getQRCode", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取二维码图片", notes = "获取二维码图片")
    public ResponseModel<Object> getQRCode(long id) throws Exception {
        return ResponseHelper.buildResponse(iCarService.getQRCode(id));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @RequestMapping(value = "/location", method = RequestMethod.GET)
        @ApiOperation(httpMethod = "GET", value = "获取二维码图片", notes = "获取二维码图片")
        public ResponseModel<Object> location() throws Exception {
        return ResponseHelper.buildResponse(iCarService.location());
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @RequestMapping(value = "/getCountOfCar", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "车辆统计-获取车辆总数", notes = "车辆统计-获取车辆总数")
    public Map<String, Integer>  getCountOfCar() {
        return iCarService.getCountOfCar();
    }
    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @RequestMapping(value = "/getCountOfCarBelongCompany", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "车辆统计-获取车辆归属单位总数", notes = "车辆统计-获取车辆归属单位总数")
    public ResponseModel<Integer> getCountOfCarBelongCompany() {
        return CommonResponseUtil.success(iCarService.getCountOfCarBelongCompany());
    }
    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @RequestMapping(value = "/getCarCategoryInfo", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "车辆统计-获取车辆分类用途信息", notes = "车辆统计-获取车辆分类用途信息")
    public List<ChartIntegerDto> getCarCategoryInfo() {
        return iCarService.getCarCategoryInfo();
    }
    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @RequestMapping(value = "/getCarEquipStateInfo", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "车辆统计-获取设备状态信息", notes = "车辆统计-获取设备状态信息")
    public Page<CarEquipStateInfoDto> getCarEquipStateInfo() {
        return iCarService.getCarEquipStateInfo();
    }
    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @RequestMapping(value = "/getCarEquipAlarmInfoDto", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "车辆统计-获取设备告警信息", notes = "车辆统计-获取设备告警信息")
    public Page<CarEquipAlarmInfoDto> getCarEquipAlarmInfoDto() {
        return iCarService.getCarEquipAlarmInfoDto();
    }
    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @RequestMapping(value = "/getCarBelongAreaInfo", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "车辆统计-获取车辆归属信息接口", notes = "车辆统计-获取车辆归属信息接口")
    public List<ChartIntegerDto> getCarBelongAreaInfo() {
        return iCarService.getCarBelongAreaInfo();
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @RequestMapping(value = "/getCarAreaInfo", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "车辆统计-获取片区车辆归属信息接口", notes = "车辆统计-获取片区车辆归属信息接口")
    public Page<CarAreaInfoDto> getCarAreaInfo(@RequestParam String areaName) {
        return iCarService.getCarAreaInfo(areaName);
    }
    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @RequestMapping(value = "/getCarMileageInfoByMoth", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "车辆统计-按照月份统计车辆里程", notes = "车辆统计-按照月份统计车辆里程")
    public Page<MileageDto> getCarMileageInfoByMoth(@RequestParam String date) {
        return iCarService.getCarMileageInfoByMoth(date);
    }
    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @RequestMapping(value = "/exportCarMileageInfoByMoth", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "车辆统计-按照月份统计导出车辆里程", notes = "车辆统计-按照月份统计导出车辆里程")
    public void exportCarMileageInfoByMoth(@RequestParam String date, HttpServletResponse response) {
            List<CarExportDto> list = this.iCarService.exportCarMileageInfoByMoth(date);
            String name = "车辆里程月度统计表-"+date;
            FileHelper.exportExcel(list,name,name,CarExportDto.class,UUID.randomUUID().toString()+".xls",response);
    }
    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @RequestMapping(value = "/getCarMileageInfoByMothOFDay", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "车辆统计-按照月份统计每天的车辆里程", notes = "车辆统计-按照月份统计每天的车辆里程")
    public ZZChartsDto getCarMileageInfoByMothOFDay(@RequestParam String iotCode) {
        return iCarService.getCarMileageInfoByMothOFDay(iotCode);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @RequestMapping(value = "/getCarExcepitonTrack", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "车辆统计-按照日期范围获取异常车辆", notes = "车辆统计-按照日期范围获取异常车辆")
    public Page<CarExceptionDto> getCarExcepitonTrack(@RequestParam Integer type) {
        return iCarService.getCarExcepitonTrack(type);
    }
}
