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

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

import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yeejoin.amos.component.feign.model.FeignClientResult;

import com.yeejoin.amos.patrol.business.dao.mapper.PointInputItemMapper;
import com.yeejoin.amos.patrol.business.dao.mapper.InputItemMapper;
import com.yeejoin.amos.patrol.business.dao.mapper.PointMapper;
import com.yeejoin.amos.patrol.business.dao.mapper.RoutePointItemMapper;
import com.yeejoin.amos.patrol.business.dao.repository.*;
import com.yeejoin.amos.patrol.business.feign.EquipFeign;
import com.yeejoin.amos.patrol.business.feign.JcsFeignClient;
import com.yeejoin.amos.patrol.business.vo.*;
import com.yeejoin.amos.patrol.dao.entity.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.patrol.business.constants.XJConstant;
import com.yeejoin.amos.patrol.business.param.MovePointParam;
import com.yeejoin.amos.patrol.business.param.NewPointParam;
import com.yeejoin.amos.patrol.business.param.PointImportParam;
import com.yeejoin.amos.patrol.business.param.PointImportQueryParam;
import com.yeejoin.amos.patrol.business.param.PointParam;
import com.yeejoin.amos.patrol.business.service.intfc.ICatalogTreeService;
import com.yeejoin.amos.patrol.business.service.intfc.IPointService;
import com.yeejoin.amos.patrol.business.util.CommonResponse;
import com.yeejoin.amos.patrol.business.util.CommonResponseUtil;
import com.yeejoin.amos.patrol.business.util.DaoCriteria;
import com.yeejoin.amos.patrol.business.util.FileHelper;
import com.yeejoin.amos.patrol.business.util.PointParamUtils;
import com.yeejoin.amos.patrol.core.async.AsyncTask;
import com.yeejoin.amos.patrol.core.common.request.CommonPageable;
import com.yeejoin.amos.patrol.core.common.request.CommonRequest;
import com.yeejoin.amos.patrol.core.common.response.PointResponse;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import com.yeejoin.amos.patrol.feign.RemoteSecurityService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

@RestController
@RequestMapping(value = "/api/point")
@Api(tags="巡检点api")
public class PointController extends AbstractBaseController {

	private final Logger log = LoggerFactory.getLogger(PointController.class);

	@Autowired
	private IPointService iPointService;

	@Autowired
	private PointMapper pointMapper;
	@Autowired
	private IPointDao iPointDao;

	@Autowired
	private ICatalogTreeService catalogTreeService;

	@Autowired
	private AsyncTask asyncTask;

    @Autowired
    private RemoteSecurityService remoteSecurityService;

	@Autowired
	private EquipFeign equipFeign;

	@Autowired
	private JcsFeignClient jcsFeignClient;

	@Autowired
	private IPointClassifyDao iPointClassifyDao;
	@Autowired
	private IPointInputItemDao iPointInputItemDao;
	@Autowired
	private IRoutePointDao iRoutePointDao;

	@Autowired
	private IRoutePointItemDao iRoutePointItemDao;


	@Autowired
	private InputItemMapper inputItemMapper;

	@Autowired
	private PointInputItemMapper pointInputItemMapper;

	@Autowired
	private RoutePointItemMapper routePointItemMapper;

    /**
	 *
	 * 新增接口
	 * **/

