package org.security.trans.dataStatistics.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.security.common.Constant;
import org.security.trans.dailyDuties.entity.InspectionLine;
import org.security.trans.dailyDuties.service.IInspectionLineService;
import org.security.trans.dailyDuties.service.IInspectionService;
import org.security.trans.dataStatistics.dto.InspectionDataDTO;
import org.security.trans.dataStatistics.dto.StatisticsDataDTO;
import org.security.trans.dataStatistics.service.InspectionDataService;
import org.security.trans.dataStatistics.util.CalculationRatioUtil;
import org.security.trans.dataStatistics.vo.InspectionDataVO;
import org.springblade.core.tool.utils.Func;
import org.springframework.stereotype.Service;

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

/**
 * @author ：wzf
 * @since ：Created in 2022/10/27 17:18
 */
@Service
@Slf4j
@AllArgsConstructor
public class InspectionDataServiceImpl implements InspectionDataService {

	private final IInspectionService inspectionService;
	private final IInspectionLineService inspectionLineService;

	@Override
	public IPage<InspectionDataVO> getTableData(InspectionDataDTO inspectionDataDTO, IPage<InspectionDataVO> page) {
		log.info("---------------------现场检查数据统计列表数据获取开始---------------------");
		List<InspectionDataVO> vos = new ArrayList<>();
		//不包含子级机构或不传值
		List<String> aimDepts = setDeptIds(inspectionDataDTO.getDeptId(),inspectionDataDTO.getIncludeChildren());
		//获取目标数据
		List<InspectionDataVO> list = inspectionService.getStatisticsData(inspectionDataDTO, aimDepts);
		if (Func.isNotEmpty(list)) {
			log.info("现场检查统计明细数据[{}]",list);
			//根据id分组获取每条检查记录的检查项数和异常数
			setBaseData(inspectionDataDTO, list, vos);
		}
		//算出一条统计值
		setTotalData(inspectionDataDTO, vos);
		log.info("---------------------现场检查数据统计列表数据获取结束---------------------");
		return page.setRecords(vos);
	}

	/**
	 * 算出一条统计值
	 */
	private void setTotalData(InspectionDataDTO inspectionDataDTO, List<InspectionDataVO> vos) {
		if (Func.isNotEmpty(vos)) {
			InspectionDataVO dataVO = new InspectionDataVO();
			dataVO.setDeptName("总计");
			dataVO.setBeginDate(inspectionDataDTO.getBeginDate());
			dataVO.setEndDate(inspectionDataDTO.getEndDate());
			dataVO.setType("总计");
			calculationValue(vos, dataVO);
			vos.add(0, dataVO);
		}
	}

	/**
	 * 统计基础数据赋值
	 */
	private void setBaseData(InspectionDataDTO inspectionDataDTO, List<InspectionDataVO> list, List<InspectionDataVO> vos) {
		Map<String, List<InspectionDataVO>> collect = list.stream().collect(Collectors.groupingBy(InspectionDataVO::getId));
		List<InspectionDataVO> baseDataList = new ArrayList<>();
		if (Func.isNotEmpty(collect)) {
			collect.forEach((key, value) -> {
				List<InspectionLine> inspectionLineList = inspectionLineService.list(new QueryWrapper<InspectionLine>().lambda()
					.eq(Func.isNotEmpty(key), InspectionLine::getFormId, key)
					.eq(InspectionLine::getFlag, Constant.PROBLEM_STATE_USUUAL));
				//统计开始时间
				value.get(0).setBeginDate(inspectionDataDTO.getBeginDate());
				//统计截止时间
				value.get(0).setEndDate(inspectionDataDTO.getEndDate());
				//检查项数
				value.get(0).setCheckNum(inspectionLineList.size());
				//异常问题数
				value.get(0).setProblemNum((int) inspectionLineList.stream().filter(item -> Constant.USUAL_STATE_TURE.equals(item.getHasProblem())).count());
				//已整改数
				value.get(0).setRectifyNum((Constant.PROBLEM_STATE_SUBMIT.equals(value.get(0).getStatus()) || Constant.PROBLEM_STATE_OVERTIME_SUBMIT.equals(value.get(0).getStatus())) ? 1 : 0);
				//按时整改数
				value.get(0).setRectifyOntimeNum(Constant.PROBLEM_STATE_SUBMIT.equals(value.get(0).getStatus()) ? 1 : 0);
				baseDataList.addAll(value);
			});
			//根据机构和检查类型分组，返回结果赋值
			setResultData(baseDataList, vos,inspectionDataDTO);
		}
	}

	/**
	 * 列表结果赋值
	 */
	private void setResultData(List<InspectionDataVO> value, List<InspectionDataVO> vos,InspectionDataDTO inspectionDataDTO) {
		if (Func.isNotEmpty(value)) {
			Map<String, List<InspectionDataVO>> collect1 = value.stream().collect(Collectors.groupingBy(item -> item.getDeptId().concat("-").concat(item.getDeptName()).concat("-").concat(item.getType())));
			if (Func.isNotEmpty(collect1)) {
				collect1.forEach((key1, value1) -> {
					InspectionDataVO vo = new InspectionDataVO();
					vo.setDeptId(key1.split("-")[0]);
					vo.setDeptName(key1.split("-")[1]);
					vo.setType(key1.split("-")[2]);
					vo.setBeginDate(inspectionDataDTO.getBeginDate());
					vo.setEndDate(inspectionDataDTO.getEndDate());
					calculationValue(value1, vo);
					vos.add(vo);
				});
			}
		}
	}

	/**
	 * 计算
	 */
	private void calculationValue(List<InspectionDataVO> value1, InspectionDataVO vo) {
		vo.setCheckNum(value1.stream().mapToInt(InspectionDataVO::getCheckNum).sum());
		vo.setProblemNum(value1.stream().mapToInt(InspectionDataVO::getProblemNum).sum());
		vo.setProblemRatio(CalculationRatioUtil.getAimRatio(vo.getProblemNum(), vo.getCheckNum()));
		vo.setRectifyNum(value1.stream().mapToInt(InspectionDataVO::getRectifyNum).sum());
		vo.setRectifyRatio(CalculationRatioUtil.getAimRatio(vo.getRectifyNum(), value1.size()));
		vo.setRectifyOntimeNum(value1.stream().mapToInt(InspectionDataVO::getRectifyOntimeNum).sum());
		vo.setRectifyOntimeRatio(CalculationRatioUtil.getAimRatio(vo.getRectifyOntimeNum(), value1.size()));
	}

	/***
	 * 获取查询部门的ids
	 */
	public List<String> setDeptIds(String aimDeptId,String includeChildren) {
		List<String> aimDepts = new ArrayList<>();
		if (Func.isNotEmpty(aimDeptId)) {
			aimDepts.add(aimDeptId);
		}
		//包含子级机构
		if (Constant.INCLUDE_CHILDREN_TYPE_ONE.equals(includeChildren) && Func.isNotEmpty(aimDeptId)) {
			//获取子级机构id
			List<String> deptIdList = inspectionLineService.getChildrenDeptId(aimDeptId);
			aimDepts.addAll(deptIdList);
		}
		return aimDepts;
	}

}
