package com.zcloud.service.risk.impl;

import com.alibaba.fastjson.JSONObject;
import com.zcloud.controller.risk.dto.RiskpointLogsDto;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.mapper.datasource.risk.*;
import com.zcloud.mapper.datasource.system.DictionariesMapper;
import com.zcloud.service.corp.CorpInfoService;
import com.zcloud.service.risk.IdeRepositoryService;
import com.zcloud.service.risk.RiskPointService;
import com.zcloud.util.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 说明：风险点台账
 * 作者：luoxiaobao
 * 时间：2020-12-29
 * 官网：www.zcloudchina.com
 */
@Service
@Transactional //开启事物
public class RiskPointServiceImpl implements RiskPointService {

	@Resource
	private RiskPointMapper riskpointMapper;
	@Autowired
	private IdeRepositoryService iderepositoryService;
	@Autowired
	private CorpInfoService corpInfoService;
	@Resource
	private RiskpointLogMapper riskpointLogMapper;
	@Resource
	private DictionariesMapper dictionariesMapper;
	@Resource
	private RiskPointAnalysisMapper riskPointAnalysisMapper;
	/**新增
	 * @param pd
	 * @throws Exception
	 */
	public void save(PageData pd)throws Exception{
		String UUID = UuidUtil.get32UUID();
		pd.put("RES_ID",UUID);
		riskpointMapper.save(pd);

		saveLog(pd,"0");

		PageData point =  riskpointMapper.findById(pd);
		PageData corp = corpInfoService.findById(pd);

		PageData repository = new PageData();
		repository.putAll(point);
		repository.put("RISKUNIT", point.get("RISKUNITNAME"));
		repository.put("IDENTIFICATION", point.get("PARTSNAME"));
		repository.put("CORP_TYPE", corp.get("CORP_TYPE"));
		repository.put("CORP_TYPE2", corp.get("CORP_TYPE2"));
		repository.put("CORP_TYPE3", corp.get("CORP_TYPE3"));
		repository.put("CORP_TYPE4", corp.get("CORP_TYPE4"));
		repository.put("CORP_TYPE_NAME", corp.get("CORP_TYPE_NAME"));
		repository.put("IDEREPOSITORY_ID", UUID);    //主键
		repository.put("RESOURCETYPE", "0");
		repository.put("ISDELETE", "0");    //是否删除 0 未删除  1已删除
		repository.put("OPERATOR", Jurisdiction.getUsername());    //操作人
		repository.put("OPERATTIME", DateUtil.date2Str(new Date()));    //操作时间
		repository.put("CREATOR", Jurisdiction.getUsername());    //创建人
		repository.put("CREATTIME", DateUtil.date2Str(new Date()));    //创建时间
		int isHas = iderepositoryService.checkHas(repository);
		if(isHas==0) {
			iderepositoryService.save(repository);
		}
	}

	private void saveLog(PageData pd,String type) throws Exception{
		PageData condition = new PageData();
		condition.put("RISKPOINT_ID",pd.getString("RISKPOINT_ID"));
		condition.put("IS_NEW","0");
		riskpointLogMapper.updateByRiskpointId(condition);

		condition.clear();
		condition.put("DICTIONARIES_ID",pd.getString("RISK_CAUSES"));
		PageData risk_causes = dictionariesMapper.findById(condition);

		condition.put("BIANMA",pd.getString("LEVELID"));
		PageData level = dictionariesMapper.findByBianma(condition);

		// 保存历史记录
		condition.clear();
		condition.putAll(pd);
		Warden.initDate(condition);
		condition.put("RISKPOINT_LOG_ID",Warden.get32UUID());
		condition.put("IS_NEW","1");
		condition.put("TYPE",type);
		condition.put("RISK_CAUSES_NAME", risk_causes == null ? "" : risk_causes.getString("NAME"));
		condition.put("LEVEL_NAME",level.getString("NAME"));
		riskpointLogMapper.save(condition);
	}

	/**删除
	 * @param pd
	 * @throws Exception
	 */
	public void delete(PageData pd)throws Exception{
		riskpointMapper.delete(pd);
	}

	/**修改
	 * @param pd
	 * @throws Exception
	 */
	public void edit(PageData pd)throws Exception{
		PageData old = riskpointMapper.findById(pd);
		old.put("RISKPOINT_ANALYSIS_ID",pd.getString("RISKPOINT_ANALYSIS_ID"));
		saveLog(old, "2");
		riskpointMapper.edit(pd);
	}

	/**列表
	 * @param page
	 * @throws Exception
	 */
	public List<PageData> list(Page page)throws Exception{
		return riskpointMapper.datalistPage(page);
	}

	/**列表(全部)
	 * @param pd
	 * @throws Exception
	 */
	public List<PageData> listAll(PageData pd)throws Exception{
		return riskpointMapper.listAll(pd);
	}

	/**查询所有（资源库配置使用）
	 * @param pd
	 * @throws Exception
	 */
	public List<PageData> listAllToRes(PageData pd)throws Exception{
		return riskpointMapper.listAllToRes(pd);
	}
	public List<PageData> listAllByDc(PageData pd)throws Exception{
		return riskpointMapper.listAllByDc(pd);
	}

	/**通过id获取数据
	 * @param pd
	 * @throws Exception
	 */
	public PageData findById(PageData pd)throws Exception{
		return riskpointMapper.findById(pd);
	}

	/**通过id获取数据
	 * @param pd
	 * @throws Exception
	 */
	public PageData findRiskById(PageData pd)throws Exception{
		return riskpointMapper.findRiskById(pd);
	}

	/**批量删除
	 * @param ArrayDATA_IDS
	 * @throws Exception
	 */
	public void deleteAll(String[] ArrayDATA_IDS)throws Exception{
		riskpointMapper.deleteAll(ArrayDATA_IDS);
	}

