package com.palmnest.service.impl;

import cn.superdesk.libs.common.util.CollectionUtils;
import com.palmnest.application.bean.Page;
import com.palmnest.application.bean.Pagenation;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.output.ElementDto;
import com.palmnest.dao.ElementGroupDao;
import com.palmnest.model.Element;
import com.palmnest.model.ElementGroup;
import com.palmnest.model.OrgElement;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.ElementGroupManager;
import com.palmnest.service.property.PropertyManager;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * ElementGroupManager接口的实现
 *
 * @author ldb
 */
@Service("elementGroupManager")
public class ElementGroupManagerImpl extends GenericManagerImpl<ElementGroup, Long> implements ElementGroupManager {

	private ElementGroupDao elementGroupDao;

	@Autowired
	public void setElementGroupDao(ElementGroupDao elementGroupDao) {

		this.elementGroupDao = elementGroupDao;
		this.dao = elementGroupDao;
	}

	@Override
	public ElementGroup getElementGroupId(Long id) {

		return this.elementGroupDao.getElementGroupId(id);
	}

	@Override
	public ElementGroup saveElementGroup(ElementGroup elementGroup) {

		return null;
	}

	@Override
	public void removeElementGroups(Long... ids) {

		this.elementGroupDao.removeElementGroups(ids);
	}

	@Override
	public void removeElement(Long... ids) {

		this.elementGroupDao.removeElement(ids);
	}

	@Autowired
	private PropertyManager propertyManager;

	public Pagenation<ElementGroup> queryElementGroup(int pageNo,
													  List<Criterion> filterList) {

		int                 pageSize  = 10;
		Map<String, String> aliasMap  = Collections.<String, String>emptyMap();
		List<Order>         orderList = new ArrayList<Order>();

		orderList.add(Order.desc("id"));

		return this.elementGroupDao.queryPage(pageNo, pageSize, aliasMap, filterList, orderList, ElementGroup.class);
	}

	@Override
	public Pagenation<Element> queryElement(int pageNo,
											List<Criterion> filterList) {

		int                 pageSize  = 10;
		Map<String, String> aliasMap  = Collections.<String, String>emptyMap();
		List<Order>         orderList = new ArrayList<Order>();

		orderList.add(Order.desc("id"));

		return this.elementGroupDao.queryPage(pageNo, pageSize, aliasMap, filterList, orderList, Element.class);
	}

	@Override
	public Map<Long, String> getElementIds(Collection<Long> ids) {
		return this.elementGroupDao.getElementIds(ids);
	}

	@Override
	public Element saveElement(Element element) {

		return this.elementGroupDao.saveElement(element);
	}

	@Override
	public Element getElementId(Long id) {

		return this.elementGroupDao.getElementId(id);
	}

	@Override
	public long getTabMaxOptVersion(String tableName) {

		return this.elementGroupDao.getTabMaxOptVersion(tableName);
	}

	@Override
	public List<ElementGroup> getSyncGroupDataList(long minVersion, long maxVersion) {
		return this.elementGroupDao.getSyncDataList(minVersion, maxVersion);
	}

	@Override
	public List<Element> getElementsByGroupName(String code) {
		return this.dao.getElementsByGroupName(code);
	}

	@Override
	public List getSyncElementDataList(long minVersion, long maxVersion) {
		return this.elementGroupDao.getSyncElementDataList(minVersion, maxVersion);
	}

	@Override
	public List<Element> getElementsByGroupName(String code,String orgId) {
		List<Element> result = new ArrayList<>();

		if (StringUtils.isNotEmpty(orgId)) {
			List<OrgElement> orgElements = elementGroupDao.getElementListByOrgAndGroup(code, Integer.parseInt(orgId));
			if (CollectionUtils.isNotEmpty(orgElements)) {

				for (OrgElement orgElement :
						orgElements) {
					Element el = elementGroupDao.getByItemname(code, orgElement.getItemname());
					result.add(el);
				}
			}
			return result;
		}
		return this.dao.getElementsByGroupName(code);
	}

	@Override
	public List<ElementGroup> getAllDataList() {
		return this.elementGroupDao.getAllDataList();
	}

	@Override
	public Map<String, Object> getOrderAreaInfo(String areaCode) {
		return this.elementGroupDao.getOrderAreaInfo(areaCode);
	}

	@Override
	public List<ElementDto> convert(List<Element> elements) {
		List<ElementDto> dtos = new ArrayList<ElementDto>();
		if (null == elements) {
			return dtos;
		}

		for (Element e : elements) {
			if(null==e){
				continue;
			}
			ElementDto dto = new ElementDto();
			dto.setId(e.getId());
			dto.setItemname(e.getItemname());
			dto.setItemcode(e.getItemcode());
			dto.setSort(e.getOrderno());
			dtos.add(dto);
		}
		return dtos;
	}

	@Override
	public Element getByItemCode(String itemcode) {
		return this.elementGroupDao.getByItemCode(itemcode);
	}

