package com.yeejoin.amos.patrol.business.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.interceptors.PermissionInterceptorContext;
import com.yeejoin.amos.patrol.business.dao.mapper.InputItemMapper;
import com.yeejoin.amos.patrol.business.dao.mapper.RouteMapper;
import com.yeejoin.amos.patrol.business.dao.repository.IInputItemDao;
import com.yeejoin.amos.patrol.business.dao.repository.IPointInputItemDao;
import com.yeejoin.amos.patrol.business.param.InputItemPageParam;
import com.yeejoin.amos.patrol.business.service.intfc.ICatalogTreeService;
import com.yeejoin.amos.patrol.business.service.intfc.IInputItemService;
import com.yeejoin.amos.patrol.business.util.DaoCriteria;
import com.yeejoin.amos.patrol.business.vo.InputItemVo;
import com.yeejoin.amos.patrol.business.vo.PointInputItemVo;
import com.yeejoin.amos.patrol.core.util.query.BaseQuerySpecification;
import com.yeejoin.amos.patrol.dao.entity.CatalogTree;
import com.yeejoin.amos.patrol.dao.entity.InputItem;
import com.yeejoin.amos.patrol.feign.RemoteSecurityService;
import org.apache.commons.lang3.StringUtils;
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.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

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

@Service("inputItemService")
public class InputItemServiceImpl implements IInputItemService {

	@Autowired
	IInputItemDao inputItemDao;
	@Autowired
	IPointInputItemDao  iPointInputItemDao ;
	@Autowired
	RouteMapper routeMapper;
	@Autowired
	InputItemMapper inputItemMapper;
	@Autowired
	private ICatalogTreeService iCatalogTreeService;
	@Value("${input.custom.prefix}")
	private String customPre;
	@Value("${auth-key-auth-enabled:}")
	private String authKey;

	@Autowired
	private RemoteSecurityService remoteSecurityService;

	@Value("${auth-key-auth-enabled:}")
	private String authKeyEnabled;




	/**
	 * 新接口
	 * **/


	@Override
	public Page<InputItemVo> queryInputItemByPageNew(InputItemPageParam criterias) {
		long total = inputItemMapper.countInputItemInfoDataNew(criterias);
		List<InputItemVo> content = inputItemMapper.getInputItemInfoNew(criterias);
		Page<InputItemVo> result = new PageImpl<InputItemVo>(content, criterias, total);
		return result;
	}

	/**
	 * 新接口
	 * **/








	@Override
	@Transactional
	public long addNewInputItem(InputItem param) {
		if(param.getId()>0){
             inputItemMapper.updateInputItem(param);
		}else{
			param.setInputType(0);
			param.setItemNo(customPre + param.getItemNo());
			param = inputItemDao.save(param);
		}
		return param.getId();
	}

	@Override
	public InputItem queryInputItemDetail(Long id) {
		return inputItemDao.findById(id).get();
	}

	@Override
	@Transactional
	public void updateInputItem(InputItem param) {
		if (param.getId() <= 0) {
			addNewInputItem(param);

		}else{
			inputItemMapper.updateInputItem(param);
		}
	}

	@Override
	@Transactional
	public void delInputItem(Long id) {
		InputItem item = inputItemDao.findById(id).get();
		item.setId(id);
		item.setIsDelete(true);
		inputItemDao.saveAndFlush(item);
	}

	@Override
	public Page<InputItemVo> queryInputItemByPage(InputItemPageParam param) {
		if(StringUtils.isNotEmpty(Integer.valueOf(param.getCatalogId()).toString())){
			List<CatalogTree> catalogTreeList = iCatalogTreeService.AllCatalogChrildList(param.getOrgCode(),(long) param.getCatalogId());
			List<Long> catalogIds = catalogTreeList.stream().map(CatalogTree::getId).collect(Collectors.toList());
			catalogIds.add(Long.valueOf(param.getCatalogId()));
			param.setCatalogIds(catalogIds);
		}
		long total = inputItemMapper.countInputItemInfoData(param);
		List<InputItemVo> content = inputItemMapper.getInputItemInfo(param);
		Page<InputItemVo> result = new PageImpl<InputItemVo>(content, param, total);
		return result;
	}

	@Override
	public List<InputItem> queryInputItemByCondition(List<DaoCriteria> criterias) {
		BaseQuerySpecification<InputItem> specification = new BaseQuerySpecification<>(criterias);
		return inputItemDao.findAll(specification);
	}

	@Override
	public int queryInputItemCountByCondition(List<DaoCriteria> criterias) {
		BaseQuerySpecification<InputItem> specification = new BaseQuerySpecification<>(criterias);
		return Integer.parseInt(inputItemDao.count(specification)+"");
	}

