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

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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.patrol.business.dao.mapper.InputItemMapper;
import com.yeejoin.amos.patrol.business.feign.JcsFeignClient;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import com.yeejoin.amos.patrol.business.dao.repository.IPointInputItemDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.patrol.business.dao.repository.IInputItemDao;
import com.yeejoin.amos.patrol.business.param.InputItemPageParam;
import com.yeejoin.amos.patrol.business.param.InputItemParam;
import com.yeejoin.amos.patrol.business.service.intfc.IInputItemService;
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.InputItemParamUtil;
import com.yeejoin.amos.patrol.business.vo.InputItemVo;
import com.yeejoin.amos.patrol.business.vo.PointInputItemVo;
import com.yeejoin.amos.patrol.common.enums.DictTypeEnum;
import com.yeejoin.amos.patrol.core.common.request.CommonPageable;
import com.yeejoin.amos.patrol.core.common.request.CommonRequest;
import com.yeejoin.amos.patrol.core.enums.QueryOperatorEnum;
import org.typroject.tyboot.core.foundation.enumeration.UserType; import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import com.yeejoin.amos.patrol.core.util.StringUtil;
import com.yeejoin.amos.patrol.dao.entity.InputItem;

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;

/**
 * 检查项
 *
 * @author gaodongdong
 *
 */
@RestController
@RequestMapping(value = "/api/inputItem")
@Api(tags = "巡检项api")
public class InputItemController extends AbstractBaseController {

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

	@Autowired
	IInputItemService inputItemService;
	@Autowired
	IInputItemDao inputItemDao;
	@Autowired
	JcsFeignClient jcsFeignClient;
	@Autowired
	InputItemMapper inputItemMapper;
	@Autowired
	IPointInputItemDao iPointInputItemDao;

	@Value("${equipment.hierarchy}")
	private String hierarchy;

	@Autowired
	private RedisUtils redisUtils;