	@Override
	public Element getByItemCode(String groupcode, String itemcode) {
		return this.elementGroupDao.getByItemCode(groupcode, itemcode);
	}

	@Override
	public Element getByItemname(String groupcode, String itemname) {
		return this.elementGroupDao.getByItemname(groupcode, itemname);
	}

	@Override
	public Page orgSettingList(int pageNo, int pageSize, HashMap<String, String> map) {
		Page                      page = this.elementGroupDao.orgSettingList(pageNo, pageSize, map);
		List<Map<String, Object>> list = page.getItems();

		// 对查询结果进行重新封装;如果项目自定义了配置项,则使用该项目的配置,如果没配置,则使用系统默认;
		if (list != null && list.size() > 0) {
			for (Map<String, Object> objectMap : list) {
				Long           groupId      = (Long) objectMap.get("groupId");
				Integer        orgId        = Integer.parseInt(map.get("orgId"));
				TbOrganization organization = propertyManager.getTbOrganizationById(orgId);
				objectMap.put("orgId", orgId);
				objectMap.put("orgName", organization.getName());
				if (objectMap.get("funcName") == null) {
					objectMap.put("funcName", "其它");
				}

				String setting = "";
				// 获取当前项目,指定数据字典自定义配置项
				List<OrgElement> orgElementList = elementGroupDao.getElementListByOrgAndGroup(groupId, orgId);
				if (orgElementList != null && orgElementList.size() > 0) {
					// 有自定义配置
					for (OrgElement element : orgElementList) {
						setting += element.getItemname() + ",";
					}
				} else {
					// 没有自定义配置
					List<Element> elements = elementGroupDao.getElementListByGroup(groupId);
					if (elements != null) {
						for (Element element : elements) {
							setting += element.getItemname() + ",";
						}
					}
				}

				objectMap.put("setting", setting);
			}
		}
		return page;
	}

	@Override
	public List<ElementDto> getOrgElementGroupInfo(int orgId, Long groupId) {

		List<ElementDto> list = new ArrayList<ElementDto>();
		// 获取当前项目,当前数据字典组的自定义配置列表
		List<OrgElement> orgElementList = elementGroupDao.getElementListByOrgAndGroup(groupId, orgId);
		if (orgElementList != null && orgElementList.size() > 0) {
			// 有自定义配置,则取自定义配置
			for (OrgElement element : orgElementList) {
				ElementDto dto = new ElementDto();
				dto.setId(element.getId());
				dto.setSort(Long.valueOf(element.getOrderno()));
				dto.setItemname(element.getItemname());
				list.add(dto);
			}
		} else {
			// 无自定义配置,取系统默认配置
			List<Element> elements = elementGroupDao.getElementListByGroup(groupId);
			if (elements != null) {
				for (Element element : elements) {
					ElementDto dto = new ElementDto();
					dto.setItemname(element.getItemname());
					list.add(dto);
				}
			}

		}

		return list;
	}

	@Override
	public List<ElementDto> getOrgElementGroupInfo(int orgId, String groupCode) {
		List<ElementDto> list = new ArrayList<ElementDto>();
		// 获取当前项目,当前数据字典组的自定义配置列表
		List<OrgElement> orgElementList = elementGroupDao.getElementListByOrgAndGroup(groupCode, orgId);
		if (orgElementList != null && orgElementList.size() > 0) {
			// 有自定义配置,则取自定义配置
			for (OrgElement element : orgElementList) {
				ElementDto dto = new ElementDto();
				Element    el  = elementGroupDao.getByItemname(groupCode, element.getItemname());
				if (el != null) {
					dto.setElOrgId(el.getId());
				}
				dto.setId(element.getId());
				dto.setSort(Long.valueOf(element.getOrderno()));
				dto.setItemname(element.getItemname());
				dto.setItemcode("");
				list.add(dto);
			}
		} else {
			// 无自定义配置,取系统默认配置
			List<Element> elements = elementGroupDao.getElementsByGroupName(groupCode);
			if (elements != null) {
				for (Element element : elements) {
					ElementDto dto = new ElementDto();
					dto.setId(element.getId());
					dto.setSort(Long.valueOf(element.getOrderno()));
					dto.setItemname(element.getItemname());
					dto.setItemcode(element.getItemcode());
					list.add(dto);
				}
			}

		}
		Collections.sort(list, new Comparator<ElementDto>() {
			public int compare(ElementDto o1, ElementDto o2) {
				Long name1 = o1.getSort();//name1是从你list里面拿出来的一个
				Long name2 = o2.getSort(); //name1是从你list里面拿出来的第二个name
				return name1.compareTo(name2);
			}
		});
		return list;
	}