	@Override
	@Transactional
	public void saveAs(String[] ids, String userId) {
		for (String itemID : ids) {
			if (ObjectUtils.isEmpty(itemID)) continue;
			InputItem inputItem = inputItemDao.findById(Long.valueOf(itemID)).get();
			InputItem targetInputItem = new InputItem();
			BeanUtils.copyProperties(inputItem, targetInputItem);
			targetInputItem.setId(0);
			targetInputItem.setName(targetInputItem.getName() + "复制");
			targetInputItem.setCreateBy(userId);
			targetInputItem.setCreateDate(new Date());
			if(targetInputItem.getItemNo()!=null&&targetInputItem.getItemNo().indexOf("-")>0)
			targetInputItem.setItemNo(targetInputItem.getItemNo().substring(0,targetInputItem.getItemNo().indexOf("-"))+"-"+new Date().getTime());
			else {
				targetInputItem.setItemNo(targetInputItem.getItemNo()+"-"+new Date().getTime());
			}
			inputItemDao.save(targetInputItem);
		}

	}

	@Override
	@Transactional
	public void batchDelInputItem(String[] param) {
		List<Long> ids = new ArrayList<Long>();
		for(int i=0;i<param.length;i++){
			ids.add(Long.parseLong(param[i]));
		}
		routeMapper.deleteReleInputItem(param);//1.删除p_route_point_inputitem
		iPointInputItemDao.delPointInputItem(ids);//2.删除p_point_inputitem
		for (String id : param) {//3.删除p_inputItem
			InputItem item = inputItemDao.findById(Long.valueOf(id)).get();
			item.setIsDelete(true);
			inputItemDao.saveAndFlush(item);
		}
	}

	@Override
	public String[] queryInputItemNames(String loginOrgCode) {
		InputItemPageParam param = new InputItemPageParam();
		param.setOrgCode(loginOrgCode);
		List<InputItemVo> content = inputItemMapper.getInputItemInfo(param);
		if (!ObjectUtils.isEmpty(content)) {
			String[] names = new String[content.size()];
			for (int i = 0; i < content.size(); i++) {
				names[i] = content.get(i).getName();
			}
			return names;
		}
		return null;
	}

	@Override
	public List<String> qryItemNoList(List<DaoCriteria> criterias, Long itemId) {
		BaseQuerySpecification<InputItem> spec = new BaseQuerySpecification<>(criterias);
		// 根据过滤条件查询出所有检查项编号
		List<InputItem> itemList = inputItemDao.findAll(spec);
		List<String> itemNoList = new ArrayList<>();
		// 将除去自身以外的所有编号添加到集合中
		for (InputItem item : itemList) {
			if (item.getId() != itemId) {
				itemNoList.add(item.getItemNo());
			}
		}
		return itemNoList;
	}

	@Override
	public Object getCheckClassify(String token, String product, String appKey, String dictCode) {
		JSONArray jsonArray = remoteSecurityService.listDictionaryByDictCode(token, product, appKey, dictCode);
		List list = new LinkedList();
		for (int i = 0; i <jsonArray.size() ; i++) {
			Map<String,String> map = new HashMap<>();
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			map.put("id",jsonObject.get("dictDataKey").toString());
			map.put("name",jsonObject.get("dictDataValue").toString());
			list.add(map);
		}
		return list;
	}

	@Override
	public List<PointInputItemVo> queryCustomInputItem(String itemType, String nameOrItemNo, String orgCode) {
		HashMap<String,Object> param = new HashMap<>();
		param.put("itemType",itemType);
		param.put("nameOrItemNo",nameOrItemNo);
		param.put("orgCode",orgCode);
		List<PointInputItemVo> content = inputItemMapper.queryCustomInputItem(param);
		return content;
	}

	@Override
	public List<PointInputItemVo> queryCustomInputItemNew(HashMap<String,Object> param, String orgCode,String companyBizOrgCode) {

		// 权限处理
		PermissionInterceptorContext.setDataAuthRule(authKeyEnabled);
		param.put("orgCode",orgCode);
		param.put("bizOrgCode",companyBizOrgCode);
		List<String> list =	new ArrayList<>();
		if(param.containsKey("equipmentType")){
			list = getEquipParent(param.get("equipmentType").toString(),list);
			list .add("-1");
			param.put("equipmentType",list);
		}
		List<String> list1 =	new ArrayList<>();
		if(param.containsKey("facilitiesType")){
			list1 = getEquipParent(param.get("facilitiesType").toString(),list1);
			list1 .add("-1");
			param.put("facilitiesType",list1);
		}
		List<PointInputItemVo> content = inputItemMapper.queryCustomInputItem(param);
		return content;
	}

	public List<String> getEquipParent(String code,List<String> objects){
		// 权限处理
		PermissionInterceptorContext.setDataAuthRule(authKey);
		Map<String, String> equipmentType = inputItemMapper.getEquipParentCode(code);
		if (equipmentType == null) {
			equipmentType =	inputItemMapper.getSystemParentCode(code);
		}
		if (!equipmentType.containsKey("parent_id") ){
			objects.add(code);
			return objects;
		}
		objects.add(code);
		Map<String, String> parent = inputItemMapper.getEquipParent(equipmentType.get("parent_id"));
	return 	getEquipParent(parent.get("code"),objects);
	}

}
