package com.yeejoin.equipmanage.controller;

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.google.common.collect.Lists;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.equipmanage.common.entity.*;
import com.yeejoin.equipmanage.common.entity.dto.ImportantEquipmentListDTO;
import com.yeejoin.equipmanage.common.entity.vo.EquipmentAppVO;
import com.yeejoin.equipmanage.common.entity.vo.ImportantEquipmentVO;
import com.yeejoin.equipmanage.common.enums.IndustryEnum;
import com.yeejoin.equipmanage.common.utils.CommonResponseUtil;
import com.yeejoin.equipmanage.common.utils.ExcelUtils;
import com.yeejoin.equipmanage.common.utils.FileHelper;
import com.yeejoin.equipmanage.common.utils.StringUtil;
import com.yeejoin.equipmanage.common.vo.*;
import com.yeejoin.equipmanage.mapper.*;
import com.yeejoin.equipmanage.service.*;
import com.yeejoin.equipmanage.service.AbstractQRCodeFactory;
import com.yeejoin.equipmanage.service.IEquipmentService;
import com.yeejoin.equipmanage.service.IQRCodeService;
import com.yeejoin.equipmanage.service.IUploadFileService;
import com.yeejoin.equipmanage.service.impl.EquipmentDetailServiceImpl;
import com.yeejoin.equipmanage.service.impl.EquipmentServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseModel;
import ucar.ma2.ArrayLong;

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

/**
 *
 *
 * @author wujiang
 * @date 2020-07-07
 */
