package com.yeejoin.precontrol.common.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import org.apache.commons.io.IOUtils;
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.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.precontrol.common.constant.Constant;
import com.yeejoin.precontrol.common.dto.CommonPageableDto;
import com.yeejoin.precontrol.common.dto.ProjectDto;
import com.yeejoin.precontrol.common.dto.StatisticsDto;
import com.yeejoin.precontrol.common.entity.Company;
import com.yeejoin.precontrol.common.entity.Districts;
import com.yeejoin.precontrol.common.entity.PersonAscription;
import com.yeejoin.precontrol.common.entity.PersonClock;
import com.yeejoin.precontrol.common.entity.Project;
import com.yeejoin.precontrol.common.entity.ProjectAccount;
import com.yeejoin.precontrol.common.entity.ProjectCamera;
import com.yeejoin.precontrol.common.entity.ProjectCompany;
import com.yeejoin.precontrol.common.entity.ProjectCoordinate;
import com.yeejoin.precontrol.common.entity.ProjectDevice;
import com.yeejoin.precontrol.common.entity.Task;
import com.yeejoin.precontrol.common.entity.TaskRiskControl;
import com.yeejoin.precontrol.common.entity.access.HttpAccessVerifyParam;
import com.yeejoin.precontrol.common.enums.ClockInOutEum;
import com.yeejoin.precontrol.common.enums.TypeKeyEnum;
import com.yeejoin.precontrol.common.exception.BaseException;
import com.yeejoin.precontrol.common.mapper.PersonAscriptionMapper;
import com.yeejoin.precontrol.common.mapper.ProjectCompanyMapper;
import com.yeejoin.precontrol.common.mapper.ProjectCoordinateMapper;
import com.yeejoin.precontrol.common.mapper.ProjectMapper;
import com.yeejoin.precontrol.common.mapper.StatisticsMapper;
import com.yeejoin.precontrol.common.param.ProjectImportParam;
import com.yeejoin.precontrol.common.service.IBadManagementService;
import com.yeejoin.precontrol.common.service.ICompanyService;
import com.yeejoin.precontrol.common.service.IDistrictsService;
import com.yeejoin.precontrol.common.service.IPersonAscriptionService;
import com.yeejoin.precontrol.common.service.IPersonClockService;
import com.yeejoin.precontrol.common.service.IPersonService;
import com.yeejoin.precontrol.common.service.IProjectAccountService;
import com.yeejoin.precontrol.common.service.IProjectCameraService;
import com.yeejoin.precontrol.common.service.IProjectCoordinateService;
import com.yeejoin.precontrol.common.service.IProjectDeviceService;
import com.yeejoin.precontrol.common.service.IProjectScoreService;
import com.yeejoin.precontrol.common.service.IProjectService;
import com.yeejoin.precontrol.common.service.IStatisticsService;
import com.yeejoin.precontrol.common.service.ITaskRiskControlService;
import com.yeejoin.precontrol.common.service.ITaskService;
import com.yeejoin.precontrol.common.utils.DateUtils;
import com.yeejoin.precontrol.common.utils.DistrictsUtils;
import com.yeejoin.precontrol.common.utils.EasyPoiUtil;
import com.yeejoin.precontrol.common.utils.PlatformUtils;
import com.yeejoin.precontrol.common.utils.StringUtil;
import com.yeejoin.precontrol.common.vo.BadProjectVo;
import com.yeejoin.precontrol.common.vo.ProjectVo;

import lombok.extern.slf4j.Slf4j;

/**
 * 项目信息 服务实现类
 *
 * @author duanwei
 * @date 2020-06-30
 */