	/**
	 * 查询巡检点的巡检项
	 *
	 * @param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询巡检点的巡检项", notes = "查询巡检点的巡检项")
	@GetMapping(value = "/queryEquipPointInputItemNew", produces = "application/json;charset=UTF-8")
	public CommonResponse queryEquipPointInputItemNew(@ApiParam(value = "巡检点id", required = true) @RequestParam Long pointId) {
		try {
			List<Map<String, Object>> pointInputItemList = iPointService.queryEquipPointInputItem(pointId);

			Page<Map<String, Object>> pag =new PageImpl<Map<String, Object>>(pointInputItemList);

			return CommonResponseUtil.success(pag);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("查询巡检点的巡检项失败");
		}
	}


	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "获取登录人单位", notes = "获取登录人单位")
	@GetMapping(value = "/getuserdept", produces = "application/json;charset=UTF-8")
	public CommonResponse getuserdept() {
		ReginParams reginParams = getSelectedOrgInfo();
		return CommonResponseUtil.success(reginParams.getPersonIdentity());
	}






	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "新*查询巡检点列表", notes = "新*查询巡检点列表")
	@GetMapping(value = "/routeListNew", produces = "application/json;charset=UTF-8")
	public CommonResponse queryPointListByRouteIdNew(
			@ApiParam(value = "线路ID") @RequestParam(value = "routeId") Long routeId) {
		Page<Map<String, Object>> pag =new PageImpl<Map<String, Object>>(iPointService.queryPointListByRouteId(routeId));
		return CommonResponseUtil.success(pag);
	}


	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "新增移动巡检点(<font color='blue'>手机app</font>)", notes = "新增移动巡检点(<font color='blue'>手机app</font>)")
	@PostMapping(value = "/addMovePointNew", produces = "application/json;charset=UTF-8")
	public CommonResponse addMovePointNew(@RequestBody MovePointParam param) {
		AgencyUserModel user = getUserInfo();
		if (ObjectUtils.isEmpty(user)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {

			ReginParams reginParams = getSelectedOrgInfo();
			String loginOrgCode = getOrgCode(reginParams);
			param.setOrgCode(loginOrgCode);	//点归属于公司
			param.setCreatorId(user.getUserId());
			param.setBizOrgCode(reginParams.getPersonIdentity().getBizOrgCode());
			param.setBizOrgName(reginParams.getPersonIdentity().getCompanyName());
			param.setChargeDeptId(reginParams.getPersonIdentity().getCompanyId());
			iPointService.addMovePoint(param);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("巡检点新增失败");
		}
	}


	@Transactional
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "新增巡查对象", notes = "新增巡查对象")
	@PostMapping(value = "/addPointXcdx", produces = "application/json;charset=UTF-8")
	public CommonResponse addPointXcdx(@ApiParam(value = "新增巡查对象", required = true) @RequestBody PointInputItemNewVo pointClassify){

		try {
			//增加判断

			PointClassify PointClassifyk= iPointClassifyDao.getPointClassifyByPointIdandcode(pointClassify.getPointId(),pointClassify.getCode());
			if(PointClassifyk!=null){
				if(PointClassifyk.getId()!=pointClassify.getId()){
					return CommonResponseUtil.failure("巡查对象code，不能重复！");
				}
			}

			List<RoutePoint> routePointList =  iRoutePointDao.queryByPointId(pointClassify.getPointId());
			AgencyUserModel user = getUserInfo();
			PointClassify newPointClassify = new PointClassify();
			newPointClassify.setEquipmentId(pointClassify.getEquipmentId());
			newPointClassify.setName(pointClassify.getName());
			newPointClassify.setInspectionSpecName(pointClassify.getInspectionName());
			newPointClassify.setCreatorId(user.getUserId());
			newPointClassify.setPointId(pointClassify.getPointId());
			newPointClassify.setOrderNo(0);
			newPointClassify.setDataSourceCode(pointClassify.getDataSourceCode());
			newPointClassify.setDataSourceName(pointClassify.getDataSourceName());
			newPointClassify.setAddress(pointClassify.getAddress());
			newPointClassify.setBuildingId(pointClassify.getBuildingId());
			if(pointClassify.getBuildingName()==null && !StringUtils.isEmpty(pointClassify.getBuildingId())){
				FeignClientResult responseModel  = equipFeign.getBuildingTreeOne(pointClassify.getBuildingId());
				if (ObjectUtils.isEmpty(responseModel.getResult()) || responseModel.getStatus() != HttpStatus.OK.value()) {
					throw new RuntimeException(responseModel.getDevMessage());
				}else{
					Map<String, Object> dat=(Map<String, Object>) responseModel.getResult();
					newPointClassify.setBuildingName(dat.get("name").toString());
				}
			}else{
				newPointClassify.setBuildingName(pointClassify.getBuildingName());
			}


			if(pointClassify.getOriginalId()!=null){
				newPointClassify.setOriginalId(pointClassify.getOriginalId());
			}else{
				String uuid= UUID.randomUUID().toString().replace("-","");
				newPointClassify.setOriginalId(uuid.substring(0,16));
			}
			if (null != pointClassify.getId()) {
				newPointClassify.setId(pointClassify.getId());
			}
			newPointClassify.setCategoryCode(pointClassify.getCategoryCode());
			newPointClassify.setCategoryName(pointClassify.getCategoryName());
			newPointClassify.setCode(pointClassify.getCode());
			List<PointInputItemVo> customInputList = pointClassify.getEquipIputDetailData();//巡检项
			iPointService.addPointClassifyByPointId(newPointClassify);
			List<PointInputItemVo> oldInputItemList = new ArrayList<>();
			List<Long> collect = new ArrayList<>();
			if(pointClassify.getId()==null){
				pointClassify.setId(newPointClassify.getId());
			}else{
				newPointClassify.setId(pointClassify.getId());
				oldInputItemList =iPointService.queryOldPointInputItemNew(pointClassify.getPointId(),pointClassify.getId()); // 新的巡检项的补集，即需要删除的项
				collect = oldInputItemList.stream().map(PointInputItemVo::getPointItemId).collect(Collectors.toList());
				List<PointInputItemVo> newInputItemList = new ArrayList<>();
				List<PointInputItemVo> classList = pointClassify.getEquipIputDetailData();
				newInputItemList.addAll(classList);

				List<Long> ids = new ArrayList<>();
				newInputItemList.forEach(item -> {
//            PointInputItem pii = iPointInputItemDao.getPointInputItem(pointId, item.getPointItemId());
//            if (pii != null) {
					ids.add(item.getPointItemId());
//            }
				});
				List<Long> pItemIds = new ArrayList<>();
				oldInputItemList.forEach(item -> {
					if (!ids.contains(item.getPointItemId())) {
						pItemIds.add(item.getPointItemId());
					}
				});
				if (pItemIds.size() > 0) {
					inputItemMapper.delPointInputItemById(pItemIds);
//					iPointInputItemDao.delPointInputItemById(pItemIds);
					inputItemMapper.delRoutePointItemByItemId(pItemIds);// 删除p_route_point_item中使用到该项的行
				}

			}


			for (PointInputItemVo pItemVo : customInputList) {
				PointInputItem pointInputItem = new PointInputItem();
				if(pItemVo.getPointItemId()==0l) {
					pointInputItem.setPointId(pointClassify.getPointId());
					pointInputItem.setInputItemId(pItemVo.getId());
					pointInputItem.setClassifyIds(Long.valueOf(newPointClassify.getId()).toString());
//				pointInputItem.setId(0);
					pointInputItem.setOrderNo(pItemVo.getpOrderNo());
					pointInputItemMapper.insert(pointInputItem);
//				PointInputItem pointInputItemResult =  iPointInputItemDao.save(pointInputItem);
					//更新巡检路线
					if(routePointList.size()>0){
						Long classifyId=newPointClassify.getId();
						for (RoutePoint routePoint :routePointList) {
							RoutePointItem routePointItem  = new RoutePointItem();
							routePointItem.setPointClassifyId(classifyId);
							routePointItem.setPointInputItemId(pointInputItem.getId());
							routePointItem.setRoutePointId(routePoint.getId());
							routePointItem.setCreatorId(routePoint.getCreatorId().toString());
							routePointItem.setCreateDate(new Date());
							routePointItemMapper.insertRoutePointItem(routePointItem);
//						iRoutePointItemDao.save(routePointItem);
						}
					}
				}else {
					if (!collect.contains(pItemVo.getPointItemId())) {
						pointInputItem.setId(pItemVo.getPointItemId());
						pointInputItem.setInputItemId(pItemVo.getId());
						pointInputItem.setPointId(pointClassify.getPointId());
						pointInputItem.setClassifyIds(Long.valueOf(newPointClassify.getId()).toString());
						pointInputItem.setId(pItemVo.getPointItemId());
						pointInputItem.setOrderNo(pItemVo.getpOrderNo());
						pointInputItemMapper.insert(pointInputItem);
//					iPointInputItemDao.save(pointInputItem);
					}
				}
			}
			return CommonResponseUtil.success(pointClassify);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("新增巡查对象失败");
		}
	}


	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "新增巡查对象", notes = "新增巡查对象")
	@PostMapping(value = "/addPointXcdxList", produces = "application/json;charset=UTF-8")
	public CommonResponse addPointXcdxList(@ApiParam(value = "新增巡查对象", required = true) @RequestBody List<PointInputItemNewVo> pointClassifys){

		try {
			AgencyUserModel user = getUserInfo();
			List<RoutePoint> routePointList =  iRoutePointDao.queryByPointId(pointClassifys.get(0).getPointId());
			for (PointInputItemNewVo pointClassify : pointClassifys) {


				PointClassify PointClassifyk= iPointClassifyDao.getPointClassifyByPointIdandcode(pointClassify.getPointId(),pointClassify.getCode());
				if(PointClassifyk!=null){
					if(PointClassifyk.getId()!=pointClassify.getId()){
						return CommonResponseUtil.failure("巡查对象code，不能重复！");
					}
				}

				PointClassify newPointClassify = new PointClassify();
				newPointClassify.setEquipmentId(pointClassify.getEquipmentId());
				newPointClassify.setName(pointClassify.getName());
				newPointClassify.setInspectionSpecName(pointClassify.getInspectionName());
				newPointClassify.setCreatorId(user.getUserId());
				newPointClassify.setPointId(pointClassify.getPointId());
				newPointClassify.setOrderNo(pointClassify.getOrderNo());
				newPointClassify.setDataSourceCode(pointClassify.getDataSourceCode());
				newPointClassify.setDataSourceName(pointClassify.getDataSourceName());
				newPointClassify.setAddress(pointClassify.getAddress());
				newPointClassify.setBuildingId(pointClassify.getBuildingId());
				newPointClassify.setOriginalId(pointClassify.getOriginalId());
				newPointClassify.setCategoryCode(pointClassify.getCategoryCode());
				newPointClassify.setCategoryName(pointClassify.getCategoryName());
				newPointClassify.setCode(pointClassify.getCode());
				newPointClassify.setBuildingName(pointClassify.getBuildingName());
				if(pointClassify.getId()!=null){
					newPointClassify.setId(pointClassify.getId());
				}
				List<PointClassify> pointClassifies = iPointClassifyDao.queryByPointIdAndEquipmentId(pointClassify.getPointId(), pointClassify.getEquipmentId());
				if (pointClassifies.size() > 0) {
					return CommonResponseUtil.failure("该巡查对象已存在，不可再添加！");
				}
				iPointService.addPointClassifyByPointId(newPointClassify);

				List<PointInputItemVo> customInputList = pointClassify.getEquipIputDetailData();//巡检项

				for (PointInputItemVo pItemVo : customInputList) {
					    PointInputItem pointInputItem = new PointInputItem();

						pointInputItem.setPointId(pointClassify.getPointId());
						pointInputItem.setInputItemId(pItemVo.getId());
						pointInputItem.setClassifyIds(Long.valueOf(newPointClassify.getId()).toString());
						pointInputItem.setId(0);
						pointInputItem.setOrderNo(pItemVo.getpOrderNo());
						PointInputItem pointInputItemResult = iPointInputItemDao.save(pointInputItem);
						//更新巡检路线
						if (routePointList.size() > 0) {

							Long classifyId = newPointClassify.getId();

							for (RoutePoint routePoint : routePointList) {
								RoutePointItem routePointItem = new RoutePointItem();
								routePointItem.setPointClassifyId(classifyId);
								routePointItem.setPointInputItemId(pointInputItemResult.getId());
								routePointItem.setRoutePointId(routePoint.getId());
								iRoutePointItemDao.save(routePointItem);
							}
						}
				}


			}

			return CommonResponseUtil.success();
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("新增巡查对象失败");
		}
	}


	//删除巡查对象

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "删除巡查对象", notes = "删除巡查对象")
	@DeleteMapping(value = "/deletPointClassify", produces = "application/json;charset=UTF-8")
	public CommonResponse deletPointClassify(@ApiParam(value = "巡查对象id", required = true) @RequestParam List<Long> ids) {
		try {
			for (Long id : ids) {
				PointClassify pointClassify=iPointClassifyDao.getOne(id);
				List<PointClassify> list=iPointClassifyDao.getPointClassifyByPointId(pointClassify.getPointId());
				List<RoutePointItem> listp=iRoutePointItemDao.getRoutePointItemByPointId(pointClassify.getPointId());

				if(list.size()==1&&listp!=null&&listp.size()>0){
					return CommonResponseUtil.failure("巡查点已绑定路线，最少保留一个巡查对象！");
				}
				if(list.size()==1){
					return CommonResponseUtil.failure("巡查点最少保留一个巡查对象！");
				}

				//删除检查项
				iPointInputItemDao.deleteClassifyId(id);
				//删除巡检路线和项的关系表
				iRoutePointItemDao.delRoutePointItemByPointClassifyId(id);
				//删除对象
				iPointClassifyDao.deleteById(id);


			}

			//如果点下只有一个对象，并且点已经关联线路就不能删除
			return CommonResponseUtil.success();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("查询巡检点失败");
		}
	}










    /**
	 *  获取当前登录人，单位下建筑树
	 *
	 * */

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "获取当前登录人，单位下建筑树", notes = "获取当前登录人，单位下建筑树")
	@GetMapping(value = "/gettreeWarehouse", produces = "application/json;charset=UTF-8")
	public CommonResponse gettreeWarehouse(@RequestParam(value = "pointId",required = false) String pointId) {
		try {
			Map<String, Object> map = new HashMap<>();
			if (!StringUtils.isEmpty(pointId)){
				map = pointMapper.getPointById(Long.valueOf(pointId));
			}
			ReginParams reginParams = getSelectedOrgInfo();
			//顶节点ID
			Long parentId = StringUtils.isEmpty(String.valueOf(map.get("buildingId"))) ? 0 : Long.parseLong(String.valueOf(map.get("buildingId")));
			return CommonResponseUtil.success(equipFeign.gettreeWarehouse(parentId, reginParams.getPersonIdentity().getCompanyBizOrgCode(),map.get("buildingId").toString()));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("查询巡检点失败");
		}
	}

	/**
	 * 根据ID查询巡检点信息
	 *
	 * @param id
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询巡检点信息", notes = "查询巡检点信息")
	@GetMapping(value = "/queryPointByIdNew", produces = "application/json;charset=UTF-8")
	public CommonResponse queryPointByIdNew(@ApiParam(value = "巡检点id", required = true) @RequestParam String id) {
		try {
			Point point = iPointService.queryPointById(Long.valueOf(id));
			PointNewVo pointNewVo = new PointNewVo();
			BeanUtils.copyProperties(point,pointNewVo);
			pointNewVo.setIsIndoor(point.getIsIndoor() == false ? "0":"1");
			pointNewVo.setOffline(point.getOffline() == false ? "0":"1");
			return CommonResponseUtil.success(pointNewVo);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("查询巡检点失败");
		}
	}







	/**
	 *
	 * 新增接口
	 * **/
	/**
	 * 增加巡检点
	 *
	 * @param pointParam
	 * @return
	 */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "新增巡检点", notes = "新增巡检点")
	@PostMapping(value = "/addPoint", produces = "application/json;charset=UTF-8")
	public CommonResponse addPoint(@ApiParam(value = "巡检点", required = true) @RequestBody PointParam pointParam){
		AgencyUserModel user = getUserInfo();
		if (ObjectUtils.isEmpty(user)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {
			 ReginParams reginParams = getSelectedOrgInfo();
	            String loginOrgCode = getOrgCode(reginParams);
			pointParam.getPoint().setOrgCode(loginOrgCode);	//点归属于公司
			pointParam.getPoint().setCreatorId(user.getUserId());
			Point point = iPointService.addPoint(pointParam);
			List<Long> ids = new ArrayList<>();
			ids.add(point.getId());
			//asyncTask.pushPointTo3D(ids);
			pushPointTo3D(getToken(), getProduct(), getAppKey(),ids);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("巡检点新增失败");
		}
	}

	/**
	 * 增加巡检点
	 *
	 * @param pointParam
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "新增巡检点", notes = "新增巡检点")
	@PostMapping(value = "/newAddPoint", produces = "application/json;charset=UTF-8")
	public CommonResponse newAddPoint(@ApiParam(value = "巡检点", required = true) @RequestBody NewPointParam pointParam){
		AgencyUserModel user = getUserInfo();
		if (ObjectUtils.isEmpty(user)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {
			ReginParams reginParams = getSelectedOrgInfo();
			String loginOrgCode = getOrgCode(reginParams);
			pointParam.getPoint().setOrgCode(loginOrgCode);	//点归属于公司
			pointParam.getPoint().setCreatorId(user.getUserId());
			Point point = iPointService.newAddPoint(pointParam);
			List<Long> ids = new ArrayList<Long>();
			ids.add(point.getId());
//			asyncTask.pushPointTo3D(ids);
//			pushPointTo3D(getToken(), getProduct(), getAppKey(),ids);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("巡检点新增失败");
		}
	}

	    @Async
	    public void pushPointTo3D(String toke,String product,String appKey,List<Long> ids ){

	    	 try {
				asyncTask.pushPointTo3D( toke, product, appKey,ids);

			} catch (InterruptedException e) {
				e.printStackTrace();
			}

	    }

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "新增移动巡检点(<font color='blue'>手机app</font>)", notes = "新增移动巡检点(<font color='blue'>手机app</font>)")
	@PostMapping(value = "/addMovePoint", produces = "application/json;charset=UTF-8")
	public CommonResponse addMovePoint(@RequestBody MovePointParam param) {
		AgencyUserModel user = getUserInfo();
		if (ObjectUtils.isEmpty(user)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {
			 ReginParams reginParams = getSelectedOrgInfo();
	            String loginOrgCode = getOrgCode(reginParams);

			param.setOrgCode(loginOrgCode);	//点归属于公司
			param.setCreatorId(user.getUserId());

			iPointService.addMovePoint(param);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("巡检点新增失败");
		}
	}

	/**
	 * 删除巡检点
	 *
	 * @param ids
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "删除巡检点", notes = "删除巡检点")
	@DeleteMapping(value = "/deletePoint", produces = "application/json;charset=UTF-8")
	public CommonResponse deletePoint(@ApiParam(value = "巡检点ID", required = true) @RequestParam Long[] ids) {
		try {
			List<Long> deleteIdList = iPointService.delPointById(ids);
			//asyncTask.pushDeletePointTo3D(deleteIdList);
			pushDeletePointTo3D(getToken(), getProduct(), getAppKey(),deleteIdList);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("删除巡检点失败");
		}
	}


	    @Async
	    public void pushDeletePointTo3D(String toke,String product,String appKey,List<Long> ids ){

	    	 try {
				//asyncTask.pushPointTo3D(ids);
	    		 pushPointTo3D( toke, product, appKey,ids);
			} catch (Exception e) {
				e.printStackTrace();
			}

	    }




	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询巡检点信息(<font color='blue'>手机app</font>)", notes = "查询巡检点信息(<font color='blue'>手机app</font>)")
	@PostMapping(value = "/queryPointByPageNew", produces = "application/json;charset=UTF-8")
	public CommonResponse queryPointByPageNew(
			@ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests,
			@ApiParam(value = "分页参数", required = true, defaultValue = "pageNumber=0&pageSize=10") CommonPageable commonPageable) {

		ReginParams reginParams = getSelectedOrgInfo();
		String orgCode = reginParams.getPersonIdentity().getCompanyBizOrgCode();
		if (ObjectUtils.isEmpty(reginParams)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {
			CommonRequest commonRequest = new CommonRequest();
			commonRequest.setName("orgCode");
			commonRequest.setValue(orgCode);
			queryRequests.add(commonRequest);
			HashMap<String, Object> param = PointParamUtils.fillTaskInfo(queryRequests);
			Page<PointVo> pointList = iPointService.queryPointByPage(param, commonPageable);
			return CommonResponseUtil.success(pointList);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("查询巡检点信息失败");
		}
	}















	/**
	 * 更新巡检点
	 *
	 * @param pointParam
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "更新巡检点", notes = "更新巡检点")
	@PutMapping(value = "/updatePoint", produces = "application/json;charset=UTF-8")
	public CommonResponse updatePoint(@ApiParam(value = "巡检点", required = true) @RequestBody PointParam pointParam) {
		try {
			Point point = iPointService.updatePoint(pointParam);
			List<Long> ids = new ArrayList<>();
			ids.add(point.getId());
			//asyncTask.pushPointTo3D(ids);
			pushPointTo3D(getToken(), getProduct(), getAppKey(),ids);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("更新巡检点失败");
		}
	}

	/**
	 * 根据ID查询巡检点信息
	 *
	 * @param id
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询巡检点信息", notes = "查询巡检点信息")
	@GetMapping(value = "/queryPointById/{id}", produces = "application/json;charset=UTF-8")
	public CommonResponse queryPointById(@ApiParam(value = "巡检点id", required = true) @PathVariable(name = "id") Long id) {
		try {
			Point point = iPointService.queryPointById(id);
			return CommonResponseUtil.success(point);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("查询巡检点失败");
		}
	}
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询巡检点详情<font color='blue'>手机app</font>)", notes = "查询巡检点详情<font color='blue'>手机app</font>)")
	@GetMapping(value = "/queryPointDetailById", produces = "application/json;charset=UTF-8")
	public CommonResponse queryPointDetailById(@ApiParam(value = "巡检点id", required = true) @RequestParam(name = "pointId") Long id) {
		try {
			Map point = iPointService.queryPointDetailById1(getToken(),getProduct(),getAppKey(),id);
			return CommonResponseUtil.success(point);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("查询巡检点详情失败");
		}

	}
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询巡检点详情<font color='blue'>手机app</font>)", notes = "查询巡检点详情<font color='blue'>手机app</font>)")
	@GetMapping(value = "/v2/queryPointDetailById", produces = "application/json;charset=UTF-8")
	public CommonResponse queryPointDetailByIdInVersion2(@ApiParam(value = "巡检点id", required = true) @RequestParam(name = "pointId") Long id) {
		try {
			Map point = iPointService.queryPointDetailByIdInVersion2(id);
			return CommonResponseUtil.success(point);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("查询巡检点详情失败");
		}

	}

	/**
	 * 查询巡检点信息
	 *
	 * @param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询巡检点信息", notes = "查询巡检点信息")
	@PostMapping(value = "/list", produces = "application/json;charset=UTF-8")
	public CommonResponse listPoint(
			@ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests,
			@ApiParam(value = "分页参数", required = true, defaultValue = "pageNumber=0&pageSize=10") CommonPageable commonPageable) {
		ReginParams reginParams = getSelectedOrgInfo();
        String loginOrgCode = getOrgCode(reginParams);
        String roleTypeName = getRoleTypeName(reginParams);
		if (ObjectUtils.isEmpty(reginParams)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {
			CommonRequest commonRequest = new CommonRequest();
			commonRequest.setName("orgCode");
			commonRequest.setValue(loginOrgCode);
			queryRequests.add(commonRequest);
            List<DaoCriteria> criterias = buildDaoCriterias(queryRequests, false, loginOrgCode, roleTypeName);
			Page<PointVo> pointList = iPointService.queryPointInfo(criterias, commonPageable, loginOrgCode);
			return CommonResponseUtil.success(pointList);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("查询巡检点信息失败");
		}
	}



	/**
	 * 查询巡检点信息
	 *
	 * @param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询所有检查点", notes = "查询所有检查点")
	@PostMapping(value = "/list/all", produces = "application/json;charset=UTF-8")
	public CommonResponse listAllPoint() {

			return CommonResponseUtil.success(iPointService.queryAllPoint());
	}

	/**
	 * 导入巡检点
	 * @param file
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "上传巡检点", notes = "上传巡检点")
	@PostMapping(value = "/import", produces = "application/json;charset=UTF-8")
	public CommonResponse importPoint(@ApiParam(value="导入数据文件", required=true) MultipartFile file) {
		String fileName = file.getOriginalFilename();

		if (!fileName.endsWith(".xls")) {
			return CommonResponseUtil.failure("文件格式错误");
		}
		 String userId = getUserId();
	        ReginParams reginParams = getSelectedOrgInfo();
	        String loginOrgCode = getOrgCode(reginParams);
		if (ObjectUtils.isEmpty(reginParams)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {
			List<PointImportParam> list = FileHelper.importExcel(file, 0, 1, PointImportParam.class);
			List<Long> pointIds = iPointService.addImportPoint(list, loginOrgCode, userId);
			//asyncTask.pushPointTo3D(pointIds);
			pushPointTo3D(getToken(), getProduct(), getAppKey(),pointIds);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			e.printStackTrace();
			return CommonResponseUtil.failure("导入失败");
		}
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "导入导入模板", notes = "导入导入模板")
	@PostMapping(value = "/exportTemplate", produces = "application/json;charset=UTF-8")
	public CommonResponse exportTemplate(HttpServletResponse response) {
		 String userId = getUserId();
	        ReginParams reginParams = getSelectedOrgInfo();
	        String loginOrgCode = getOrgCode(reginParams);
        String fileName = "巡检点导入模板"; //模板名称
        String[] handers = {"点编号","点名称","是否为移动点","计划外巡检是否评分","是否允许离线巡检","参考地址","3维地图坐标","3维地图楼层","最少拍照数量","最多拍照数量","风险等级","备注说明","所属分类目录","检查项目","是否室内"}; //列标题
        List<String[]> downData = new ArrayList();
        String[] isScore = {"否","是"};
        String[] isFixed = {"否","是"};
        String[] offline = {"否","是"};
        String[] isIndoor = {"否","是"};
        String[] level = {"一级","二级","三级","四级","五级"};
        String[] catalog = catalogTreeService.getCataLogList(loginOrgCode);
        downData.add(isFixed);
        downData.add(isScore);
        downData.add(offline);
        downData.add(level);
        downData.add(catalog);
        downData.add(isIndoor);
        String [] downRows = {"2","3","4", "10", "12","14"}; //下拉的列序号数组(序号从0开始)

        try {
        	FileHelper.createExcelTemplate(fileName, handers, downData, downRows, response);
        } catch (Exception e) {
        	CommonResponseUtil.failure(e.getMessage());
        }
        return CommonResponseUtil.success();
	}

/**新加接口**/
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@ApiOperation(value = "导入导入模板新", notes = "导入模板新")
	@GetMapping(value = "/exportTemplateNew", produces = "application/json;charset=UTF-8")
	public CommonResponse exportTemplateNew(HttpServletResponse response) {
		String userId = getUserId();
		ReginParams reginParams = getSelectedOrgInfo();
		String loginOrgCode = getOrgCode(reginParams);
		String fileName = "巡检点导入模板.xls"; //模板名称
		String[] handers = {"点编号","点名称","是否为移动点","计划外巡检是否评分","是否允许离线巡检","参考地址","最少拍照数量","最多拍照数量","风险等级","备注说明","检查项目","是否室内","归属单位/部门","责任人","所在建筑"}; //列标题
		List<String[]> downData = new ArrayList();
		String[] isScore = {"否","是"};
		String[] isFixed = {"否","是"};
		String[] offline = {"否","是"};
		String[] isIndoor = {"否","是"};
		String[] level = {"一级","二级","三级","四级","五级"};

		//    String[] catalog = catalogTreeService.getCataLogList(loginOrgCode);
		downData.add(isFixed);
		downData.add(isScore);
		downData.add(offline);
		downData.add(level);
		//    downData.add(catalog);
		downData.add(isIndoor);

		//归属单位
		ResponseModel<Object> orgUsr = jcsFeignClient.getByOrgCode(reginParams.getPersonIdentity().getBizOrgCode());
		if (!ObjectUtils.isEmpty(orgUsr.getResult())){
			Object result = orgUsr.getResult();
			List<Map<String,String>> orgList =(List<Map<String,String>>)result;
			String[] orgUsrs = new String[orgList.size()];
			if (CollectionUtils.isNotEmpty(orgList)){
				for (int i = 0; i < orgList.size(); i++) {
					orgUsrs[i] = orgList.get(i).get("bizOrgName")+"@"+orgList.get(i).get("sequenceNbr");
				}
			}
			downData.add(orgUsrs);
		}else {
			downData.add(new String[0]);
		}
		//责任人
		if (!StringUtils.isEmpty(reginParams.getPersonIdentity().getBizOrgCode())) {
			Object o = jcsFeignClient.listCompany(reginParams.getPersonIdentity().getBizOrgCode());
			List<Map<String,String>> personlist = (List<Map<String,String>>)o;
			String[] person = new String[personlist.size()];
			if (CollectionUtils.isNotEmpty(personlist)){
				for (int i = 0; i < personlist.size(); i++) {
					person[i] = personlist.get(i).get("bizOrgName")+"@"+personlist.get(i).get("amosOrgId")+"@"+personlist.get(i).get("parentName");
				}
				downData.add(person);
			} else {
				downData.add(new String[0]);
			}
		} else {
			downData.add(new String[0]);
		}
		if (!StringUtils.isEmpty(reginParams.getPersonIdentity().getBizOrgCode())) {
			//所在建筑
			FeignClientResult result = equipFeign.myTreeList();
			Object obj = result.getResult();
			List<Map<String, Object>> treeMap = (List<Map<String, Object>>) obj;
			String[] build = new String[treeMap.size()];
			if (CollectionUtils.isNotEmpty(treeMap)) {
				for (int i = 0; i < treeMap.size(); i++) {
					build[i] = treeMap.get(i).get("instanceName") + "@" + treeMap.get(i).get("instanceId");
				}
			}
			downData.add(build);
		} else {
			downData.add(new String[0]);
		}
		String [] downRows = {"2","3","4", "8","11","12","13","14"}; //下拉的列序号数组(序号从0开始)

		try {
			FileHelper.createExcelTemplate(fileName, handers, downData, downRows, response);
		} catch (Exception e) {
			CommonResponseUtil.failure(e.getMessage());
		}
		return CommonResponseUtil.success();
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询巡检点信息", notes = "查询巡检点信息")
	@PostMapping(value = "/exportListPoint", produces = "application/json;charset=UTF-8")
	public CommonResponse exportListPoint(@ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests,
			@RequestParam(value="exportType",required = false) int exportType,
			HttpServletResponse response) {
		  String userId = getUserId();
	        ReginParams reginParams = getSelectedOrgInfo();
	        String orgCode = getOrgCode(reginParams);
		if (ObjectUtils.isEmpty(reginParams)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {

			PointImportQueryParam pointImportQueryParam = PointParamUtils.fillPointImportQuery(queryRequests);


			pointImportQueryParam.setOrgCode(orgCode);
			List<PointVo> pointList = iPointService.queryPointInfoListByIds(pointImportQueryParam);
			if (exportType == 0) {
				FileHelper.exportExcel(pointList, "巡检点列表", "巡检点信息", PointVo.class, "巡检点.xls", response);
			} else if (exportType == 1) {
				FileHelper.exportQRCode(pointList, "巡检点二维码", response);
			}
			return CommonResponseUtil.success("导出成功");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("查询巡检点信息失败");
		}
	}


	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询巡检点信息", notes = "查询巡检点信息")
	@PostMapping(value = "/exportListPointNew", produces = "application/json;charset=UTF-8")
	public CommonResponse exportListPointNew(@ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests,
										  @RequestParam(value="exportType",required = false) int exportType,
										  HttpServletResponse response) {

		ReginParams reginParams = getSelectedOrgInfo();
		String companyBizOrgCode = reginParams.getPersonIdentity().getCompanyBizOrgCode();
		if (ObjectUtils.isEmpty(reginParams)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {

			PointImportQueryParam pointImportQueryParam = new PointImportQueryParam();
			pointImportQueryParam.setBizOrgCode(companyBizOrgCode);

			List<PointVo> pointList = iPointService.queryPointInfoListByIds(pointImportQueryParam);
			if (exportType == 0) {
				FileHelper.exportExcel(pointList, "巡检点列表", "巡检点信息", PointVo.class, "巡检点.xls", response);
			} else if (exportType == 1) {
				FileHelper.exportQRCode(pointList, "巡检点二维码", response);
			}
			return CommonResponseUtil.success("导出成功");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("查询巡检点信息失败");
		}
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询巡检点信息", notes = "查询巡检点信息")
	@GetMapping(value = "/exportListPointByIds", produces = "application/json;charset=UTF-8")
	public CommonResponse exportListPointByIds(@ApiParam(value = "查询条件", required = false) @RequestParam(value="ids",required = false) Long[] ids,
			@RequestParam(value="exportType",required = false) int exportType,
			HttpServletResponse response) {
		ReginParams reginParams = getSelectedOrgInfo();
        String orgCode = getOrgCode(reginParams);
		if (ObjectUtils.isEmpty(reginParams)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {
			List<Long> idList = Arrays.asList(ids);
			PointImportQueryParam pointImportQueryParam = new PointImportQueryParam();
			pointImportQueryParam.setPointIds(idList);
			pointImportQueryParam.setOrgCode(orgCode);
			List<PointVo> pointList = iPointService.queryPointInfoListByIds(pointImportQueryParam);
			if (exportType == 0) {
				FileHelper.exportExcel(pointList, "巡检点列表", "巡检点信息", PointVo.class, "巡检点.xls", response);
			} else if (exportType == 1) {
				FileHelper.exportQRCode(pointList, "巡检点二维码", response);
			}
			return CommonResponseUtil.success("导出成功");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("查询巡检点信息失败");
		}
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询巡检点信息(<font color='blue'>手机app</font>)", notes = "查询巡检点信息(<font color='blue'>手机app</font>)")
	@PostMapping(value = "/queryPointByPage", produces = "application/json;charset=UTF-8")
	public CommonResponse queryPointByPage(
			@ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests,
			@ApiParam(value = "分页参数", required = true, defaultValue = "pageNumber=0&pageSize=10") CommonPageable commonPageable) {

		 ReginParams reginParams = getSelectedOrgInfo();
	        String orgCode = getOrgCode(reginParams);
		if (ObjectUtils.isEmpty(reginParams)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {
			CommonRequest commonRequest = new CommonRequest();
			commonRequest.setName("orgCode");
			commonRequest.setValue(orgCode);
			queryRequests.add(commonRequest);
			HashMap<String, Object> param = PointParamUtils.fillTaskInfo(queryRequests);
			Page<PointVo> pointList = iPointService.queryPointByPage(param, commonPageable);
			return CommonResponseUtil.success(pointList);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("查询巡检点信息失败");
		}
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询用户登录公司全部巡检点", notes = "查询用户登录公司全部巡检点")
	@GetMapping(value = "/authPoints", produces = "application/json;charset=UTF-8")
	public CommonResponse listPoint(@ApiParam(value = "巡检点编码", required = false) @RequestParam("ids") List<String> ids,
									@ApiParam(value = "巡检点名称", required = false) @RequestParam("names") List<String> names) {
		 ReginParams reginParams = getSelectedOrgInfo();
	        String orgCode = getOrgCode(reginParams);
		try {


			List<Point> list = iPointService.queryPointList(ids, names, orgCode);
			return CommonResponseUtil.success(list);
		} catch (Exception e) {
			return CommonResponseUtil.failure(e.getMessage());
		}
	}

	/**
	 * 查询巡检点信息及所包含得分类
	 * @param code
	 * @param name
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询用户登录公司全部巡检点", notes = "查询用户登录公司全部巡检点")
	@GetMapping(value = "/queryPoints", produces = "application/json;charset=UTF-8")
	public CommonResponse queryPoints(@ApiParam(value = "巡检点编码", required = false) @RequestParam("code") String code,
									@ApiParam(value = "巡检点名称", required = false) @RequestParam("name") String name) {
		 ReginParams reginParams = getSelectedOrgInfo();
		 String orgCode = getOrgCode(reginParams);
		try {
			/*String orgCode = null;
			if (!ObjectUtils.isEmpty(reginParams)) {
				orgCode = loginUserParam.getOrgCode();
			} */
			List<HashMap<String, Object>> list = iPointService.findPointList(code, name, orgCode);
			return CommonResponseUtil.success(list);
		} catch (Exception e) {
			log.error(e.getMessage());
			return CommonResponseUtil.failure(e.getMessage());
		}
	}

	/**
	 * 另存巡检点
	 *
	 * @param ids
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "另存巡检点", notes = "另存巡检点")
	@PostMapping(value = "/saveAs", produces = "application/json;charset=UTF-8")
	public CommonResponse saveAs(@ApiParam(value = "巡检点id集合", required = true) @RequestParam Long[] ids) {
		try {
			List<String> list = iPointService.qryPointNoList(null, (long)-1);
			for (Long id : ids) {
				Point point = iPointService.queryPointById(id);
				if(list.contains(point.getPointNo()+"_copy")){
					return CommonResponseUtil.failure("巡检点"+point.getPointNo()+"已另存!");
				}
			}
			iPointService.saveAs(ids);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("另存巡检点失败");
		}
	}

	/**
	 * 查询巡检点的巡检项
	 *
	 * @param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询巡检点的巡检项", notes = "查询巡检点的巡检项")
	@PostMapping(value = "/queryPointInputItem", produces = "application/json;charset=UTF-8")
	public CommonResponse queryPointInputItem(@ApiParam(value = "巡检点id", required = true) @RequestParam Long pointId) {
		try {
			List<PointInputItemVo> pointInputItemList = iPointService.queryPointInputItem(pointId);
			return CommonResponseUtil.success(pointInputItemList);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("查询巡检点的巡检项失败");
		}
	}
	/**
	 * 查询巡检点的巡检项
	 *
	 * @param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询巡检点的巡检项", notes = "查询巡检点的巡检项")
	@GetMapping(value = "/queryEquipPointInputItem", produces = "application/json;charset=UTF-8")
	public CommonResponse queryEquipPointInputItem(@ApiParam(value = "巡检点id", required = true) @RequestParam Long pointId) {
		try {
			List<Map<String, Object>> pointInputItemList = iPointService.queryEquipPointInputItem(pointId);
			return CommonResponseUtil.success(pointInputItemList);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("查询巡检点的巡检项失败");
		}
	}
	/**
	 * 查询巡检点的分类
	 *
	 * @param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询巡检点的分类", notes = "查询巡检点的分类")
	@PostMapping(value = "/queryPointClassify", produces = "application/json;charset=UTF-8")
	public CommonResponse queryPointClassify(@ApiParam(value = "巡检点id", required = true) @RequestParam Long pointId) {
		try {
			List<PointClassify> pointClassify = iPointService.queryPointClassify(pointId);
			return CommonResponseUtil.success(pointClassify);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("查询巡检点的分类失败");
		}
	}

	/**
	 * 根据分类id查询对应项
	 *
	 * @param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "根据分类id查询对应项", notes = "根据分类id查询对应项")
	@PostMapping(value = "/queryPointInputItemByClassify", produces = "application/json;charset=UTF-8")
	public CommonResponse queryPointInputItemByClassify(@ApiParam(value = "巡检点id", required = true) @RequestParam Long pointId,
			@ApiParam(value = "巡检点分类id", required = true) @RequestParam Long classifyId) {
		try {
			List<PointInputItemVo> pointInputItem = iPointService.queryPointInputItemByClassify(pointId, classifyId);
			return CommonResponseUtil.success(pointInputItem);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("根据分类id查询对应项失败");
		}
	}

	/**
	 * 根据点id查询点的分类及对应项
	 *
	 * @param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "根据点id查询点的分类及对应项", notes = "根据点id查询点的分类及对应项")
	@PostMapping(value = "/queryPointClassifyWithInputItem", produces = "application/json;charset=UTF-8")
	public CommonResponse queryPointClassifyWithInputItem(@ApiParam(value = "巡检点id", required = true) @RequestParam Long pointId) {
		try {
			Map<String, PointClassifyVo> classifyNameWithInputItemIdMap = iPointService.queryPointClassifyWithInputItemVo(pointId);
			return CommonResponseUtil.success(classifyNameWithInputItemIdMap);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("根据点id查询点的分类及对应项失败");
		}
	}

	/**
	 * 设置巡检点巡检模式
	 * @param pointId
	 * @param isOffine
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "设置巡检点巡检模式", notes = "设置巡检点巡检模式")
	@PostMapping(value = "/setPatrolMode", produces = "application/json;charset=UTF-8")
	public CommonResponse setPatrolMode(@ApiParam(value = "巡检点id", required = true) @RequestParam Long pointId,
			@ApiParam(value = "是否开启离线模式", required = true) @RequestParam Boolean isOffine){
		try {
			Point point = iPointService.setPatrolMode(pointId, isOffine);
			if(ObjectUtils.isEmpty(point)){
				return CommonResponseUtil.failure("该巡检点不存在");
			}
			return CommonResponseUtil.success(point);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("绑卡失败");
		}
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询用户权限点信息饼图(<font color='blue'>手机app</font>)", notes = "查询用户权限点信息饼图(<font color='blue'>手机app</font>)")
	@GetMapping(value = "/queryPointPie", produces = "application/json;charset=UTF-8")
	public CommonResponse queryPointPie() {
		    ReginParams reginParams = getSelectedOrgInfo();
	        String loginOrgCode = getOrgCode(reginParams);
	        String roleTypeName = getRoleTypeName(reginParams);
	        String departmentId = getDepartmentId(reginParams);
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("orgCode", loginOrgCode);
		if (XJConstant.ROLE_NAME_DEPTADMIN.equals(roleTypeName.toUpperCase())) {
			params.put("department", departmentId);
		} else  if (XJConstant.ROLE_NAME_PERSON.equals(roleTypeName.toUpperCase())){
			params.put("userId", getUserId());
		}
		HashMap<String, Object> response = iPointService.queryPointPie(params);
		return CommonResponseUtil.success(response);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询用户权限点信息柱状图(<font color='blue'>手机app</font>)", notes = "查查询用户权限点信息柱状图(<font color='blue'>手机app</font>)")
	@GetMapping(value = "/queryPointHistogram", produces = "application/json;charset=UTF-8")
	public CommonResponse queryPointHistogram() {
		 ReginParams reginParams = getSelectedOrgInfo();
	        String loginOrgCode = getOrgCode(reginParams);
	        String roleTypeName = getRoleTypeName(reginParams);
	        String departmentId = getDepartmentId(reginParams);
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("orgCode", loginOrgCode);
		if (XJConstant.ROLE_NAME_DEPTADMIN.equals(roleTypeName.toUpperCase())) {
			params.put("department", departmentId);
		} else if (XJConstant.ROLE_NAME_PERSON.equals(roleTypeName.toUpperCase())){
			params.put("userId", getUserId());
		}
		List<HashMap<String, Object>> response = iPointService.queryPointHistogram(params);

		 //安全处里
        if(response!=null&&response.size()>0){

        	  //获取部门名称
            String userIds="";
            Set<String> set = new HashSet<>();
            response.forEach(s -> {
            	if(!"其他".equals(s.get("departmentName")+"")){
            		 set.add(s.get("departmentName").toString());
            	}

            });

            List<String> list1 = new ArrayList<>(set);
            userIds = String.join(",", list1);
            List<LinkedHashMap> listd=remoteSecurityService.listDepartmentByDeptIds( getToken(),getProduct(),getAppKey(),userIds);
            Map<String, String> deptMap =  new HashMap<String,String>();
            if(listd != null && listd.size() > 0){
            	 for (int i = 0; i < listd.size(); i++) {
                 	deptMap.put(listd.get(i).get("sequenceNbr").toString(), listd.get(i).get("departmentName").toString());
     			}
            }

            //新安全
            response.forEach(s -> {
            	if( !"其他".equals(s.get("departmentName")+"")) {

        			s.put("departmentName", deptMap.get(s.get("departmentName")+""));
            	}

            	    });
        }






		return CommonResponseUtil.success(response);
	}

	/**
	 * 查询巡检点信息
	 *
	 * @param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询巡检点编号信息", notes = "查询巡检点编号信息")
	@GetMapping(value = "/queryPointNo/{pointId}", produces = "application/json;charset=UTF-8")
	public CommonResponse queryPointNoList(
			@ApiParam(value = "巡检点id", required = true) @PathVariable(name = "pointId") Long pointId,
			@ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests) {
		 ReginParams reginParams = getSelectedOrgInfo();
	        String loginOrgCode = getOrgCode(reginParams);
	        String roleTypeName = getRoleTypeName(reginParams);
	        String departmentId = getDepartmentId(reginParams);
		if (ObjectUtils.isEmpty(reginParams)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {
			CommonRequest commonRequest = new CommonRequest();
			commonRequest.setName("orgCode");
			commonRequest.setValue(loginOrgCode);
			if (queryRequests == null) {
				queryRequests = new ArrayList<>();
			}
			queryRequests.add(commonRequest);
            List<DaoCriteria> criterias = buildDaoCriterias(queryRequests, false, loginOrgCode, roleTypeName);
			List<String> pointNoList = iPointService.qryPointNoList(criterias, pointId);
			return CommonResponseUtil.success(pointNoList);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("查询巡检点编号信息失败");
		}
	}

	/**
	 * 离线点信息同步
	 * @param startTime
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询离线点信息", notes = "查询离线点信息")
	@GetMapping(value = "/queryLeavelPoint", produces = "application/json;charset=UTF-8")
	public CommonResponse queryLeavelPoint(@ApiParam(value = "数据同步开始时间（不传为全部同步）", required = false) @RequestParam(required=false) String startTime) {
		 ReginParams reginParams = getSelectedOrgInfo();
	        // String loginOrgCode = getOrgCode(reginParams);
			String loginOrgCode = reginParams.getPersonIdentity().getBizOrgCode();
	        String roleTypeName = getRoleTypeName(reginParams);
		if (ObjectUtils.isEmpty(reginParams)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		//String orgCode = loginUserParam.getOrgCode();
		return CommonResponseUtil.success(iPointService.queryLeavelPoint(getToken(), getProduct(), getAppKey(),loginOrgCode, startTime));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询点信息json", notes = "查询点信息json")
	@GetMapping(value = "/getPointConfigJson",  produces ="application/json;charset=UTF-8")
	public CommonResponse getPointConfigJson() {

		return CommonResponseUtil.success(iPointService.getPointConfigDom());
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询点信息xml", notes = "查询点信息xml")
	@GetMapping(value = "/getPointConfigDom",  produces =MediaType.APPLICATION_XML_VALUE)
	public  List<PointResponse> getPointConfigDom() {

		return iPointService.getPointConfigDom();
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "导出IEC104点位表", notes = "导出IEC104点位表")
	@PostMapping(value = "/exportPoint/iec", produces = "application/json;charset=UTF-8")
	public CommonResponse exportIecPoint(HttpServletResponse response) {
		 ReginParams reginParams = getSelectedOrgInfo();
	        String loginOrgCode = getOrgCode(reginParams);
	        String roleTypeName = getRoleTypeName(reginParams);
        String fileName = "巡检点点位"; //模板名称
        String[] handers = {"点位名称","点位编码"}; //列标题
        List<Map<String, Object>> list = iPointService.queryAllPointConfig(loginOrgCode);
        try {
        	FileHelper.exportExcel(list, fileName, response);
        } catch (Exception e) {
        	CommonResponseUtil.failure(e.getMessage());
        }
        return CommonResponseUtil.success();
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "新*巡检点筛选分页列表", notes = "新*巡检点筛选分页列表")
	@GetMapping(value = "/list-new", produces = "application/json;charset=UTF-8")
	public CommonResponse queryPointList4Route(
			@ApiParam(value = "区域") @RequestParam(value = "riskSourceId", required = false) Long riskSourceId,
			@ApiParam(value = "点编号") @RequestParam(value = "pointNo", required = false) String pointNo,
			@ApiParam(value = "点名称") @RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "current", defaultValue = "1") int current,
			@RequestParam(value = "size", defaultValue = "10") int size) {
		return CommonResponseUtil.success(iPointService.queryPointList4Route(riskSourceId, pointNo, name, current-1, size));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "关联巡检点分页列表", notes = "关联巡检点分页列表")
	@GetMapping(value = "/listNew", produces = "application/json;charset=UTF-8")
	public CommonResponse queryPointList4RouteNew(
			@ApiParam(value = "区域") @RequestParam(value = "riskSourceId", required = false) Long riskSourceId,
			@ApiParam(value = "点编号") @RequestParam(value = "pointNo", required = false) String pointNo,
			@ApiParam(value = "点名称") @RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "pageNumber", defaultValue = "0") int pageNumber,
			@RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
			@RequestParam(value = "companyId") String companyId) {

		ReginParams reginParams = getSelectedOrgInfo();
		String companyBizOrgCode = reginParams.getPersonIdentity().getCompanyBizOrgCode();
		return CommonResponseUtil.success(iPointService.queryPointList4RouteNew(companyBizOrgCode,riskSourceId, pointNo, name, pageNumber, pageSize,companyId));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "新*查询巡检点列表", notes = "新*查询巡检点列表")
	@GetMapping(value = "/route-list-new", produces = "application/json;charset=UTF-8")
	public CommonResponse queryPointListByRouteId(
			@ApiParam(value = "线路ID") @RequestParam(value = "routeId") Long routeId) {
		return CommonResponseUtil.success(iPointService.queryPointListByRouteId(routeId));
	}


	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "新*查询巡检点对应设备列表", notes = "新*查询巡检点对应设备列表")
	@GetMapping(value = "/equip-list-new", produces = "application/json;charset=UTF-8")
	public CommonResponse queryEquipListByPointId(
			@ApiParam(value = "巡检点ID") @RequestParam(value = "pointId") Long pointId) {
		return CommonResponseUtil.success(iPointService.queryEquipListByPointId(pointId));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "新*查询巡检点对应设备列表", notes = "新*查询巡检点对应设备列表")
	@GetMapping(value = "/item-list-new", produces = "application/json;charset=UTF-8")
	public CommonResponse queryItemList4RoutePoint(
			@ApiParam(value = "巡检点ID") @RequestParam(value = "pointId") Long pointId,
			@ApiParam(value = "设备ID") @RequestParam(value = "classifyId") Long classifyId) {
		return CommonResponseUtil.success(iPointService.queryItemList4RoutePoint(pointId, classifyId));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "新*查询巡检点对应设备列表新", notes = "新*查询巡检点对应设备列表新")
	@GetMapping(value = "/newQueryByIds", produces = "application/json;charset=UTF-8")
	public CommonResponse queryItemList4RoutePointNew(
			@ApiParam(value = "巡检点ID") @RequestParam(value = "pointId") Long pointId,
			@ApiParam(value = "设备ID") @RequestParam(value = "classifyId") Long classifyId,
			@ApiParam(value = "路线ID") @RequestParam(value = "routeId") Long routeId) {
		return CommonResponseUtil.success(iPointService.queryItemList4RoutePointNew(routeId,pointId, classifyId));
	}

		/**
	 * 更新巡检点
	 *
	 * @param newPointParam
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "更新巡检点", notes = "更新巡检点")
	@PutMapping(value = "/v3/updatePoint", produces = "application/json;charset=UTF-8")
	public CommonResponse updatePoint3(@ApiParam(value = "巡检点", required = true) @RequestBody NewPointParam newPointParam) {
		try {
			Point point = iPointService.updatePointNew(newPointParam);
			List<Long> ids = new ArrayList<>();
			ids.add(point.getId());
//			asyncTask.pushPointTo3D(ids);
			pushPointTo3D(getToken(), getProduct(), getAppKey(),ids);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("更新巡检点失败");
		}
	}
	/**
	 * 获取所属区域树
	 * @return
	 */

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "新*查询巡检点列表", notes = "新*查询巡检点列表")
	@GetMapping(value = "/regionTress", produces = "application/json;charset=UTF-8")
	public CommonResponse getRegionTress() {
		return CommonResponseUtil.success(iPointService.getRegionTress());
	}


/*********新增接口************/
	/**
	 * 增加巡检点
	 *
	 * @param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "新增巡检点", notes = "新增巡检点")
	@PostMapping(value = "/addPointNew", produces = "application/json;charset=UTF-8")
	public CommonResponse AddPointNew(@ApiParam(value = "巡检点", required = true) @RequestBody PointNewVo pointNewVo){
		AgencyUserModel user = getUserInfo();
		if (ObjectUtils.isEmpty(user)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		if (ObjectUtils.isEmpty(pointNewVo.getChargePersonId())) {
			return CommonResponseUtil.failure("责任人不能为空");
		}
		if (!ObjectUtils.isEmpty(pointNewVo.getName())) {
			List<Point> list = iPointDao.findByName(pointNewVo.getName(), pointNewVo.getId() != 0 ? String.valueOf(pointNewVo.getId()) : null);
			if (CollectionUtils.isNotEmpty(list)) {
				throw new BadRequest("该名称巡检点已存在");
			}
		}
		if (!ObjectUtils.isEmpty(pointNewVo.getName())) {
			List<Point> list = iPointDao.findByNo(pointNewVo.getPointNo(), pointNewVo.getId() != 0 ? String.valueOf(pointNewVo.getId()) : null);
			if (CollectionUtils.isNotEmpty(list)) {
				throw new BadRequest("该编号已存在");
			}
		}


		try {
			Point point = new Point();
			BeanUtils.copyProperties(pointNewVo,point);

			point.setIsIndoor(pointNewVo.getIsIndoor().equals("1") ? true : false);
			point.setOffline(pointNewVo.getOffline().equals("1") ? true : false);

			ReginParams reginParams = getSelectedOrgInfo();
			String loginOrgCode = getOrgCode(reginParams);
			point.setOrgCode(loginOrgCode);	//点归属于公司
			point.setCreatorId(user.getUserId());

			ResponseModel<Object> companyInfo = jcsFeignClient.getCompanyInfo(point.getChargeDeptId());
			Object obj = companyInfo.getResult();
			String bizOrgCode = ((Map<String, Object>) obj).get("bizOrgCode").toString();
			String bizOrgName = ((Map<String, Object>) obj).get("bizOrgName").toString();
			point.setBizOrgCode(bizOrgCode);
			point.setBizOrgName(bizOrgName);

			FeignClientResult userInfo = jcsFeignClient.selectById(point.getChargePersonId());
			Object result = userInfo.getResult();
			Map<String, Object> map = (Map<String, Object>) result;
			point.setChargePersonName(map.get("personName").toString());

			iPointService.addPointNew(point);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("巡检点新增失败");
		}
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "新增巡查对象", notes = "新增巡查对象")
	@GetMapping(value = "/xcdxIsExits", produces = "application/json;charset=UTF-8")
	public CommonResponse xcdxIsExits(Long pointId,String equipMentId){

		List<PointClassify> pointClassifies = iPointClassifyDao.queryByPointIdAndEquipmentId(pointId,equipMentId);

		if (pointClassifies.size() > 0){
			return CommonResponseUtil.success(false);
		}
		return CommonResponseUtil.success(true);
	}

	/**
	 * 查询巡检点信息
	 *
	 * @param point
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询巡检点信息", notes = "查询巡检点信息")
	@PostMapping(value = "/listNew", produces = "application/json;charset=UTF-8")
	public CommonResponse listPointNew(
			@ApiParam(value = "查询条件", required = false) @RequestBody(required = false)  PointQueryVo point,
			@RequestParam(value = "pageNumber", defaultValue = "1") int current,
			@RequestParam(value = "pageSize", defaultValue = "10") int size) {
		ReginParams reginParams = getSelectedOrgInfo();
		String loginOrgCode = getOrgCode(reginParams);
		String roleTypeName = getRoleTypeName(reginParams);
		if (ObjectUtils.isEmpty(reginParams)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {
			if (StringUtils.isEmpty(point.getBizOrgCode())){
				point.setBizOrgCode(reginParams.getPersonIdentity().getCompanyBizOrgCode());
			}

			IPage<PointVo> pointList = iPointService.queryPointInfoNew(point, current,size, loginOrgCode);
			return CommonResponseUtil.success(pointList);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("查询巡检点信息失败");
		}
	}
}