@RestController
@Api(tags = "装备定义Api")
@RequestMapping(value = "/equipment", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class EquipmentController extends AbstractBaseController {

	@Autowired
	IEquipmentService iEquipmentService;

	@Autowired
	IEquipmentParamsService iEquipmentParamsService;

	@Autowired
	private EquipmentMapper equipmentMapper;
	@Autowired
	private EquipmentDetailMapper equipmentDetailMapper;
	@Autowired
	private CarMapper carMapper;
	@Autowired
	private EquipmentIndexMapper equipmentIndexMapper;
	@Autowired
	private EquipmentCategoryMapper equipmentCategoryMapper;
	@Autowired
	private EquPropertyMapper equPropertyMapper;
	@Autowired
	private IUploadFileService iUploadFileService;
	@Autowired
	private UnitMapper unitMapper;
	@Resource(name = "qRCodeFactory")
	private AbstractQRCodeFactory abstractQRCodeFactory;

	/**
	 * 新增
	 *
	 * @return
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "POST", value = "新增", notes = "新增")
	public boolean saveEquipment(HttpServletRequest request, @RequestBody Equipment equipment) {
		return iEquipmentService.addEquipmentDef(equipment);
	}

//	@RequestMapping(value = "/saveEqu", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
//	@TycloudOperation(ApiLevel = UserType.AGENCY)
//	@ApiOperation(httpMethod = "POST", value = "新增", notes = "新增")
//	public EquipmentPar saveEqu(@RequestBody EquipmentPar equipmentPar) {
//		EquipmentDetail equ = equipmentPar.getEquipmentDetail();
//		String sysCode = equ.getCode();
//		EquipmentParams params = equipmentPar.getEquipmentParams();
//
//		if (StringUtils.isNotEmpty(sysCode) && StringUtils.isNotEmpty(sysCode.trim())){
//			int code = iEquipmentService.count(new QueryWrapper<Equipment>().eq("code", sysCode.trim()));
//			if (code != 0 ) {
//				equipmentPar.getEquipmentDetail().setMarkSpecification("设备编码填写重复，请重新输入！");
//				return equipmentPar;
//			}
//		}
//		iEquipmentService.save(equ);
//		params.setCode(equ.getCode());
//		iEquipmentParamsService.saveOne(params);
//		return equipmentPar;
//	}

	/**
	 * 根据id删除
	 *
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
	public boolean deleteById(HttpServletRequest request,
			@ApiParam(value = "装备定义idList", required = true) @RequestBody List<Long> ids) {
		List<Long> idList = Optional.ofNullable(ids).orElseThrow(IllegalArgumentException::new);
		try {
			iEquipmentService.deleteEquipments(idList);
			return true;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	@RequestMapping(value = "/checkDelete", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
	public String checkDelete(HttpServletRequest request,
			@ApiParam(value = "装备定义idList", required = true) @RequestBody List<Long> ids) {
		return iEquipmentService.checkDelete(ids);
	}

	/**
	 * 修改
	 *
	 * @return
	 */
	@RequestMapping(value = "/updateById", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "PUT", value = "修改", notes = "修改")
	public boolean updateByIdEquipment(HttpServletRequest request, @RequestBody Equipment equipment) {

		return iEquipmentService.editEquipmentDef(equipment);
	}

	/**
	 * 根据id查询
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
	public Equipment selectById(HttpServletRequest request, @PathVariable Long id) {
		Equipment byId = iEquipmentService.getById(id);
		Map<String, Object> columnMap = new HashMap<String, Object>();
		columnMap.put("equipment_id", id);
		List<EquipmentDetail> equipmentDetails = equipmentDetailMapper.selectByMap(columnMap);
		List<Car> cars = carMapper.selectByMap(columnMap);
		if (!equipmentDetails.isEmpty() || !cars.isEmpty()) {
			byId.setUse(true);
		}
		return byId;
	}

	/**
	 * 列表分页查询
	 *
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
	public IPage<Equipment> listPage(String pageNum, String pageSize, String name, String isIot) {
		Page pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
		List<Map<String, Object>> equipmentDefList = iEquipmentService.getWlZbdyByCondition(name, isIot,
				pageBean.getSize(), pageBean.offset());
		long count = iEquipmentService.getWlZbdyRowNum(name);
		pageBean.setTotal(count);
		pageBean.setRecords(equipmentDefList);
		return pageBean;
	}

	/**
	 * 获取装备新能参数列表
	 *
	 */
	@RequestMapping(value = "/queryPerfQuotaListByEquipId", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
	public IPage<Equipment> queryPerfQuotaListByEquipId(String pageNum, String pageSize, Long equipId) {
		Page pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
		List<Map<String, Object>> equipmentDefList = iEquipmentService.queryPerfQuotaByCondition(equipId,
				pageBean.getSize(), pageBean.offset());
		long count = iEquipmentService.countPerfQuotaByCondition(equipId);
		pageBean.setTotal(count);
		pageBean.setRecords(equipmentDefList);
		return pageBean;
	}

	/**
	 * 编辑指标项
	 *
	 */
	@RequestMapping(value = "/performanceindexTemp", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "PUT", value = "修改", notes = "修改")
	public boolean updateByIdEquipment(HttpServletRequest request, @RequestBody EquipmentIndex equipmentIndex) {

		if (null == equipmentIndex.getEquipmentId()) {
			throw new RuntimeException("装备参数传入失败或装备不存在！");
		}

		Equipment dt = equipmentMapper.selectById(equipmentIndex.getEquipmentId());
		if (dt == null) {
			throw new RuntimeException("装备参数传入失败或装备不存在！");
		}
		if (equipmentIndex.getIsImportentParameter()) {
			if (null == equipmentIndex.getIndexId()) {
				throw new RuntimeException("指标量参数传入失败或性能指标不存在！");
			}

			Map<String, Object> columnMap = new HashMap<String, Object>();
			columnMap.put("equipment_id", equipmentIndex.getEquipmentId());
			columnMap.put("index_definition_id", equipmentIndex.getIndexId());
			List<EquipmentIndex> perfQuotaTemp = equipmentIndexMapper.selectByMap(columnMap);

			if (null != perfQuotaTemp && perfQuotaTemp.size() > 0) {
				throw new RuntimeException("装备性能指标不能重复录入！");
			} else {
				columnMap.clear();
				columnMap.put("equipment_index_id", equipmentIndex.getEquipmentId());
				equPropertyMapper.deleteByMap(columnMap);
				equipmentIndexMapper.deleteById(equipmentIndex.getId());
				EquipmentIndex quota = new EquipmentIndex();
				quota.setEquipmentId(equipmentIndex.getEquipmentId());
				quota.setIndexId(equipmentIndex.getIndexId());
				quota.setIsImportentParameter(true);

				quota.setType(equipmentIndex.getType());
				equipmentIndexMapper.insert(quota);
				quota.setPerfGroupCode("groupcode-" + quota.getEquipmentId());
				equipmentIndexMapper.updateById(quota);
			}

			return true;

		} else {
			if (null != equipmentIndex.getPerfQuotaStr()) {
				Equipment equipment = equipmentMapper.selectById(equipmentIndex.getEquipmentId());
				if (StringUtil.isNotEmpty(equipment.getPrefQuota())) {
					equipment.setPrefQuota(equipmentIndex.getPerfQuotaStr());
				}
				equipmentMapper.updateById(equipment);
				return true;
			} else {
				throw new RuntimeException("传入参数失败！");
			}

		}
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "POST", value = "新增性能指标(<font color='blue'>release</font>)", notes = "")
	@RequestMapping(value = "/performanceindex", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public boolean addPerformanceIndex(
			@ApiParam(value = "性能指标", required = true) @RequestBody EquipmentIndex equipmentIndex) {
		if (null == equipmentIndex.getEquipmentId()) {
			throw new RuntimeException("装备参数传入失败或装备不存在！");
		}

		Equipment dt = equipmentMapper.selectById(equipmentIndex.getEquipmentId());
		if (dt == null) {
			throw new RuntimeException("装备参数传入失败或装备不存在！");
		}

		if (equipmentIndex.getIsImportentParameter()) {

			if (null == equipmentIndex.getIndexId()) {
				throw new RuntimeException("指标量参数传入失败或性能指标不存在！");
			}

			Map<String, Object> columnMap = new HashMap<String, Object>();
			columnMap.put("equipment_id", equipmentIndex.getEquipmentId());
			columnMap.put("index_definition_id", equipmentIndex.getIndexId());
			List<EquipmentIndex> perfQuotaTemp = equipmentIndexMapper.selectByMap(columnMap);

			if (null != perfQuotaTemp && perfQuotaTemp.size() > 0) {
				throw new RuntimeException("装备性能指标不能重复录入！");
			}

			Equipment equipment = equipmentMapper.selectById(equipmentIndex.getEquipmentId());
			String str = equipment.getCode().substring(0, 1);
			if ("2".equals(str)) {
				equipmentIndex.setType(equipmentIndex.getType());
			} else {
				equipmentIndex.setType(equipmentIndex.getType());
			}
			equipmentIndex.setPerfGroupCode("groupcode-" + equipmentIndex.getEquipmentId());
			equipmentIndexMapper.insert(equipmentIndex);

		} else {
			if (null != equipmentIndex.getPerfQuotaStr()) {
				Equipment equipment = equipmentMapper.selectById(equipmentIndex.getEquipmentId());
				if (StringUtil.isNotEmpty(equipment.getPrefQuota())) {
					equipment.setPrefQuota(equipment.getPrefQuota() + "\n" + equipmentIndex.getPerfQuotaStr());
				} else {
					equipment.setPrefQuota(equipmentIndex.getPerfQuotaStr());
				}
				equipmentMapper.insert(equipment);
			}
		}
		return true;
	}

	/***
	 * <pre>
	 * &#64;Description: 冗余代码
	 * </pre>
	 *
	 * @MethodName:
	 * @Param: [ids]
	 * @Return: boolean
	 * @Throws
	 * @Author keyong
	 * @Date 2020/10/27 17:31
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "DELETE", value = "根据Id删除多条性能指标记录(<font color='blue'>release</font>)", notes = "删除性能指标")
	@RequestMapping(value = "/perf-quota-definition", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
	public boolean deletePerfQuotaDefinition(@RequestBody List<KeyValue> ids) {
		for (KeyValue keyValue : ids) {
			if (keyValue.getKey()) {
				Map<String, Object> columnMap = new HashMap<String, Object>();
				columnMap.put("perf_quota_definition_id", keyValue.getValue());
				List<EquipmentIndex> perfQuotas = equipmentIndexMapper.selectByMap(columnMap);
				if (perfQuotas != null && !perfQuotas.isEmpty()) {
					throw new RuntimeException("该指标已被使用无法删除！");
				}
//				perfQuotaDefinitionMapper.deleteById(keyValue.getValue());
			} else {
				Equipment equipment = equipmentMapper.selectById(keyValue.getValue());
				equipment.setPrefQuota(null);
				equipmentMapper.updateById(equipment);
			}

		}
		return true;
	}

	/**
	 *
	 * 导入数据接口
	 *
	 **/
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "POST", value = "excel上传(<font color='blue'>release</font>)", notes = "上传excel同步数据库")
	@RequestMapping(value = "/upload-xls/{type}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public ResponseModel uploadXML(@PathVariable("type") String type,
			@RequestParam(value = "file") MultipartFile file) {
		try {
			long count = iUploadFileService.uploadFile(file, type);
			return CommonResponseUtil.success("已更新" + count + "条数据");
		} catch (Exception e) {
			e.printStackTrace();
			return CommonResponseUtil.failure(e.getMessage());
		}
	}

	// 扫描二维码
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "二维码查询数据", httpMethod = "POST", response = String.class, notes = "二维码查询数据")
	@RequestMapping(value = "/query/qrcode", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	public ResponseModel queryQRCode(@RequestBody QRCodeRequest request) {
		// 如果是查询装备详细
		try {
			IQRCodeService<ScanResult<QREquipResponse>> iQRCodeService = abstractQRCodeFactory
					.createScanService(request.getQrCode(), request.getType());
			return CommonResponseUtil.success(iQRCodeService.scan(request).get());
		} catch (RuntimeException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
	}

	/*
	 *
	 *
	 * 装备分类树
	 **/
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "按装备分类，获取该分类下级树(<font color='blue'>release</font>)", notes = "按装备分类，获取该分类下级树")
	@RequestMapping(value = "/query/classification/{code}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public List<EquipmentCategory> getAllEquipmentClassification(
			@ApiParam(value = "装备分类名称", required = true, defaultValue = "20000000") @PathVariable("code") String code,
			@RequestParam(required = false) String industryCode) {
		try {
			String idyCode = IndustryEnum.EQUIP.getCode();
			if (StringUtil.isNotEmpty(industryCode)) {
				idyCode = industryCode;
			}
			if (null != code) {
				Map<String, Object> columnMap = new HashMap<String, Object>();
				columnMap.put("code", code);
				columnMap.put("industry_code", idyCode);
				List<EquipmentCategory> equipCode = equipmentCategoryMapper.selectByMap(columnMap);
				if (equipCode == null || equipCode.size() < 1) {
					throw new RuntimeException("分类名称输入错误！");
				}
				columnMap.clear();
				columnMap.put("parent_id", equipCode.get(0).getId());
				List<EquipmentCategory> results = equipmentCategoryMapper.selectByMap(columnMap);

				return results;
			}

			throw new RuntimeException("分类名称输入错误！");

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

	/**
	 * <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/classification", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public List<StoreEquipmentClassificationResponse> getAllEquipmentClassification() {
		try {
			List<StoreEquipmentClassificationResponse> list = new ArrayList<>();
			List<EquipmentCategory> results = equipmentCategoryMapper.selectList(null);
			Map<String, List<StoreEquipmentClassificationResponse>> tmpMap = new HashMap<String, List<StoreEquipmentClassificationResponse>>();
			for (EquipmentCategory equip : results) {

				if (equip.getParentId() == null) {
					list.add(createEquipmentClassificationResponse(equip));
				} else {

					if (tmpMap.get(equip.getParentId().toString()) == null) {
						ArrayList<StoreEquipmentClassificationResponse> tmplist = new ArrayList<StoreEquipmentClassificationResponse>();
						tmplist.add(createEquipmentClassificationResponse(equip));
						tmpMap.put(equip.getParentId().toString(), tmplist);
					} else {
						if (!tmpMap.get(equip.getParentId().toString())
								.contains(createEquipmentClassificationResponse(equip))) {

							tmpMap.get(equip.getParentId().toString())
									.add(createEquipmentClassificationResponse(equip));
						}
					}

				}

			}
			getChildren(list, tmpMap);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("系统异常！");
		}
	}

	/**
	 * 获取子节点
	 *
	 * @param list
	 * @param tmpMap
	 */
	private void getChildren(List<StoreEquipmentClassificationResponse> list,
			Map<String, List<StoreEquipmentClassificationResponse>> tmpMap) {
		for (StoreEquipmentClassificationResponse Root : list) {
			if (tmpMap.get(Root.getEquipmentClassificationId()) != null
					&& tmpMap.get(Root.getEquipmentClassificationId()).size() > 0) {
				List<StoreEquipmentClassificationResponse> equipcliss = tmpMap.get(Root.getEquipmentClassificationId());
				Root.setHasLowerClassification(true);
				Root.setChildren(equipcliss);
				getChildren(equipcliss, tmpMap);
			}

		}

	}

	public StoreEquipmentClassificationResponse createEquipmentClassificationResponse(EquipmentCategory instance) {
		StoreEquipmentClassificationResponse respnse = new StoreEquipmentClassificationResponse();

		if (StringUtil.isNotEmpty(instance.getId())) {
			respnse.setEquipmentClassificationId(instance.getId().toString());
		}

		if (StringUtil.isNotEmpty(instance.getName())) {
			respnse.setEquipmentClassificationName(instance.getName());
			respnse.setLabel(instance.getName());
		}
		if (StringUtil.isNotEmpty(instance.getParentId())) {
			respnse.setParentId(instance.getParentId());
		}

		if (StringUtil.isNotEmpty(instance.getCode())) {
			respnse.setEquipmentClassificationCode(instance.getCode());
			respnse.setValue(instance.getCode());
		}

		if (StringUtil.isNotEmpty(instance.getRemark())) {
			respnse.setRemark(instance.getRemark());

		}

		if (StringUtil.isNotEmpty(instance.getLevel())) {
			respnse.setLevel(instance.getLevel());
		}

		if (StringUtil.isNotEmpty(instance.getIsConsumptive()))

		{
			boolean bool = instance.getIsConsumptive();
			respnse.setConsumeEquipment(bool);
		}

		respnse.setHasLowerClassification(instance.isHasLowerClassification());

		return respnse;
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "按计量单位，获取该分类下级树(<font color='blue'>release</font>)", notes = "按计量单位分类，获取该分类下级树")
	@RequestMapping(value = "/query/calculateUnitClassification", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public List<CalculateUnitResponse> getAllCalculateUnitClassification() {
		try {
			List<Unit> results = unitMapper.selectList(null);

			List<CalculateUnitResponse> list = new ArrayList<>();
			for (Unit instance : results) {

				if (instance.getParentId() == null || "".equals(instance.getParentId() + "")) {
					list.add(createCalculateUnitResponse(instance));
				} else {
					getUnitChildren(list, instance.getParentId().toString()).add(createCalculateUnitResponse(instance));
				}

			}

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

	/**
	 *
	 *
	 * 获取子节点
	 *
	 **/
	private List<CalculateUnitResponse> getUnitChildren(List<CalculateUnitResponse> list, String id) {
		List<CalculateUnitResponse> temp = new ArrayList<>();
		for (CalculateUnitResponse instance : list) {
			if (!instance.getUnitClassificationId().equals(id)) {
				temp = getUnitChildren(instance.getChildren(), id);
				if (null != temp) {
					break;
				}
			} else {
				instance.setHasLowerClassification(true);
				temp = instance.getChildren();
				break;
			}
		}
		return temp;
	}

	/***
	 *
	 * 返回结果封装
	 *
	 **/
	public CalculateUnitResponse createCalculateUnitResponse(Unit instance) {

		CalculateUnitResponse respnse = new CalculateUnitResponse();

		if (StringUtil.isNotEmpty(instance.getId().toString())) {
			respnse.setUnitClassificationId(instance.getId().toString());
		}

		if (StringUtil.isNotEmpty(instance.getName())) {
			respnse.setUnitName(instance.getName());
		}

		if (StringUtil.isNotEmpty(instance.getCode())) {
			respnse.setUnitCode(instance.getCode());
		}

		if (StringUtil.isNotEmpty(instance.getDescription())) {
			respnse.setUnitDescription(instance.getDescription());
		}

		if (StringUtil.isNotEmpty(instance.getParentId())) {
			respnse.setParentId(instance.getParentId().toString());
		}

		return respnse;
	}

	/**
	 * 分类查询
	 *
	 * @return
	 */
	@RequestMapping(value = "/list/{categoryId}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
	public List<Equipment> listPage(@PathVariable Long categoryId) {
		return iEquipmentService.listByCategoryId(categoryId);
	}

	@RequestMapping(value = "/listLike/{code}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
	public List<Map<String, Object>> listLikePage(@PathVariable String code) {
		List<Map<String, Object>> existEquipments = equipmentMapper.listLikePage(code);
		return existEquipments;
	}

	/**
	 * 设备信息
	 *
	 * @return
	 */
	@GetMapping(value = "/detail")
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "获取设备详情", notes = "获取设备详情")
	public EquipmentAppVO detail(String qrCode) {
		return iEquipmentService.getEquipmentAppMessage(qrCode);
	}

	/**
	 * 设备信息
	 *
	 * @return
	 */
	@PostMapping(value = "/getImportantEquipmentList")
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "POST", value = "获取重点设备列表", notes = "获取重点设备列表")
	public List<ImportantEquipmentVO> getImportantEquipmentList(
			@RequestBody ImportantEquipmentListDTO importantEquipmentListDTO) {
		return iEquipmentService.getImportantEquipmentList(importantEquipmentListDTO.getIds());
	}

	@GetMapping(value = "/getViewSearchOption")
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "获取三维下拉搜索列表", notes = "获取三维下拉搜索列表")
	public List<EquipmentVo> getViewSearchOption(@RequestParam String type) {
		if ("riskSource".equalsIgnoreCase(type)) {
			List<EquipmentVo> list = new ArrayList<>();
			EquipmentVo equipmentVo = new EquipmentVo();
			equipmentVo.setName("风险点");
			equipmentVo.setType(type);
			list.add(equipmentVo);
			return list;
		} else if ("patrol".equalsIgnoreCase(type)) {
			List<EquipmentVo> list = iEquipmentService.getEquipListBySpecific();
			EquipmentVo equipmentVo = new EquipmentVo();
			equipmentVo.setName("巡检点");
			equipmentVo.setType("patrol");
			list.add(0, equipmentVo);
			return list;
		}
		return Lists.newArrayList();
	}

	@GetMapping(value = "/getEquipmentNameAndCode")
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "获取装备名称下拉列表", notes = "获取装备名称下拉列表")
	public List<Map<String, Object>> getEquipmentNameAndCode() {
		return iEquipmentService.getEquipmentNameAndCode();
	}

	@GetMapping(value = "/list-all")
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询装备定义不分页-列表", notes = "查询装备定义不分页-列表")
	public List<Equipment> listAll() {
		return iEquipmentService.getAll();
	}


}