@Service
@Slf4j
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements IProjectService {

	@Autowired
	PlatformUtils platformUtils;

	@Autowired
	ProjectMapper projectMapper;

	@Autowired
	IProjectCoordinateService iProjectCoordinateService;
	@Autowired
	ProjectCoordinateMapper projectCoordinateMapper;

	@Autowired
	IProjectService iProjectService;

	@Autowired
	PersonAscriptionMapper personAscriptionMapper;

	@Autowired
	IDistrictsService iDistrictsService;

	@Autowired
	IPersonAscriptionService iPersonAscriptionService;

	/**
	 * 项目分数服务
	 */
	@Autowired
	IProjectScoreService projectScoreService;

	@Autowired
	IPersonService iPersonService;

	@Autowired
	ITaskService iTaskService;

	@Autowired
	IBadManagementService iBadManagementService;

	@Autowired
	StatisticsMapper statisticsMapper;

	@Autowired
	ProjectCompanyMapper projectCompanyMapper;

	@Autowired
	IProjectDeviceService projectDeviceService;

	@Autowired
	IStatisticsService statisticsService;

	@Autowired
	ITaskRiskControlService iTaskRiskControlService;

	@Autowired
	ICompanyService iCompanyService;

	@Autowired
	IPersonClockService iPersonClockService;
	@Autowired
	IProjectCameraService projectCameraService;
	
	@Autowired
	IProjectAccountService iProjectAccountService;
	/**
	 * 江西电建公司id
	 */
	@Value("${jxdj.id}")
	private String companyId;
	@Override
	public IPage<ProjectVo> listByPage(CommonPageableDto pageable, ProjectDto projectDto) {
		if (pageable.getIsAll() == 1) {
			pageable.setPageNumber(0);
			pageable.setPageSize(Integer.MAX_VALUE);
		}
		Page<ProjectVo> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		IPage<ProjectVo> iPageData = projectMapper.listByPage(page, projectDto);
		/**
		 * 为解决接口过慢问题，已将以下for循环内的三个数据查询sql整合到上面查询中 vo.setCompanyNum(companyNum);
		 * vo.setPersonNum(personNum); vo.setRegionName(districtsName.toString());
		 * 将以下未找到前端使用的两个数据查询注释
		 * vo.setPlatformProjectName(platformUtils.getDepartmentNameByOrgCode(vo.getOrgCode()));
		 * vo.setSecurityScore(securityScore(vo.getId()));
		 */
		return iPageData;
	}

	@Override
	public List<HashMap<String, Object>> projectSelect() {
		return projectMapper.projectSelect();
	}

	@Override
	public Integer securityScore(Long projectId) {
		Date date = new Date();
		SimpleDateFormat startFormat = new SimpleDateFormat("yyyy-MM-dd 12:00:00");
		SimpleDateFormat dayStartFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
		SimpleDateFormat endFormat = new SimpleDateFormat("yyyy-MM-dd 23:30:00");
		SimpleDateFormat dayEndFormat = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
		String start = startFormat.format(date);
		String end = endFormat.format(date);
		String dayStart = dayStartFormat.format(date);
		String dayEnd = dayEndFormat.format(date);
		// 未交底扣分
		AtomicReference<Integer> pointsDeductionForViolations = new AtomicReference<>(100);
		// 当日扣分 最大为40
		int jobTotal = 0;
		Project project = projectMapper.selectById(projectId);
		if (project == null) {
			return 0;
		}
		Long jobNum = project.getJobNum();
		if (jobNum == null) {
			jobNum = 0L;
		}
		// （1）安全隐患 1、未交底总数量: 本项目未交底总数达2次以内减5分、3次-5次减10分，5-10次减20次，11次以上减40分
		if (jobNum > 0 && jobNum <= 2) {
			pointsDeductionForViolations.updateAndGet(v -> v - 5);
		}
		if (jobNum > 2 && jobNum <= 5) {
			pointsDeductionForViolations.updateAndGet(v -> v - 10);
		}
		if (jobNum > 5 && jobNum <= 10) {
			pointsDeductionForViolations.updateAndGet(v -> v - 20);
		}
		if (jobNum > 10) {
			pointsDeductionForViolations.updateAndGet(v -> v - 40);
		}
		// （2）当日增减： 按入场计算
		// 1、分包商未交底: 本项目当日中的分包商(或班组)未执行三交三查任务，每个分包商(或班组)未执行减5分；
		// 2、项目未交底：本项目当日未发生交底任务（含所有分包商或班组），减40分;说明本项目未按规范执行；
		// 3、违章行为数量：违章行为每增加一个加4分，说明项目督查到位。
		List<PersonClock> clockList = iPersonClockService.list(new LambdaQueryWrapper<PersonClock>()
				.eq(PersonClock::getClockProjectId, projectId).between(PersonClock::getCreateDate, dayStart, dayEnd)
				.eq(PersonClock::getInOrOut, ClockInOutEum.in.getValue()));
		Set<Long> clockPersonIdList = clockList.stream().map(clock -> clock.getPersonId()).collect(Collectors.toSet());
		List<PersonAscription> companyList = null;
		if (StringUtil.isNotEmpty(clockPersonIdList)) {
			companyList = iPersonAscriptionService.list(new LambdaQueryWrapper<PersonAscription>()
					.select(PersonAscription::getCompanyId).eq(PersonAscription::getProjectId, projectId)
					.in(PersonAscription::getPersonId, clockPersonIdList).isNotNull(PersonAscription::getCompanyId)
					.groupBy(PersonAscription::getCompanyId));
		}
		Set<Long> companyIdList = null;
		// 如果有人入场
		if (StringUtil.isNotEmpty(companyList)) {
			companyIdList = companyList.stream().map(company -> company.getCompanyId()).collect(Collectors.toSet());
			// 过滤出分包商
			List<Company> list = iCompanyService.list(new LambdaQueryWrapper<Company>()
					.eq(Company::getTypeKey, TypeKeyEnum.COMPANY).in(Company::getId, companyIdList));
			companyIdList = list.stream().map(company -> company.getId()).collect(Collectors.toSet());
			// 获取今天的交底情况
			Set<Long> taskPersonIdList = null;
			List<Task> taskList = iTaskService.list(new LambdaQueryWrapper<Task>().eq(Task::getProjectId, projectId)
					.eq(Task::getType, 1).between(Task::getCreateDate, dayStart, dayEnd));
			// 发起任务的人的id
			if (StringUtil.isNotEmpty(taskList)) {
				taskPersonIdList = taskList.stream().map(task -> task.getCreatePersonId()).collect(Collectors.toSet());
				// 发起任务的人得分包商id
				Set<Long> taskCompanyIds = null;
				// 根据发起任务的人 获取对应的分包商id
				List<PersonAscription> taskCompanyIdList = iPersonAscriptionService
						.list(new LambdaQueryWrapper<PersonAscription>().select(PersonAscription::getCompanyId)
								.in(PersonAscription::getPersonId, taskPersonIdList));
				if (StringUtil.isNotEmpty(taskCompanyIdList)) {
					taskCompanyIds = taskCompanyIdList.stream().map(task -> task.getCompanyId())
							.collect(Collectors.toSet());
					// 过滤出分包商
					List<Company> list2 = iCompanyService.list(new LambdaQueryWrapper<Company>()
							.eq(Company::getTypeKey, TypeKeyEnum.COMPANY).in(Company::getId, taskCompanyIds));
					taskCompanyIds = list2.stream().map(company -> company.getId()).collect(Collectors.toSet());
					// 时间必须在12点-23点之间才扣分
					try {
						long currentTimeMillis = System.currentTimeMillis();
						long date1 = DateUtils.date2TimeStamp(start, DateUtils.DATE_TIME_PATTERN);
						long date2 = DateUtils.date2TimeStamp(end, DateUtils.DATE_TIME_PATTERN);
						log.info("交底任务已经发布 currentTimeMillis:{},startTime:{},endTime:{}", currentTimeMillis, date1,
								date2);
						if (currentTimeMillis > date1 && currentTimeMillis < date2) {
							// 得到未交底得数量
							int jobCount = companyIdList.size() - taskCompanyIds.size();
							if (jobCount < 0) {
								jobCount = 0;
							}
							jobTotal = jobCount * 5;
							if (jobTotal >= 40) {
								jobTotal = 40;
							}
						} else {
							jobTotal = 0;
						}
					} catch (Exception e) {
						log.error("时间转换异常");
					}
				}
			} else {
				// 没有发任务 判断下当前时间
				try {
					long currentTimeMillis = System.currentTimeMillis();
					long date1 = DateUtils.date2TimeStamp(start, DateUtils.DATE_TIME_PATTERN);
					long date2 = DateUtils.date2TimeStamp(end, DateUtils.DATE_TIME_PATTERN);
					log.info("交底任务未发布 currentTimeMillis:{},startTime:{},endTime:{}", currentTimeMillis, date1, date2);
					if (currentTimeMillis > date1 && currentTimeMillis < date2) {
						jobTotal = 40;
					} else {
						jobTotal = 0;
					}
				} catch (Exception e) {
					log.error("时间转换异常");
				}
			}
		}
		int badTotal = 0;
		// 违规任务,今日的
		List<Task> taskList = iTaskService.list(new LambdaQueryWrapper<Task>().eq(Task::getProjectId, projectId)
				.eq(Task::getType, 2).between(Task::getCreateDate, dayStart, dayEnd));
		if (StringUtil.isNotEmpty(taskList)) {
			badTotal = taskList.size() * 4;
		}
		Integer scope = pointsDeductionForViolations.get();
		scope = scope - jobTotal + badTotal;
		if (scope >= 100) {
			scope = 100;
		} else if (scope <= 0) {
			scope = 0;
		}
		return scope;
	}

//    @Override 公司地图做法
//    public List<Map<String, Object>> getMapLine() {
//        List<Map<String, Object>> mapList = new ArrayList<>();
//        List<Project> projectList = this.list();
//        if (StringUtil.isNotEmpty(projectList)) {
//            mapList = projectList.stream().map(project -> {
//                Map<String, Object> param = new LinkedHashMap<>();
//                Long id = project.getId();
//                param.put("id", id);
//                param.put("name", project.getName());
//                param.put("lng", project.getLongitude());
//                param.put("lat", project.getLatitude());
//                param.put("type", project.getPointType());
//                Integer score = securityScore(id);
//                param.put("score", score);
//                // 计算项目安全情况
//                String status;
//                if (score >= 90) {
//                    status = "green";
//                } else if (score >= 60 && score < 90) {
//                    status = "yellow";
//                } else {
//                    status = "red";
//                }
//                param.put("status", status);
//                param.put("path", getPath(id));
//                String lineJson = project.getLineJson();
//                if (StringUtil.isNotEmpty(lineJson)) {
//                    param.put("aliasName", this.getValueFromStringJson(lineJson, "aliasName"));
//                    param.put("pathName", this.getValueFromStringJson(lineJson, "pathName"));
//                    param.put("gradient", this.getValueFromStringJson(lineJson, "gradient"));
//                    param.put("width", this.getValueFromStringJson(lineJson, "width"));
//                    param.put("height", this.getValueFromStringJson(lineJson, "height"));
//                    param.put("position", this.getValueFromStringJson(lineJson, "position"));
//                } else {
//                    param.put("aliasName", "");
//                    param.put("pathName", "");
//                    param.put("gradient", "");
//                    param.put("width", "");
//                    param.put("height", "");
//                    param.put("position", "");
//                }
//                List<PersonAscription> list1 = iPersonAscriptionService
//                        .list(new LambdaQueryWrapper<PersonAscription>().select(PersonAscription::getCompanyId)
//                                .eq(PersonAscription::getProjectId, id).groupBy(PersonAscription::getCompanyId));
//                Integer companyNum = list1.size();
//                if (companyNum == null) {
//                    param.put("companyNum", 0);
//                } else {
//                    param.put("companyNum", companyNum);
//                }
//                List<PersonAscription> list2 = iPersonAscriptionService
//                        .list(new LambdaQueryWrapper<PersonAscription>().select(PersonAscription::getPersonId)
//                                .eq(PersonAscription::getProjectId, id).groupBy(PersonAscription::getPersonId));
//                Integer personNum = list2.size();
//                if (personNum == null) {
//                    param.put("personNum", 0);
//                } else {
//                    param.put("personNum", personNum);
//                }
//                // 地区
//                if (StringUtils.isNotBlank(project.getRegion())) {
//                    String[] split = project.getRegion().split(",");
//                    LinkedList<Long> collect = Arrays.stream(split).map(Long::parseLong)
//                            .collect(Collectors.toCollection(LinkedList::new));
//                    Collection<Districts> districts = iDistrictsService.listByIds(collect);
//                    StringBuffer districtsName = new StringBuffer();
//                    districts.forEach(districts1 -> districtsName.append(districts1.getExtName()).append(","));
//                    districtsName.deleteCharAt(districtsName.length() - 1);
//                    param.put("region", districtsName.toString());
//                } else {
//                    log.error("企业位置地区数据为空!");
//                }
//                return param;
//            }).collect(Collectors.toList());
//        }
//        return mapList;
//    }

	@Override
	public Object getMapLine(String orgCode, Long projectId) throws IOException {
		List<Object> data = new ArrayList<>();
		List<Project> projectList;
		if (projectId != null) {
			projectList = this.list(new LambdaQueryWrapper<Project>().eq(Project::getId, projectId));
		} else {
			if (StringUtil.isNotEmpty(orgCode)) {
				projectList = this.list(new LambdaQueryWrapper<Project>().eq(Project::getOrgCode, orgCode)
						.in(Project::getStatus, Arrays.asList("开发", "策划", "在建")));
			} else {
				projectList = this.list(
						new LambdaQueryWrapper<Project>().in(Project::getStatus, Arrays.asList("开发", "策划", "在建")));
			}
		}
		ClassPathResource resource = new ClassPathResource("json/projcetJxdj.json");
		InputStream inputStream = resource.getInputStream();
		String result = IOUtils.toString(inputStream, String.valueOf(StandardCharsets.UTF_8));
		Project center = JSONObject.parseObject(result, Project.class);
		Map<String, Object> centerMap = new LinkedHashMap<>();
		Long centerId = center.getId();
		LinkedList centerArray = new LinkedList();
		centerArray.add(center.getLongitude());
		centerArray.add(center.getLatitude());
		centerMap.put("id", centerId);
		centerMap.put("name", center.getName());
		centerMap.put("value", centerArray);
		Integer centerScore = projectScoreService.getNowDateScore(centerId);
		centerMap.put("score", centerScore);
		String centerStatus;
		if (centerScore >= 90) {
			centerStatus = "green";
		} else if (centerScore >= 60 && centerScore < 90) {
			centerStatus = "yellow";
		} else {
			centerStatus = "red";
		}
		centerMap.put("status", centerStatus);
		centerMap.put("companyNum", 0);
		centerMap.put("personNum", 0);
		if (StringUtils.isNotBlank(center.getRegion())) {
			String[] split = center.getRegion().split(",");
			LinkedList<Long> collect = Arrays.stream(split).map(Long::parseLong)
					.collect(Collectors.toCollection(LinkedList::new));
			Collection<Districts> districts = iDistrictsService.listByIds(collect);
			StringBuffer districtsName = new StringBuffer();
			districts.forEach(districts1 -> districtsName.append(districts1.getExtName()).append(","));
			districtsName.deleteCharAt(districtsName.length() - 1);
			centerMap.put("region", districtsName.toString());
		}

		if (StringUtil.isNotEmpty(projectList)) {
			projectList.parallelStream().forEach(project -> {
				if (project.getId() == 0) {
					return;
				}
				Map<String, Object> param = new LinkedHashMap<>();
				Long id = project.getId();
				param.put("id", id.toString());
				param.put("name", project.getName());
				LinkedList projectArray = new LinkedList();
				projectArray.add(project.getLongitude());
				projectArray.add(project.getLatitude());
				param.put("value", projectArray);
				// 算分
//                Integer score = securityScore(id);
				Integer score = projectScoreService.getNowDateScore(id);
				param.put("score", score);
				// 计算项目安全情况
				String status;
				if (score >= 90) {
					// 低级
					status = "green";
				} else if (score >= 60 && score < 90) {
					// 中级
					status = "yellow";
				} else {
					// 高级
					status = "red";
				}
				param.put("status", status);
				StatisticsDto statisticsDto = new StatisticsDto(null, id, null);
				int companyNum = statisticsMapper.companyCount(statisticsDto, true);
				param.put("companyNum", companyNum);
				int personNum = statisticsMapper.projectPersonCount(statisticsDto, TypeKeyEnum.COMPANY.getLongType(),
						null, null);
				param.put("personNum", personNum);
				// 地区
				if (StringUtils.isNotBlank(project.getRegion())) {
					String[] split = project.getRegion().split(",");
					LinkedList<Long> collect = Arrays.stream(split).map(Long::parseLong)
							.collect(Collectors.toCollection(LinkedList::new));
					Collection<Districts> districts = iDistrictsService.listByIds(collect);
					StringBuffer districtsName = new StringBuffer();
					districts.forEach(districts1 -> districtsName.append(districts1.getExtName()).append(","));
					districtsName.deleteCharAt(districtsName.length() - 1);
					param.put("region", districtsName.toString());
				} else {
					log.error("企业位置地区数据为空!");
				}
				int riskNum = iTaskRiskControlService
						.count(new LambdaQueryWrapper<TaskRiskControl>().eq(TaskRiskControl::getProjectId, id));
				param.put("riskNum", riskNum);
				LinkedList linkedList1 = new LinkedList();
				linkedList1.add(param);
				linkedList1.add(centerMap);
				data.add(linkedList1);
			});
		}
		return data;
	}

	private Object getValueFromStringJson(String str, String key) {
		if (org.springframework.util.StringUtils.isEmpty(str)) {
			return "";
		} else {
			JSONObject lineJson = JSONObject.parseObject(str);
			return lineJson.get(key);
		}
	}

	private JSONArray getPath(Long id) {
		JSONArray pathArray = new JSONArray();
		// 第一条数据是业务点 第二条是不变得固定点
		pathArray.add(this.getLngAndLat(id));
		pathArray.add(this.getLngAndLat(0L));
		return pathArray;
	}

	private JSONObject getLngAndLat(Long id) {
		JSONObject lngLatObject = new JSONObject();
		lngLatObject.put("lng", "");
		lngLatObject.put("lat", "");
		if (id != null) {
			Project project = this.getById(id);
			if (project != null) {
				lngLatObject.put("lng", project.getLongitude());
				lngLatObject.put("lat", project.getLatitude());
			}
		}
		return lngLatObject;
	}

	@Override
	public IPage<BadProjectVo> pageBadProject(boolean isBad, boolean isAllStatus, CommonPageableDto pageable,
			BadProjectVo badProjectVo) {
		if (pageable.getIsAll() == 1) {
			pageable.setPageNumber(0);
			pageable.setPageSize(Integer.MAX_VALUE);
		}
		Page<BadProjectVo> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		List<BadProjectVo> list = projectMapper.badProject(page, isBad, isAllStatus, badProjectVo);
		page.setRecords(list);
		return page;
	}

	@Override
	public Object selectById(Long id, Long companyId) {
		Project project = iProjectService.getById(id);
		ProjectVo projectVo = new ProjectVo();
		BeanUtils.copyProperties(project, projectVo);
		Long projectId = project.getId();
		QueryWrapper<PersonAscription> personAscriptionQueryWrapper1 = new QueryWrapper<>();
		personAscriptionQueryWrapper1.eq("project_id", projectId);
		personAscriptionQueryWrapper1.groupBy("company_id");

		StatisticsDto statisticsDto = new StatisticsDto(null, id, companyId);
		int companyNum = statisticsMapper.companyCount(statisticsDto, true);
		projectVo.setCompanyNum(companyNum);
		int personNum = statisticsMapper.projectPersonCount(statisticsDto, TypeKeyEnum.COMPANY.getLongType(), null,
				null);
		projectVo.setPersonNum(personNum);
		// 转换地区
		if (StringUtils.isNotBlank(projectVo.getRegion())) {
			String[] split = projectVo.getRegion().split(",");
			LinkedList<Long> collect = Arrays.stream(split).map(Long::parseLong)
					.collect(Collectors.toCollection(LinkedList::new));
			Collection<Districts> districts = iDistrictsService.listByIds(collect);
			StringBuffer districtsName = new StringBuffer();
			districts.forEach(districts1 -> districtsName.append(districts1.getExtName()).append(","));
			districtsName.deleteCharAt(districtsName.length() - 1);
			projectVo.setRegionName(districtsName.toString());
		}
//        projectVo.setSecurityScore(iProjectService.securityScore(projectId));
		projectVo.setSecurityScore(projectScoreService.getNowDateScore(projectId));
		if (null != project.getOrgCode()) {
			projectVo.setOrgCode(project.getOrgCode());
			projectVo.setPlatformProjectName(platformUtils.getDepartmentNameByOrgCode(project.getOrgCode()));
		}

		// 项目坐标信息
		List<ProjectCoordinate> projectCoordinates = projectCoordinateMapper
				.selectList(new QueryWrapper<ProjectCoordinate>().lambda().eq(ProjectCoordinate::getProjectId, id));
		projectVo.setProjectCoordinateList(projectCoordinates);

		// 项目分包商
		List<ProjectCompany> companys = projectCompanyMapper.listByProjectId(projectId);
		projectVo.setProjectCompanyList(companys);
		Optional<String> optional = Optional.ofNullable(project).map(Project::getProjectRegion);
		optional.ifPresent(o -> {
			List<ProjectCamera> cameraList = projectCameraService.list(new QueryWrapper<ProjectCamera>().lambda()
					.eq(ProjectCamera::getRegionIndexCode, project.getProjectRegion()));
			projectVo.setCameraList(cameraList);
		});
		List<ProjectDevice> devices = projectDeviceService
				.list(new LambdaQueryWrapper<ProjectDevice>().eq(ProjectDevice::getProjectId, projectId));
		projectVo.setProjectDeviceList(devices);
		
		//项目专户信息
		ProjectAccount projectAccount = iProjectAccountService.getOne(new LambdaQueryWrapper<ProjectAccount>().eq(ProjectAccount::getProjectId, projectId));
		projectVo.setProjectAccount(projectAccount);
		return projectVo;
	}

	@Override
	public List<Project> projectImport(MultipartFile file) throws Exception {
		List<ProjectImportParam> projectImportParams = EasyPoiUtil.importExcel(file, 1, 1, ProjectImportParam.class);
		FeignClientResult<Collection<DepartmentModel>> result=   Privilege.departmentClient.queryDeptTree(null, Long.valueOf(companyId));
		Collection<DepartmentModel> collection = result.getResult();
		List<Project> data = new ArrayList<>();
		projectImportParams.forEach(projectImportParam -> {
			Project project = new Project();
			BeanUtils.copyProperties(projectImportParam, project);
			if (StringUtils.isEmpty(project.getProjectNum())) {
				throw new BaseException("项目编号不能为空");
			}
			if (StringUtils.isEmpty(project.getName())) {
				throw new BaseException("项目名称不能为空");
			}
			List<Project> projectNum = iProjectService
					.list(new QueryWrapper<Project>().eq("project_num", project.getProjectNum()));
			List<Project> projectName = iProjectService.list(new QueryWrapper<Project>().eq("name", project.getName()));
			if (StringUtil.isNotEmpty(projectName)) {
				throw new BaseException("项目名称重复: " + project.getName());
			}
			if (StringUtil.isNotEmpty(projectNum)) {
				throw new BaseException("项目编号重复: " + project.getProjectNum());
			}
			String regionName = projectImportParam.getRegionName();
			if (regionName != null) {
				String region = DistrictsUtils.findByName(regionName);
				if (region == null) {
					throw new BaseException("地区内容填写有误,系统暂无法匹配: " + projectName);
				}
				project.setRegion(region);
			} else {
				throw new BaseException("地区内容未填写: " + projectName);
			}
		    String orgName = projectImportParam.getOrgName();
		    if(!StringUtils.isEmpty(orgName)) 
		    {
		    	DepartmentModel departmentModel = isMatch(collection, orgName);
		    	if(departmentModel ==null){
		    		throw new BaseException("项目部名称不存在: " +orgName);
		    	}else 
		    	{
		    		project.setOrgCode(departmentModel.getOrgCode());
		    	}
		    }
			data.add(project);
		});
		return data;
	}

	
	private DepartmentModel isMatch(Collection<DepartmentModel> collection,String orgName) 
	{
		if(collection!=null) 
		{
			for(Object object:collection) 
			{
				DepartmentModel departmentModel = JSONObject.parseObject(JSONObject.toJSONString(object), DepartmentModel.class);
				if(departmentModel.getDepartmentName().equals(orgName))
				{
					return departmentModel;
				}else 
				{
					DepartmentModel departmentModel1= isMatch(departmentModel.getChildren(),orgName);
					if(departmentModel1!=null) 
					{
						return departmentModel1;
					}
				}
			}
		}
		return null;
	}
	
	@Override
	public List<Long> listByPlatformOrgCode(String orgcode) {
		List<Project> list = iProjectService.list(new LambdaQueryWrapper<Project>().eq(Project::getOrgCode, orgcode));
		if (StringUtil.isNotEmpty(list)) {
			List<Long> ids = list.stream().map(p -> p.getId()).collect(Collectors.toList());
			return ids;
		} else {
			return null;
		}
	}

	/**
	 * 保存项目坐标信息
	 *
	 * @param projectDto
	 * @return
	 */
	@Override
	@Transactional
	public void saveProject(ProjectDto projectDto) {
		Project project = new Project();
		BeanUtils.copyProperties(projectDto, project, "id");
		int result = projectMapper.insert(project);
		List<ProjectCoordinate> projectCoordinateList = projectDto.getProjectCoordinateList();
		if (result > 0) {
			if (null != projectCoordinateList && projectCoordinateList.size() > 0) {
				projectCoordinateList.stream().forEach(projectCoordinate -> {
					projectCoordinate.setProjectId(project.getId());
					if (projectCoordinate.getIsMain()) {
						project.setClockScope(projectCoordinate.getClockScope());
						project.setLatitude(projectCoordinate.getLatitude());
						project.setLongitude(projectCoordinate.getLongitude());
					}
				});
				iProjectCoordinateService.saveBatch(projectCoordinateList);
				projectMapper.updateById(project);
			}
		}
		projectDto.setId(project.getId());
	}

	/**
	 * 根据id修改项目信息和坐标信息
	 *
	 * @param projectDto
	 */
	@Override
	@Transactional
	public void updateById(ProjectDto projectDto) {
		Project project = new Project();
		BeanUtils.copyProperties(projectDto, project);
		// 先删除已存在的项目坐标信息
//		projectCoordinateMapper.delete(
//				new QueryWrapper<ProjectCoordinate>().lambda().eq(ProjectCoordinate::getProjectId, projectDto.getId()));
		List<ProjectCoordinate> projectCoordinateList = projectDto.getProjectCoordinateList();
		// 保存新的坐标信息
		if (null != projectCoordinateList && projectCoordinateList.size() > 0) {
			projectCoordinateList.stream().forEach(projectCoordinate -> {
				projectCoordinate.setProjectId(project.getId());
				if (projectCoordinate.getIsMain()) {
					project.setClockScope(projectCoordinate.getClockScope());
					project.setLatitude(projectCoordinate.getLatitude());
					project.setLongitude(projectCoordinate.getLongitude());
				}
			});
			iProjectCoordinateService.saveOrUpdateBatch(projectCoordinateList);
		}
		// 保存设备信息
		projectDeviceService
				.remove(new LambdaQueryWrapper<ProjectDevice>().eq(ProjectDevice::getProjectId, projectDto.getId()));
		List<ProjectDevice> projectDeviceList = projectDto.getProjectDeviceList();
		if (StringUtil.isNotEmpty(projectDeviceList)) {
			projectDeviceList.stream().forEach(projectDevice -> {
				projectDevice.setProjectId(project.getId());
			});
			projectDeviceService.saveBatch(projectDeviceList);
		}
		projectMapper.updateById(project);
	}

	/**
	 * 根据项目id删除项目信息和坐标信息
	 *
	 * @param id
	 */
	@Override
	@Transactional
	public boolean removeById(Long id) {
		Project project = this.getById(id);
		projectCoordinateMapper
				.delete(new LambdaQueryWrapper<ProjectCoordinate>().eq(ProjectCoordinate::getProjectId, id));
		projectMapper.deleteById(id);
		// 更新推送
		statisticsService.initWs(project.getOrgCode(), Constant.WS_COMPOSITESUM);
		statisticsService.initWs(project.getOrgCode(), Constant.WS_MAPPROJECTSUM);
		return true;
	}

	/**
	 * 根据项目id批量删除项目信息和坐标信息
	 *
	 * @param ids
	 */
	@Override
	@Transactional
	public boolean removeByIds(List<Long> ids) {
		int count = iPersonAscriptionService
				.count(new LambdaQueryWrapper<PersonAscription>().in(PersonAscription::getProjectId, ids));
		if (count > 0) {
			throw new BaseException("项目包含人员,无法删除");
		}

		ids.forEach(id -> {
			projectCoordinateMapper
					.delete(new LambdaQueryWrapper<ProjectCoordinate>().eq(ProjectCoordinate::getProjectId, id));
		});
		projectMapper.deleteBatchIds(ids);
		// 更新推送
		statisticsService.initWs("0", Constant.WS_COMPOSITESUM);
		statisticsService.initWs("0", Constant.WS_MAPPROJECTSUM);
		return true;
	}

	/**
	 * 根据导入的数据保存项目信息和坐标信息
	 *
	 * @param data
	 * @return
	 */
	@Override
	@Transactional
	public Boolean saveProjectImportData(List<Project> data) {
		data.forEach(item -> {
			iProjectService.saveOrUpdate(item);
			if (null != item.getLatitude() && null != item.getLongitude()) {
				ProjectCoordinate projectCoordinate = new ProjectCoordinate();
				projectCoordinate.setProjectId(item.getId());
				projectCoordinate.setIsMain(true);
				projectCoordinate.setCreateDate(new Date());
				BeanUtils.copyProperties(item, projectCoordinate);
				projectCoordinateMapper.insert(projectCoordinate);
			}
		});
		return true;
	}

	public static List<String> getContent(String filePath) {
		// 读取文件
		List<String> lineLists = null;
		try {
			lineLists = Files.lines(Paths.get(filePath), Charset.defaultCharset())
					.flatMap(line -> Arrays.stream(line.split("\n"))).collect(Collectors.toList());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return lineLists;
	}
}