	/**
	 * 检查项列表左侧树缓存Key
	 */
	private static final String EQUIP_AND_FIRE_TREE = "EQUIP_AND_FIRE_TREE:";


/**
 * 新加接口*****************************************************************************
 * */

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "分页查询检查项", notes = "分页查询检查项")
	@RequestMapping(value = "/queryItemByPageNew", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public CommonResponse queryItemByPageNew(
			@ApiParam(value = "组合查询条件", required = false, defaultValue = "[]") @RequestBody(required = false) InputItemPageParam criterias,
			@ApiParam(value = "分页参数", required = false, defaultValue = "current=0&pageSize=10或pageNumber0&pageSize=10") CommonPageable pageable,
			@ApiParam(value = "树code")@RequestParam(required = false) String treeId) {
		int inhierarchy = 1;
		String subCode = "";
		if (StringUtil.isNotEmpty(treeId) && Long.parseLong(treeId.replace("@","")) > 0) {
			String[] result = hierarchy.split(",");
			Map<Integer, Integer> map = new HashMap<>();
			for (int i = 0; i < result.length; i++) {
				map.put(i, Integer.valueOf(result[i]));
			}

			Map<String, String> equipmentCategory = inputItemMapper.getCategoryByCode(treeId.replace("@",""), "2");
			if (equipmentCategory == null) {
				throw new RuntimeException("装备定义code有误");
			}


			for (int i = 0; i < result.length + 1; i++) {
				//进来先判断是否默认就是空，如果为空第一层
				if (!StringUtil.isNotEmpty(equipmentCategory.get("parentId"))) {
					//判断是否是最下面的子节点
					if (i >= 4) {
						inhierarchy = 8;
					} else {
						inhierarchy = map.get(i);
					}
					break;
				} else {
					//查找到循环几次为空
					equipmentCategory = inputItemMapper.getCategoryById(equipmentCategory.get("parentId"));
				}
			}
			subCode = treeId.replace("@","").substring(0, inhierarchy);
		}
		ReginParams reginParams = getSelectedOrgInfo();
		//查询向上查询所属单位的bizOrgCode
		String bizOrgCode = reginParams.getPersonIdentity().getCompanyBizOrgCode();
		criterias.setBizOrgCode(bizOrgCode);
		if (pageable != null) {
			criterias.setPageNumber(pageable.getPageNumber()-1);
			criterias.setPageSize(pageable.getPageSize());
		}
		criterias.setTreeId(treeId);
		criterias.setInhierarchy(inhierarchy);
		criterias.setSubCode(subCode);
		Page<InputItemVo> page = inputItemService.queryInputItemByPageNew(criterias);
		List<Map<String, String>> allCategoryNameList = inputItemMapper.getAllCategoryName();
		Map<String, String> resultMap = new HashMap<>();
		for (Map<String, String> map : allCategoryNameList) {
			resultMap.put(map.get("code"), map.get("name"));
		}
		for (InputItemVo inputItemVo : page.getContent()) {
			String finalTypeName = "";
			finalTypeName = StringUtils.isNotEmpty(inputItemVo.getCustomType())? "自定义巡检点" : "";
			String keyPartsTypeName = StringUtils.isNotEmpty(inputItemVo.getKeyPartsType())? "重点部位类型" : "";
			if (StringUtils.isNotEmpty(finalTypeName) && StringUtils.isNotEmpty(keyPartsTypeName)) {
				finalTypeName = finalTypeName + "，" + keyPartsTypeName;
			} else if (!StringUtils.isNotEmpty(finalTypeName) && StringUtils.isNotEmpty(keyPartsTypeName)) {
				finalTypeName = keyPartsTypeName;
			}
			String equipmentTypeName = StringUtils.isNotEmpty(inputItemVo.getEquipmentType())? resultMap.get(inputItemVo.getEquipmentType()) : "";
			if (StringUtils.isNotEmpty(finalTypeName) && StringUtils.isNotEmpty(equipmentTypeName)) {
				finalTypeName = finalTypeName + "，" + equipmentTypeName;
			} else if (!StringUtils.isNotEmpty(finalTypeName) && StringUtils.isNotEmpty(equipmentTypeName)) {
				finalTypeName = equipmentTypeName;
			}
			String facilitiesTypeName = StringUtils.isNotEmpty(inputItemVo.getFacilitiesType())? resultMap.get(inputItemVo.getFacilitiesType()) : "";
			if (StringUtils.isNotEmpty(finalTypeName) && StringUtils.isNotEmpty(facilitiesTypeName)) {
				finalTypeName = finalTypeName + "，" + facilitiesTypeName;
			} else if (!StringUtils.isNotEmpty(finalTypeName) && StringUtils.isNotEmpty(facilitiesTypeName)) {
				finalTypeName = facilitiesTypeName;
			}
			inputItemVo.setTypeName(finalTypeName);
		}
			return CommonResponseUtil.success(page);
	}

/**
 * 新加接口*****************************************************************************
 * */


	/*******新增接口************/
	/**
	 * 查询巡检项详情
	 *
	 * @param itemID
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "检查项ID新", notes = "检查项详情新")
	@RequestMapping(value = "/queryItemNew", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse queryItemDetailNew(@ApiParam(value = "巡检项ID") @RequestParam(required = true) Long itemID) {
		InputItem bo = inputItemService.queryInputItemDetail(itemID);
		InputItemParam inputItemVo = new InputItemParam();
		BeanUtils.copyProperties(bo,inputItemVo);
		if(inputItemVo.getItemType().equals("文本")){
			Map<String,Object> map= JSONObject.parseObject(bo.getDataJson(),Map.class);
			inputItemVo.setOkScore(Integer.valueOf(map.get("OkScore").toString()));
			inputItemVo.setNoScore(Integer.valueOf(map.get("NoScore").toString()));
			inputItemVo.setCheckType(map.get("CheckType")!=null?map.get("CheckType").toString():null);
		}else if(inputItemVo.getItemType().equals("数字")){
			Map<String,Object> map= JSONObject.parseObject(bo.getDataJson(),Map.class);
			inputItemVo.setOkScore(Integer.valueOf(map.get("OkScore").toString()));
		    inputItemVo.setNoScore(Integer.valueOf(map.get("NoScore").toString()));
			inputItemVo.setValidUp("".equals(map.get("ValidUp").toString())?null:Integer.valueOf(map.get("ValidUp").toString()));
			inputItemVo.setValidDown("".equals(map.get("ValidDown").toString())?null:Integer.valueOf(map.get("ValidDown").toString()));
			inputItemVo.setOkUp("".equals(map.get("OkUp").toString())?null:Integer.valueOf(map.get("OkUp").toString()));
			inputItemVo.setOkDown("".equals(map.get("OkDown").toString())?null:Integer.valueOf(map.get("OkDown").toString()));
			inputItemVo.setCheckValidUp(Boolean.valueOf(map.get("CheckValidUp").toString())?"true":"false");
			inputItemVo.setCheckValidDown(Boolean.valueOf(map.get("CheckValidDown").toString())?"true":"false");
			inputItemVo.setCheckOkUp(Boolean.valueOf(map.get("CheckOkUp").toString())?"true":"false");
			inputItemVo.setCheckOkDown(Boolean.valueOf(map.get("CheckOkDown").toString())?"true":"false");
			inputItemVo.setPrecision(Integer.valueOf(map.get("Precision").toString()));
		}else{
			inputItemVo.setDataJson(bo.getDataJson() != null?JSONObject.parse(bo.getDataJson()):null);
		}
		inputItemVo.setPictureJson(bo.getPictureJson()!=null?JSONObject.parse(bo.getPictureJson()):null);
		return CommonResponseUtil.success(inputItemVo);
	}


	/**
	 * 新增巡检项
	 *
	 * @param param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "新增检查项", notes = "新增检查项")
	@RequestMapping(value = "/addItem", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public CommonResponse addNewItem(@ApiParam(value = "检查项信息") @RequestBody InputItemParam param) {
		if (ObjectUtils.isEmpty(param.getId())) {
			return updateItem(param);
		}
		 AgencyUserModel user = getUserInfo();
		if (ObjectUtils.isEmpty(user)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {
			InputItem inputItem = new InputItem();
			 ReginParams reginParams = getSelectedOrgInfo();
	         String loginOrgCode = getOrgCode(reginParams);

			BeanUtils.copyProperties(param, inputItem);
			///LoginUserParam loginParam = getLoginUserParam();
			  inputItem.setOrgCode(loginOrgCode);
			  inputItem.setCreateBy(user.getUserId());
			inputItemService.addNewInputItem(inputItem);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			return CommonResponseUtil.failure("检查项新增失败: " + e.getMessage());
		}
	}


	/**
	 * 查询巡检项详情
	 *
	 * @param itemID
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "检查项ID", notes = "检查项详情")
	@RequestMapping(value = "/queryItem", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse queryItemDetail(@ApiParam(value = "巡检项ID") @RequestParam(required = true) Long itemID) {
		InputItem bo = inputItemService.queryInputItemDetail(itemID);
		return CommonResponseUtil.success(bo);
	}

	/**
	 *
	 * @param param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "更新检查项", notes = "更新检查项")
	@RequestMapping(value = "/updateItem", produces = "application/json;charset=UTF-8", method = RequestMethod.PUT)
	public CommonResponse updateItem(@ApiParam(value = "检查项详情", required = false) @RequestBody InputItemParam param) {
		if (ObjectUtils.isEmpty(param.getId())) {
			return addNewItem(param);
		}
		AgencyUserModel user = getUserInfo();
		if (ObjectUtils.isEmpty(user)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {
			InputItem inputItem = new InputItem();
			BeanUtils.copyProperties(param, inputItem);
			inputItem.setId(param.getId());
			// inputItem.setCreateBy(Integer.parseInt(user.getId() +""));
			inputItemService.updateInputItem(inputItem);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			return CommonResponseUtil.failure("检查项新增失败: " + e.getMessage());
		}
	}

	/**
	 * 批量删除检查项
	 *
	 * @param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "批量删除检查项", notes = "批量删除检查项")
	@RequestMapping(value = "/batchDelItem", produces = "application/json;charset=UTF-8", method = RequestMethod.DELETE)
	public CommonResponse batchDelItem(
			@ApiParam(value = "巡检项ID(检查项id以英文半角逗号分割。如： 1,2)") @RequestParam(required = true) String itemIDs) {
		try {
			ReginParams reginParams = getSelectedOrgInfo();
			if (ObjectUtils.isEmpty(itemIDs)) {
				return CommonResponseUtil.failure("请选择要删除的检查项");
			}
			//查询该巡查项是否已有巡查点绑定 有就返回
			if (iPointInputItemDao.selectByITemId(itemIDs) > 0) {
				return CommonResponseUtil.failure("该巡检项已绑定，请先删除巡检设备的巡检项");
			}
			String[] ids = itemIDs.split(",");
			inputItemService.batchDelInputItem(ids);
			redisUtils.del(EQUIP_AND_FIRE_TREE + (reginParams.getPersonIdentity().getBizOrgCode() == null? "" :reginParams.getPersonIdentity().getBizOrgCode()));
			return CommonResponseUtil.success();
		} catch (Exception e) {
			return CommonResponseUtil.failure("检查项新增失败: " + e.getMessage());
		}
	}

	/**
	 * 删除检查项
	 *
	 * @param itemID
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "删除检查项", notes = "删除检查项")
	@RequestMapping(value = "/delItem", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse delItem(@ApiParam(value = "巡检项ID") @RequestParam(required = true) Long itemID) {
		try {
			inputItemService.delInputItem(itemID);
			return CommonResponseUtil.success();
		} catch (Exception e) {
			return CommonResponseUtil.failure("检查项新增失败: " + e.getMessage());
		}
	}

	/**
	 * 检查项另存为
	 *
	 * @param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "检查项另存为", notes = "检查项另存为")
	@RequestMapping(value = "/saveAs", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse saveAs(@ApiParam(value = "巡检项ID") @RequestParam(required = true) String itemIDs) {
		AgencyUserModel user = getUserInfo();
		if (ObjectUtils.isEmpty(user)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		try {
			if (ObjectUtils.isEmpty(itemIDs)) {
				return CommonResponseUtil.failure("请选择要另存的检查项");
			}
			String[] ids = itemIDs.split(",");
			inputItemService.saveAs(ids, user.getUserId());
			return CommonResponseUtil.success();
		} catch (Exception e) {
			return CommonResponseUtil.failure("检查项另存为失败: " + e.getMessage());
		}
	}

	/**
	 * 分页查询检查项
	 *
	 * @param queryRequests
	 * @param pageable
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "分页查询检查项", notes = "分页查询检查项")
	@RequestMapping(value = "/queryItemByPage", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public CommonResponse queryItemByPage(
			@ApiParam(value = "组合查询条件", required = false, defaultValue = "[]") @RequestBody(required = false) List<CommonRequest> queryRequests,
			@ApiParam(value = "分页参数", required = false, defaultValue = "current=0&pageSize=10或pageNumber0&pageSize=10") CommonPageable pageable) {
		//LoginUserParam user = CurUserCompanyCache.getInstance().getCurCompany(getUserId(), getToken());

		  ReginParams reginParams = getSelectedOrgInfo();
//	        String loginOrgCode = getOrgCode(reginParams);
		String bizOrgCode = reginParams.getPersonIdentity().getCompanyBizOrgCode();


		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("bizOrgCode", bizOrgCode);
		InputItemPageParam criterias = InputItemParamUtil.fillInputItemPageParam(queryRequests, pageable, paramMap);
		Page<InputItemVo> page = inputItemService.queryInputItemByPage(criterias);
		return CommonResponseUtil.success(page);
	}

	/**
	 * 条件查询检查项
	 *
	 * @param queryRequests
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/queryItemByCondition", produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "条件查询检查项", notes = "条件查询检查项")
	public CommonResponse queryItemByCondition(
			@ApiParam(value = "组合查询条件", required = false, defaultValue = "[]") @RequestBody(required = false) List<CommonRequest> queryRequests) {
		// 1.组织查询条件数据
		 ReginParams reginParams = getSelectedOrgInfo();
	        String loginOrgCode = getOrgCode(reginParams);
	        String roleTypeName = getRoleTypeName(reginParams);
        List<DaoCriteria> criterias = buildDaoCriterias(queryRequests, false, loginOrgCode, roleTypeName);
		// 2.组织数据权限过滤条件，基础数据不管roleType，全按照选择的公司orgCode过滤

		DaoCriteria compDaoCriteria = new DaoCriteria();
		compDaoCriteria.setPropertyName("orgCode");
		compDaoCriteria.setOperator(QueryOperatorEnum.EQUAL.getName());
		compDaoCriteria.setValue(loginOrgCode);
		criterias.add(compDaoCriteria);
		List<InputItem> list = inputItemService.queryInputItemByCondition(criterias);
		return CommonResponseUtil.success(list);
	}
	/**
	 * 条件查询检查项
	 *
	 * @param params
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping (value = "/queryCustomInputItem", produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "条件查询检查项", notes = "条件查询检查项")
	public CommonResponse queryCustomInputItem( @RequestBody HashMap<String,Object> params){
		ReginParams reginParams = getSelectedOrgInfo();
		String orgCode = getOrgCode(reginParams);
		List<PointInputItemVo> list = inputItemService.queryCustomInputItem(params.get("itemType").toString(),params.get("nameOrItemNo").toString(),orgCode);
		return CommonResponseUtil.success(list);
	}


	/**
	 * 条件查询检查项
	 *
	 * @param params
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping (value = "/queryCustomInputItemNew", produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "条件查询检查项", notes = "条件查询检查项")
	public CommonResponse queryCustomInputItemNew( @RequestBody HashMap<String,Object> params){
		ReginParams reginParams = getSelectedOrgInfo();
		String orgCode = getOrgCode(reginParams);
		String companyBizOrgCode = reginParams.getPersonIdentity().getCompanyBizOrgCode();

		List<PointInputItemVo> list = inputItemService.queryCustomInputItemNew(params,orgCode,companyBizOrgCode);
		return CommonResponseUtil.success(list);
	}
	/**
	 * 条件查询检查项
	 *
	 * @param queryRequests 查询条件
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/queryItemByCondition1", produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "条件查询检查项", notes = "条件查询检查项")
	public CommonResponse queryItemByCondition1(
			@ApiParam(value = "组合查询条件", required = false, defaultValue = "[]") @RequestBody(required = false) List<CommonRequest> queryRequests) {
		// 组织数据权限过滤条件，基础数据不管roleType，全按照选择的公司orgCode过滤
		 ReginParams reginParams = getSelectedOrgInfo();
	        String loginOrgCode = getOrgCode(reginParams);
		List<InputItem> list = null;

		if (ObjectUtils.isEmpty(queryRequests)) {
			list = inputItemDao.findAllByLevel(loginOrgCode);
		} else {
			String level = null;
			for (CommonRequest quest : queryRequests) {
				if (quest.getName().equals("level")) {
					if (StringUtil.isNotEmpty(quest.getValue())) {
						if (quest.getValue().toString().equals("-0")) {  //如果前台传过来等级条件为-0，数据库则存储为空
							level = null;
						} else {
							level = quest.getValue().toString();
						}
					}

				}
			}
			if(ObjectUtils.isEmpty(level)){
				list = inputItemDao.findByLevelNull(loginOrgCode);
			}else{
				list = inputItemDao.findByLevel(loginOrgCode, level);
			}
		}
		return CommonResponseUtil.success(list);
	}

	/**
	 * 查询检查项编号信息
	 *
	 * @param itemId  检查项id,如果为新增，则为-1
	 *
	 * @param queryRequests  查询条件
	 *
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询巡检点编号信息", notes = "查询巡检点编号信息")
	@GetMapping(value = "/queryItemNo/{itemId}", produces = "application/json;charset=UTF-8")
	public CommonResponse queryItemNoList(
			@ApiParam(value = "巡检点id", required = true) @PathVariable(name = "itemId") Long itemId,
			@ApiParam(value = "查询条件", required = false) @RequestBody(required = false) List<CommonRequest> queryRequests) {
		 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);
			if (queryRequests == null) {
				queryRequests = new ArrayList<>();
			}
			queryRequests.add(commonRequest);
            List<DaoCriteria> criterias = buildDaoCriterias(queryRequests, false, loginOrgCode, roleTypeName);

			List<String> pointNoList = inputItemService.qryItemNoList(criterias, itemId);
			return CommonResponseUtil.success(pointNoList);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return CommonResponseUtil.failure("查询检查项编号信息失败");
		}
	}

    @TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "获取检查分类", notes = "获取检查分类")
	@GetMapping(value = "/checkClassify")
	public CommonResponse getCheckClassify() {
		return CommonResponseUtil.success(inputItemService.getCheckClassify(getToken(), getProduct(), getAppKey(), DictTypeEnum.CHECK_CLASSIFY.getCode()));
	}

	/*******新增接口************/
	/**
	 * 新增巡检项
	 *
	 * @param param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "新增检查项", notes = "新增检查项")
	@RequestMapping(value = "/addItemNew", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public CommonResponse addNewItemNew(@ApiParam(value = "检查项信息") @RequestBody InputItemParam param) {

		if (param.getEquipmentType() == null && param.getCustomType() == null&&param.getFacilitiesType() == null&&param.getKeyPartsType() == null){
			throw new BadRequest("适用类型至少需选择一项");
		}

		if (CollectionUtils.isNotEmpty(inputItemDao.findByItemNo(param.getItemNo(), param.getId() != 0 ? String.valueOf(param.getId()) : null))) {
			throw new BadRequest("该编号已存在,请重新输入");
		}

		if (CollectionUtils.isNotEmpty(inputItemDao.findByItemName(param.getName(), param.getId() != 0 ? String.valueOf(param.getId()) : null))) {
			throw new BadRequest("该名称已存在,请重新输入");
		}

		//如果为1则为否，顺应机场逻辑
		param.setCustomType("1".equals(param.getCustomType()) ? null : param.getCustomType());
		param.setKeyPartsType("1".equals(param.getKeyPartsType()) ? null : param.getKeyPartsType());
		AgencyUserModel user = getUserInfo();
		if (ObjectUtils.isEmpty(user)) {
			return CommonResponseUtil.failure("用户session过期");
		}
		   List dt=new ArrayList<>();
		if(param.getDataJson()==null){
			param.setDataJson(dt);
		}
		if(param.getPictureJson()==null){
			param.setPictureJson(dt );
		}

		try {
			InputItem inputItem = new InputItem();
			ReginParams reginParams = getSelectedOrgInfo();
			String loginOrgCode = getOrgCode(reginParams);
			BeanUtils.copyProperties(param, inputItem);
			if(param.getPictureJson() != null){
				List<Map<String,Object>>   listr = (List<Map<String,Object>>)param.getPictureJson();
				for (int i = 0; i < listr.size(); i++) {
					listr.get(i).remove("Symbol_key");
					listr.get(i).put("orderNo",i);
				}
				inputItem.setPictureJson(JSONObject.toJSONString(listr));
			}

			inputItem.setBizOrgCode(reginParams.getPersonIdentity().getBizOrgCode() == null? null :reginParams.getPersonIdentity().getBizOrgCode() );
			inputItem.setBizOrgName(reginParams.getPersonIdentity().getCompanyName()== null? null :reginParams.getPersonIdentity().getCompanyName());
			inputItem.setOrgCode(loginOrgCode);
			inputItem.setCreateBy(user.getUserId());

			if(param.getItemType().equals("文本")){

				Map<String,Object> map=new HashMap<>();
				map.put("OkScore",param.getOkScore()!=null?param.getOkScore():0);
				map.put("NoScore",param.getNoScore()!=null?param.getNoScore():0);
				map.put("CheckType",param.getCheckType());
				inputItem.setDataJson(JSONObject.toJSONString(map));

			}else if(param.getItemType().equals("选择")){
				if(param.getDataJson() != null){
					List<Map<String,Object>>   listr = (List<Map<String,Object>>)param.getDataJson();
					for (int i = 0; i < listr.size(); i++) {
						listr.get(i).remove("Symbol_key");
						listr.get(i).put("orderNo",i);
					}
					inputItem.setDataJson(JSONObject.toJSONString(listr));
				}
			}else{
				Map<String,Object> map=new HashMap<>();
				map.put("OkScore",param.getOkScore()!=null?param.getOkScore():0);
				map.put("NoScore",param.getNoScore()!=null?param.getNoScore():0);
				map.put("ValidUp",param.getValidUp()!=null?param.getValidUp():"");
				map.put("ValidDown",param.getValidDown()!=null?param.getValidDown():"");
				map.put("OkUp",param.getOkUp()!=null?param.getOkUp():"");
				map.put("OkDown",param.getOkDown()!=null?param.getOkDown():"");
				map.put("CheckValidUp",param.getCheckValidUp().equals("false")?false:true);
				map.put("CheckValidDown",param.getCheckValidDown().equals("false")?false:true);
				map.put("CheckOkUp",param.getCheckOkUp().equals("false")?false:true);
				map.put("CheckOkDown",param.getCheckOkDown().equals("false")?false:true);
				map.put("Precision",param.getPrecision()!=null?param.getPrecision():0);
				inputItem.setDataJson(JSONObject.toJSONString(map));
			}
			if (!ObjectUtils.isEmpty(param.getId())) {
				inputItem.setId(param.getId());
			inputItemService.updateInputItem(inputItem);
			}
			redisUtils.del(EQUIP_AND_FIRE_TREE + (reginParams.getPersonIdentity().getBizOrgCode() == null? "" :reginParams.getPersonIdentity().getBizOrgCode()));
			return CommonResponseUtil.success();
		} catch (Exception e) {
			return CommonResponseUtil.failure("检查项新增失败: " + e.getMessage());
		}
	}


}