	@Override
	public List<ElementDto> getOrgElementGroupInfoV2(String orgIds, String groupCode) {
		List<ElementDto> list = new ArrayList<>();
		// 获取当前项目,当前数据字典组的自定义配置列表
		List<OrgElement> orgElementList = elementGroupDao.getElementListByOrgAndGroup(groupCode, orgIds);
		if (orgElementList != null && orgElementList.size() > 0) {
			// 有自定义配置,则取自定义配置
			for (OrgElement element : orgElementList) {
				ElementDto dto = new ElementDto();
				Element el = elementGroupDao.getByItemCode(groupCode, element.getCode());
				if (el != null) {
					dto.setElOrgId(el.getId());
					dto.setItemcode(el.getItemcode());
					dto.setId(el.getId());
					if(null==element.getOrderno()){
						dto.setSort(9999L);
					}else{
						dto.setSort(Long.valueOf(element.getOrderno()));
					}
					
					dto.setItemname(element.getItemname());
					list.add(dto);
				}

			}

			Collections.sort(list, new Comparator<ElementDto>() {
				public int compare(ElementDto o1, ElementDto o2) {
					Long name1 = o1.getSort();//name1是从你list里面拿出来的一个
					Long name2 = o2.getSort(); //name1是从你list里面拿出来的第二个name
					return name1.compareTo(name2);
				}
			});
		}

		return list;
	}

	@Override
	public void saveUpdateOrgSetting(List<ElementDto> dtos, Integer orgId, Long groupId) throws Exception {

		String notDelIds = "";
		if (dtos != null) {
			for (ElementDto dto : dtos) {
				if (dto.getId() != null) {
					notDelIds += dto.getId() + ",";
				}
			}
		}
		// 删除被移除的配置项
		if (StringUtils.isNotBlank(notDelIds)) {
			notDelIds = notDelIds.substring(0, notDelIds.length() - 1);
		}
		elementGroupDao.delOrgSettingByOrgAndGroup(notDelIds, orgId, groupId);


		if (dtos != null) {
			// 新增或修改
			for (ElementDto dto : dtos) {
				if (dto.getId() != null) {
					// 修改
					OrgElement element = elementGroupDao.getOrgElementId(dto.getId());
					element.setOrderno(dto.getSort().intValue());
					element.setItemname(dto.getItemname());
					propertyManager.updateModel(element);
				} else {
					// 新增
					OrgElement element = new OrgElement();
					element.setItemname(dto.getItemname());
					element.setOrderno(dto.getSort().intValue());
					element.setCreatetime(new Date());
					element.setIsenabled(1);

					ElementGroup elementGroup = new ElementGroup();
					elementGroup.setId(groupId);
					element.setElementGroup(elementGroup);

					TbOrganization organization = new TbOrganization();
					organization.setId(orgId);
					element.setOrganization(organization);

					propertyManager.save(element);
				}
			}
		}
	}

	@Override
	public OrgElement getOrgElementId(Long id) {
		return elementGroupDao.getOrgElementId(id);
	}

	@Override
	public ElementDto getElementById(Long id) {
		ElementDto dto   = new ElementDto();
		OrgElement orgEl = elementGroupDao.getOrgElementId(id);
		if (orgEl != null) {
			dto.setId(orgEl.getId());
			dto.setItemcode("");
			dto.setItemname(orgEl.getItemname());
			if (orgEl.getOrderno() != null) {
				dto.setSort(Long.parseLong(orgEl.getOrderno().toString()));
			} else {
				dto.setSort(Long.parseLong("0"));
			}
			return dto;
		} else {
			Element el = elementGroupDao.getElementId(id);
			if (el != null) {
				dto.setId(el.getId());
				dto.setItemcode(el.getItemcode());
				dto.setItemname(el.getItemname());
				if (el.getOrderno() != null) {
					dto.setSort(Long.parseLong(el.getOrderno().toString()));
				} else {
					dto.setSort(Long.parseLong("0"));
				}
				return dto;
			}
		}
		return null;
	}

	@Override
	public ElementDto getByItemname(String orgId, String groupcode,
									String itemname) {
		ElementDto dto   = new ElementDto();
		OrgElement orgEl = elementGroupDao.getByItemname(orgId, groupcode, itemname);
		if (orgEl != null) {
			dto.setId(orgEl.getId());
			dto.setItemcode("");
			dto.setItemname(orgEl.getItemname());
			if (orgEl.getOrderno() != null) {
				dto.setSort(Long.parseLong(orgEl.getOrderno().toString()));
			} else {
				dto.setSort(Long.parseLong("0"));
			}
			return dto;
		} else {
			Element el = elementGroupDao.getByItemname(groupcode, itemname);
			if (el != null) {
				dto.setId(el.getId());
				dto.setItemcode(el.getItemcode());
				dto.setItemname(el.getItemname());
				if (el.getOrderno() != null) {
					dto.setSort(Long.parseLong(el.getOrderno().toString()));
				} else {
					dto.setSort(Long.parseLong("0"));
				}
				return dto;
			}
		}
		return null;
	}

}
