package com.yeejoin.amos.boot.module.jxiop.biz.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.jxiop.api.dto.RectificationUnitClassifyTreeDto;
import com.yeejoin.amos.boot.module.jxiop.api.feign.McbWarningFeign;
import com.yeejoin.amos.boot.module.jxiop.api.service.IMcbWarningService;
import com.yeejoin.amos.boot.module.jxiop.api.service.IPermissionService;
import com.yeejoin.amos.boot.module.jxiop.biz.mcbwarningmapper.McbWarningMapper;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

@Service
public class McbWarningServiceImpl implements IMcbWarningService {

	private final static org.slf4j.Logger log = LoggerFactory.getLogger(McbWarningServiceImpl.class);

	@Autowired
	private McbWarningMapper mcbWarningMapper;

	@Autowired
	private IPermissionService permissionService;

	@Autowired
	private McbWarningFeign mcbWarningFeign;

	/**
	 * 今日预警-预警总数
	 *
	 * @param processingStatus 处理状态
	 * @return 总数信息
	 */
	@Override
	public Map<String, Object> queryTodayCount(Integer processingStatus) {
		List<String> projectOrgCodes = this.getProjectOrgCodes();
		if (projectOrgCodes.isEmpty()) {
			projectOrgCodes.add("NULL");
		}
		return mcbWarningMapper.queryTodayCount(projectOrgCodes, processingStatus);
	}

	/**
	 * 近七日预警统计
	 *
	 * @return 预警统计
	 */
	@Override
	public List<Map<String, Object>> queryWeekCount() {
		List<String> projectOrgCodes = this.getProjectOrgCodes();
		if (projectOrgCodes.isEmpty()) {
			projectOrgCodes.add("NULL");
		}
		return mcbWarningMapper.queryWeekCount(projectOrgCodes);
	}

	/**
	 * 预警信息列表
	 *
	 * @param page             分页
	 * @param processingStatus 处理状态
	 * @return 预警信息列表
	 */
	@Override
	public Page<Map<String, Object>> queryWarningPage(Page<Map<String, Object>> page, Integer processingStatus,
			String eventLevel, String createDate, String warningSourceType) {
		List<String> projectOrgCodes = this.getProjectOrgCodes();
		long start = page.getCurrent() - 1;
		long offset = page.getSize() * page.getCurrent();
		if (projectOrgCodes.isEmpty()) {
			projectOrgCodes.add("NULL");
		}
		List<Map<String, Object>> records = mcbWarningMapper.queryWarningList(start, offset, projectOrgCodes,
				processingStatus, eventLevel, createDate, warningSourceType);
		Long total = mcbWarningMapper.queryWarningCount(projectOrgCodes, processingStatus, eventLevel, createDate,
				warningSourceType);
		page.setRecords(records);
		page.setTotal(total);
		return page;
	}

	/**
	 * 预警信息总数
	 *
	 * @param processingStatus 处理状态
	 * @return 预警信息总数
	 */
	@Override
	public Long queryWarningCount(Integer processingStatus, String eventLevel, String createDate,
			String warningSourceType) {
		List<String> projectOrgCodes = this.getProjectOrgCodes();
		if (projectOrgCodes.isEmpty()) {
			projectOrgCodes.add("NULL");
		}
		return mcbWarningMapper.queryWarningCount(projectOrgCodes, processingStatus, eventLevel, createDate,
				warningSourceType);
	}

	/**
	 * 问题信息列表
	 *
	 * @param page             分页
	 * @param completionStatus 完成状态
	 * @return 问题信息列表
	 */
	@Override
	public Page<Map<String, Object>> queryQuestionPage(Page<Map<String, Object>> page, Integer completionStatus) {
		List<String> projectOrgCodes = this.getProjectOrgCodes();
		long start = page.getCurrent() - 1;
		long offset = page.getSize() * page.getCurrent();
		if (projectOrgCodes.isEmpty()) {
			projectOrgCodes.add("NULL");
		}
		List<Map<String, Object>> records = mcbWarningMapper.queryQuestionList(start, offset, projectOrgCodes,
				completionStatus);
		Long total = mcbWarningMapper.queryQuestionCount(projectOrgCodes, completionStatus);
		page.setRecords(records);
		page.setTotal(total);
		return page;
	}

	/**
	 * 问题信息列表
	 *
	 * @param completionStatus 完成状态
	 * @return 问题信息列表
	 */
	@Override
	public Long queryQuestionCount(Integer completionStatus) {
		List<String> projectOrgCodes = this.getProjectOrgCodes();
		if (projectOrgCodes.isEmpty()) {
			projectOrgCodes.add("NULL");
		}
		return mcbWarningMapper.queryQuestionCount(projectOrgCodes, completionStatus);
	}

	/**
	 * 获取地图点位/路线
	 *
	 * @param province 省份
	 * @return 地图点位/路线
	 */
	@Override
	public Object queryMapRoutes(String province) {
		List<String> projectOrgCodes = this.getProjectOrgCodes();
		// TODO: 远程调用warning服务
		return null;
	}

	/**
	 * 任务详情分页列表
	 */
	@Override
	public Page<Map<String, Object>> getTaskDetailPage(Map<String, Object> map) {
		map.put("projectOrgCodes", this.getProjectOrgCodes());
		FeignClientResult<Page<Map<String, Object>>> page = mcbWarningFeign.getTaskDetailPage(map);
		return page.getResult();
	}

