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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.excel.ExcelUtil;
import com.yeejoin.amos.boot.biz.common.interceptors.PermissionInterceptorContext;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.patrol.business.dao.mapper.InputItemMapper;
import com.yeejoin.amos.patrol.business.dao.repository.IInputItemDao;
import com.yeejoin.amos.patrol.business.dao.repository.IPointInputItemDao;
import com.yeejoin.amos.patrol.business.dto.InputItemDataDto;
import com.yeejoin.amos.patrol.business.dto.InputItemDataJsonlDto;
import com.yeejoin.amos.patrol.business.dto.InputItemExcelDto;
import com.yeejoin.amos.patrol.business.dto.InputItemExcelVo;
import com.yeejoin.amos.patrol.business.feign.JcsFeignClient;
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.common.request.ToJson;
import com.yeejoin.amos.patrol.core.enums.QueryOperatorEnum;
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 liquibase.pro.packaged.S;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
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.*;
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.exception.instance.BadRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 检查项
 *
 * @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;
	@Value("${auth-key-auth-enabled:}")
	private String authKey;

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

	private static final String ITEMTYPE = "选择,文本:";


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

	@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]));
			}

			// 权限处理
			PermissionInterceptorContext.setDataAuthRule(authKey);
			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 {
					// 权限处理
					PermissionInterceptorContext.setDataAuthRule(authKey);
					//查找到循环几次为空
					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;
//			}
			if ("1".equals(inputItemVo.getCustomType()) && "1".equals(inputItemVo.getKeyPartsType())) {
				finalTypeName = "";
			} else if ("0".equals(inputItemVo.getCustomType()) && "1".equals(inputItemVo.getKeyPartsType())) {
				finalTypeName = "自定义巡检点";
			} else if ("1".equals(inputItemVo.getCustomType()) && "0".equals(inputItemVo.getKeyPartsType())) {
				finalTypeName = "重点部位类型";
			} else if ("0".equals(inputItemVo.getCustomType()) && "0".equals(inputItemVo.getKeyPartsType())) {
				finalTypeName = "自定义巡检点" + "，" + "重点部位类型";
			}
			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("检查项新增失败: 请联系管理员 ");
		}
	}


	/**
	 * 查询巡检项详情
	 *
	 * @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("检查项新增失败:请联系管理员  " );
		}
	}

	/**
	 * 批量删除检查项
	 *
	 * @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("检查项新增失败:请联系管理员  " );
		}
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "导入检查项", notes = "导入检查项")
	@PostMapping(value = "/importData", produces = "application/json;charset=UTF-8")
	public CommonResponse importData(@RequestPart("file") MultipartFile multipartFile) {
		try {
			List<InputItemExcelDto> inputItemExcelDtos = ExcelUtil.readFirstSheetExcel(multipartFile, InputItemExcelDto.class, 1);
			for (InputItemExcelDto inputItemExcelDto : inputItemExcelDtos) {
				if (StringUtils.isEmpty(inputItemExcelDto.getItemNo()) || StringUtils.isEmpty(inputItemExcelDto.getName()) || StringUtils.isEmpty(inputItemExcelDto.getInputClassify())){
					throw new BadRequest("编号、名称、检查类型不能为空");
				}
				InputItemParam inputItemParam = new InputItemParam();
				//组装参数 因部分字段数据数据库中用json统一保存 按类型组装为所需数据结构
				if (inputItemExcelDto.getItemType().equals("选择")  && StringUtil.isNotEmpty(inputItemExcelDto.getDataJson())){
					List<InputItemDataDto> itemDataDtos = new ArrayList<>();
					if (inputItemExcelDto.getDataJson().contains("|")) {
						String[] datas = inputItemExcelDto.getDataJson().split("\\|");
						List<String> list = Arrays.asList(datas);
						list.forEach(e->{
							String[] data = e.split(",");
							InputItemDataDto inputItemDataDto = new InputItemDataDto(data[0],data[1],data[2],data[3]);
							itemDataDtos.add(inputItemDataDto);
						});
					}else {
						String[] data = inputItemExcelDto.getDataJson().split(",");
						InputItemDataDto inputItemDataDto = new InputItemDataDto(data[0],data[1],data[2],data[3]);
						itemDataDtos.add(inputItemDataDto);
					}
					inputItemExcelDto.setDataJson(JSON.toJSONString(itemDataDtos));
				}else if(inputItemExcelDto.getItemType().equals("数字")  && StringUtil.isNotEmpty(inputItemExcelDto.getDataJson())){
					InputItemDataJsonlDto inputItemDataJsonlDto = new InputItemDataJsonlDto();
					BeanUtils.copyProperties(inputItemExcelDto,inputItemDataJsonlDto);
					inputItemExcelDto.setDataJson(JSON.toJSONString(inputItemExcelDto));
				}
				List<Map<String, String> > itemDataDtos = new ArrayList<>();
				if (inputItemExcelDto.getPictureJson() != null){

					if (inputItemExcelDto.getPictureJson().contains("|")) {
						String[] datas = inputItemExcelDto.getPictureJson().split("\\|");
						List<String> list = Arrays.asList(datas);
						list.forEach(e->{
							String[] data = e.split(",");

							Map<String, String> map = new HashMap<>();
							map.put("name",data[0]);
							map.put("isMust",data[1]);
							itemDataDtos.add(map);
						});
					}else {
						String[] data = inputItemExcelDto.getPictureJson().split(",");
						Map<String, String> map = new HashMap<>();
						map.put("name",data[0]);
						map.put("isMust",data[1]);
						itemDataDtos.add(map);
					}
				}
				//转化为新增接口所需参数

				BeanUtils.copyProperties(inputItemExcelDto,inputItemParam);
				if (inputItemParam.getDataJson() != null){
					inputItemParam.setDataJson(JSON.parseArray(inputItemParam.getDataJson().toString(),Map.class));
				}
				if (inputItemParam.getPictureJson()!=null){
					inputItemParam.setPictureJson(itemDataDtos);
				}
				//新增接口
				this.addNewItemNew(inputItemParam);
			}
			return CommonResponseUtil.success();
		} catch (Exception e) {
			throw new BadRequest(e.getMessage());
		}
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "导出检查项", notes = "导出检查项")
	@RequestMapping(value = "/exportData", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public void exportData(HttpServletResponse response,String ids) {
		InputItemPageParam  criterias = new InputItemPageParam();
		ReginParams params = getSelectedOrgInfo();
		if (!StringUtils.isEmpty(ids)){
			criterias.setIds(ids);
		}
		criterias.setBizOrgCode(params.getPersonIdentity().getCompanyBizOrgCode());
		List<InputItemExcelVo> content = inputItemMapper.getInputItemInfoExcelNew(criterias);
		//此处对数据做统一处理 拼接为易读内容
		for (InputItemExcelVo inputItemExcelDto : content) {
			String text = "";
			if (inputItemExcelDto.getItemType().equals("选择")&& !inputItemExcelDto.getDataJson().equals("[]")&& !inputItemExcelDto.getDataJson().equals("")) {
				List<Map> maps = JSONObject.parseArray(inputItemExcelDto.getDataJson(), Map.class);
				for (int i = 0; i< maps.size(); i++) {
					Map jsonObject = maps.get(i);
					text = text +"名称："+jsonObject.get("name")+" "+"评分："+jsonObject.get("score")+" "+"选择是否合格："+jsonObject.get("isOk")+" "+"默认选中："+jsonObject.get("isChecked");
					if(i < (maps.size()-1) ){
						text = text+"|";
						inputItemExcelDto.setDataJson(text);
					}else {
						inputItemExcelDto.setDataJson(text);
					}
				}
			}
			if (!inputItemExcelDto.getPictureJson().equals("[]")&& !inputItemExcelDto.getPictureJson().equals("")) {
				List<Map> maps = JSONObject.parseArray(inputItemExcelDto.getPictureJson(), Map.class);
				text = "";
				for (int i = 0; i< maps.size(); i++) {
					Map jsonObject = maps.get(i);
					text = text +"名称："+ jsonObject.get("name")+","+ "是否拍照："+jsonObject.get("isMust");
					if(i < (maps.size()-1) ){
						text = text+"|";
						inputItemExcelDto.setPictureJson(text);
					}else {
						inputItemExcelDto.setPictureJson(text);
					}
				}
			}
			if (inputItemExcelDto.getItemType().equals("数字") || inputItemExcelDto.getItemType().equals("文本")) {
				//此处为避免大量set方法 将data_json字段中的数据转为对象组装
				InputItemDataJsonlDto inputItemDataJsonlDto = JSONObject.parseObject(inputItemExcelDto.getDataJson(), InputItemDataJsonlDto.class);
				BeanUtils.copyProperties(inputItemDataJsonlDto,inputItemExcelDto);
				inputItemExcelDto.setDataJson(null);
			}
		}

		ExcelUtil.createTemplate(response,"检查项","检查项",content,InputItemExcelVo.class,null,true);

	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "模板下载", notes = "模板下载")
	@RequestMapping(value = "/downTemplate", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public void downTemplate(HttpServletResponse response) {
		ExcelUtil.createTemplate(response,"检查项模板","检查项",null,InputItemExcelDto.class,null,true);
	}



	/**
	 * 删除检查项
	 *
	 * @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("检查项新增失败:请联系管理员 ");
		}
	}

	/**
	 * 检查项另存为
	 *
	 * @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("检查项另存为失败:请联系管理员 " );
		}
	}

	/**
	 * 分页查询检查项
	 *
	 * @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);
        Object ov=ToJson.tojson(list);


		return CommonResponseUtil.success(ov);
	}
	/**
	 * 条件查询检查项
	 *
	 * @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.getId()>0){
		}else{
			if ("1".equals(param.getEquipmentType())  && "1".equals(param.getCustomType()) &&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.setInputClassify(param.getInputClassify());
				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:true);
				map.put("CheckValidDown",param.getCheckValidDown().equals("否")?false:true);
				map.put("CheckOkUp",param.getCheckOkUp().equals("否")?false:true);
				map.put("CheckOkDown",param.getCheckOkDown().equals("否")?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("检查项新增失败:请联系管理员 ");
		}
	}


}