	/**总数统计
	 * @throws Exception all
	 */
	public List<PageData> statisticsAll(PageData pd)throws Exception{
		return riskpointMapper.statisticsAll(pd);
	}
	/**
	 * 列表 搜索 风险单元辨识部位模糊查询
	 * @param page
	 * @return
	 * @throws Exception
	 */
	public List<PageData> getListForLikeName (Page page)throws Exception{
		return riskpointMapper.datalistPageForNameLikes(page);
	}

	/**app增加位置信息
	 * @param pd
	 * @throws Exception
	 */
	public void editLonAndLat(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		riskpointMapper.editLonAndLat(pd);
	}

	@Override
	public String countByCorpInfo(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		return riskpointMapper.countByCorpInfo(pd);
	}

	public PageData getDiagnosis(PageData pd)throws Exception{
		return riskpointMapper.getDiagnosis(pd);
	}

	@Override
	public Map<String, Object> getLogs(PageData request, Page page) throws Exception {
		//1、查找要展示的数据列表
		PageData condtion = new PageData();
		condtion.put("KEYWORDS", request.getString("KEYWORDS"));
		condtion.put("RISK_UNIT_ID",request.getString("RISK_UNIT_ID"));
		condtion.put("IDENTIFICATION_ID",request.getString("IDENTIFICATION_ID"));
		condtion.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		condtion.put("STATUS", "1");
		page.setPd(condtion);
		List<PageData> raw = riskPointAnalysisMapper.formlistPage(page);
		//2、整理数据，将新老数据整理在一起
		int index = 0;
		List<PageData> _list = new ArrayList<>();
		for (PageData x : raw) {
			List<PageData> logs = null;
			if (StringUtils.isNotBlank(x.getString("RISKPOINT_ID")) && StringUtils.isNotBlank(x.getString("RISKPOINT_ANALYSIS_ID"))) {
				condtion.clear();
				condtion.put("RISKPOINT_ID", x.getString("RISKPOINT_ID"));
				condtion.put("IS_NEW", "1");
				condtion.put("RISKPOINT_ANALYSIS_ID", x.getString("RISKPOINT_ANALYSIS_ID"));
				logs = riskpointLogMapper.findByCondition(condtion);
			} else {
				logs = new ArrayList<>();
			}
			if ( logs.size() <= 0 || "0".equals(logs.get(0).getString("TYPE"))) {
				PageData target = new PageData();
				logs.clear();
				logs.add(target);
				x.put("is_new", "新增");
			} else {
				x.put("is_new", "修改");
			}
			x.put("index", index++);
			x.put("label", "改进之后");
			_list.add(x);
			logs.get(0).put("index", index++);
			logs.get(0).put("label", "改进之前");
			_list.add(logs.get(0));
		}
		// 3、整理数据
		List<RiskpointLogsDto> list = _list.stream()
				.map(RiskpointLogsDto::new)
				.sorted(Comparator.comparing(p -> new BigDecimal(p.getIndex())))
				.collect(Collectors.toList());
		// 4、整理返回数据
		Map<String, Object> map = new HashMap<>();
		map.put("list", list);

		PageData pages = new PageData();
		pages.put("showCount", page.getShowCount());
		pages.put("totalPage", page.getTotalPage());
		pages.put("currentPage", page.getCurrentPage());
		map.put("page", page);
		return map;
	}

	@Override
	public List<RiskpointLogsDto> getLogDiagnosis(PageData pd) throws Exception {
		//1、查找要展示的数据列表
		PageData condtion = new PageData();
		condtion.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		condtion.put("STATUS", "1");
		if (StringUtils.isNotBlank(pd.getString("MONTH"))) {
			String [] dates = pd.getString("MONTH").split("-");
			condtion.put("START_TIME", Warden.getMonthFristDate(dates[0],dates[1]));
			condtion.put("END_TIME", Warden.getMonthLastDate(dates[0],dates[1]));
		} else {
			condtion.put("START_TIME", Warden.getMonthFristDate());
			condtion.put("END_TIME", Warden.getMonthLastDate());
		}

		List<PageData> raw = riskPointAnalysisMapper.formList(condtion);
		//2、整理数据，将新老数据整理在一起
		int index = 0;
		List<PageData> _list = new ArrayList<>();
		for (PageData x : raw) {
			List<PageData> logs = null;
			if (StringUtils.isNotBlank(x.getString("RISKPOINT_ID")) && StringUtils.isNotBlank(x.getString("RISKPOINT_ANALYSIS_ID"))){
				condtion.clear();
				condtion.put("RISKPOINT_ID", x.getString("RISKPOINT_ID"));
				condtion.put("IS_NEW", "1");
				condtion.put("RISKPOINT_ANALYSIS_ID",x.getString("RISKPOINT_ANALYSIS_ID"));
				logs = riskpointLogMapper.findByCondition(condtion);
			}else {
				logs = new ArrayList<>();
			}
			if ( logs.size() <= 0 || "0".equals(logs.get(0).getString("TYPE"))) {
				PageData target = new PageData();
				logs.clear();
				logs.add(target);
				x.put("is_new", "新增");
			} else {
				x.put("is_new", "修改");
			}
			x.put("index", index++);
			x.put("label", "改进之后");
			_list.add(x);
			logs.get(0).put("index", index++);
			logs.get(0).put("label", "改进之前");
			_list.add(logs.get(0));
		}
		// 3、整理数据
		return _list.stream()
				.map(RiskpointLogsDto::new)
				.sorted(Comparator.comparing(p -> new BigDecimal(p.getIndex())))
				.collect(Collectors.toList());
	}
}