	/**
	 * 问题记录分页列表
	 */
	@Override
	public Page<Map<String, Object>> getQuestionRecordPage(Map<String, Object> map) {
		map.put("projectOrgCodes", this.getProjectOrgCodes());
		FeignClientResult<Page<Map<String, Object>>> page = mcbWarningFeign.getQuestionRecordPage(map);
		return page.getResult();
	}

	public List<RectificationUnitClassifyTreeDto> treeToList(List<RectificationUnitClassifyTreeDto> source,
			List<RectificationUnitClassifyTreeDto> object) {
		source.stream().forEach(v -> {
			RectificationUnitClassifyTreeDto t = new RectificationUnitClassifyTreeDto();
			BeanUtils.copyProperties(v, t);
			t.setChildren(new ArrayList());
			object.add(t);
			// 判断该对象的getChildren()是否为空
			if (!CollectionUtils.isEmpty(v.getChildren())) {
				treeToList(v.getChildren(), object);
			}
		});
		return object;
	}

	/**
	 * 任务详情、问题记录左侧树
	 *
	 */
	@Override
	public Object getWarnTree() {
		FeignClientResult<List<RectificationUnitClassifyTreeDto>> allUnitList = mcbWarningFeign.getWarnTree();
		List<RectificationUnitClassifyTreeDto> res = allUnitList.getResult();
		if (CollectionUtils.isEmpty(res)) {
			return new ArrayList<>();
		}
		List<RectificationUnitClassifyTreeDto> targetList = new ArrayList<>();
		List<RectificationUnitClassifyTreeDto> tempList = treeToList(res, targetList);
		List<String> codes = permissionService.getCurrentUserAmosOrgCodes();
		targetList = tempList.stream().filter(x -> {
			if (CollectionUtil.isNotEmpty(codes)) {
				for (String str : codes) {
					if (x.getCode().startsWith(str)) {
						return true;
					}
				}
			}
			return false;
		}).collect(Collectors.toList());
		List<RectificationUnitClassifyTreeDto> listDate = new ArrayList<>();
		if (!targetList.isEmpty()) {
			for (RectificationUnitClassifyTreeDto t : targetList) {
				if (StringUtils.isBlank(t.getParentId()) || "0".equals(t.getParentId())
						|| codes.get(0).equals(t.getCode())) {
					t.setChildren(getChild(t, targetList));
					listDate.add(t);
					break;
				}
			}
		}
		return listDate;
	}

	private List<RectificationUnitClassifyTreeDto> getChild(RectificationUnitClassifyTreeDto dto,
			List<RectificationUnitClassifyTreeDto> listDto) {
		return (List<RectificationUnitClassifyTreeDto>) listDto.stream()
				.filter(t -> t.getParentId().equals(dto.getSequenceNbr().toString()))
				.peek(m -> m.setChildren(getChild(m, listDto))).collect(Collectors.toList());
	}

	/**
	 * 任务详情列表统计
	 *
	 */
	@Override
	public Object getTaskDetailStatistic(Map<String, Object> map) {
		List<String> projectOrgCodes = this.getProjectOrgCodes();
		map.put("projectOrgCodes", projectOrgCodes);
		FeignClientResult result = mcbWarningFeign.getTaskDetailStatistic(map);
		return result.getResult();
	}

	/**
	 * 问题记录列表统计
	 *
	 */
	@Override
	public Object getQuestionRecordStatistic(Map<String, Object> map) {
		List<String> projectOrgCodes = this.getProjectOrgCodes();
		map.put("projectOrgCodes", this.getProjectOrgCodes());
		FeignClientResult result = mcbWarningFeign.getQuestionRecordStatistic(map);
		return result.getResult();
	}

	/**
	 * 问题记录列表统计
	 *
	 */
	@Override
	public Object getMapRouteInfoByCodes(String province) {
		List<String> projectOrgCodes = permissionService.getCurrentUserAmosOrgCodes();
		if (projectOrgCodes.isEmpty()) {
			projectOrgCodes.add("NULL");
		}
		FeignClientResult<Object> result = mcbWarningFeign.getMapRouteInfoByCodes(province, projectOrgCodes, "like");
		return result.getResult();
	}

	@Override
	public Object getLampListPageByCodes(String questionRectificationStatus, String warningSourceType,
			String objectName, Page page) {
		List<String> projectOrgCodes = permissionService.getCurrentUserAmosOrgCodes();
		if (projectOrgCodes.isEmpty()) {
			projectOrgCodes.add("NULL");
		}
		FeignClientResult<Object> result = mcbWarningFeign.getLampListPage(questionRectificationStatus,
				warningSourceType, objectName, projectOrgCodes, "like", page.getCurrent(), page.getSize());
		return result.getResult();
	}

	@Override
	public Object getLampListByCodes(String questionRectificationStatus, String warningSourceType, String objectName) {
		List<String> projectOrgCodes = permissionService.getCurrentUserAmosOrgCodes();
		if (projectOrgCodes.isEmpty()) {
			projectOrgCodes.add("NULL");
		}
		FeignClientResult<Object> result = mcbWarningFeign.getLampList(questionRectificationStatus, warningSourceType,
				objectName, projectOrgCodes, "like");
		return result.getResult();
	}

	/**
	 * 获取用户权限(此处使用projectOrgCode)
	 * 
	 * @return gatewayIds
	 */
	private List<String> getProjectOrgCodes() {
		List<String> projectOrgCodes = permissionService.getCurrentUserProjectOrgCodes();
		if (Objects.isNull(projectOrgCodes)) {
			projectOrgCodes = Collections.emptyList();
		}
		log.info(JSON.toJSONString("当前用户转换获取的orgcode列表是 " + projectOrgCodes));
		return projectOrgCodes;
	}

}
