/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.security.trans.securityCommandCenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.security.common.Constant;
import org.security.flow.core.constant.ProcessConstant;
import org.security.flow.core.entity.BladeFlow;
import org.security.flow.core.entity.BladeFlowDef;
import org.security.flow.core.feign.IFlowClient;
import org.security.flow.core.utils.FlowUtil;
import org.security.system.feign.ISysClient;
import org.security.trans.basic.service.IDepartmentService;
import org.security.trans.common.service.IFileService;
import org.security.ht.vo.common.UploadVO;
import org.security.trans.dailyDuties.service.IInspectionService;
import org.security.trans.dataStatistics.dto.AnswerAlarmDataDTO;
import org.security.trans.dataStatistics.dto.StatisticsDataDTO;
import org.security.trans.dataStatistics.vo.AnswerAlarmDataVO;
import org.security.trans.dataStatistics.vo.UnlocaleCheckDataVO;
import org.security.trans.securityCommandCenter.dto.SccAlarmPushDTO;
import org.security.trans.securityCommandCenter.dto.SccAnswerAlarmDTO;
import org.security.trans.securityCommandCenter.entity.SccAlarmPush;
import org.security.trans.securityCommandCenter.entity.SccAnswerAlarm;
import org.security.trans.securityCommandCenter.service.ISccAlarmPushService;
import org.security.trans.securityCommandCenter.vo.SccAnswerAlarmVO;
import org.security.trans.securityCommandCenter.mapper.SccAnswerAlarmMapper;
import org.security.trans.securityCommandCenter.service.ISccAnswerAlarmService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.Func;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 安保指挥中心-联系接警记录 服务实现类
 *
 * @author BladeX
 * @since 2022-07-06
 */
@Slf4j
@Service
@AllArgsConstructor
public class SccAnswerAlarmServiceImpl extends ServiceImpl<SccAnswerAlarmMapper, SccAnswerAlarm> implements ISccAnswerAlarmService {
	private final IFileService fileService;
	private final ISccAlarmPushService sccAlarmPushService;
	private final IFlowClient flowClient;
	private final IDepartmentService departmentService;
	private final ISysClient sysClient;
	private final IInspectionService iInspectionService;

	@Override
	public IPage<SccAnswerAlarmVO> selectSccAnswerAlarmPage(IPage<SccAnswerAlarmVO> page, SccAnswerAlarmDTO sccAnswerAlarmDTO) {
		log.info("==============获取联系接警记录开始==============");
		List<SccAnswerAlarmVO> vos = baseMapper.selectSccAnswerAlarmPage(page, sccAnswerAlarmDTO);
		if (Func.isNotEmpty(vos)) {
			vos.forEach(item ->{
				item.setPlaceName(Func.isNotEmpty(item.getPlace()) ? departmentService.getById(item.getPlace()).getDeptName() : null);
			});
			List<SccAnswerAlarmVO> collect = vos.stream().sorted(Comparator.comparing(SccAnswerAlarmVO::getUpdatedTime, Comparator.nullsLast(Comparator.reverseOrder()))).collect(Collectors.toList());
			return page.setRecords(collect);
		}
		log.info("==============获取联系接警记录结束==============");
		return page.setRecords(vos);
	}

	@Override
	public SccAnswerAlarmVO getData(String id) {
		log.info("==============获取联系接警记详情录开始==============");
		SccAnswerAlarm sccAnswerAlarm = this.getById(id);
		SccAnswerAlarmVO sccAnswerAlarmVO = Func.copy(sccAnswerAlarm, SccAnswerAlarmVO.class);
		sccAnswerAlarmVO.setPlaceName(Func.isNotEmpty(sccAnswerAlarm.getPlace()) ? departmentService.getById(sccAnswerAlarm.getPlace()).getDeptName() : null);
		//获取相关附件
		List<UploadVO> attachments = fileService.getAttachments(id, sccAnswerAlarm.getGroupName());
		sccAnswerAlarmVO.setRelevantAttachments(attachments);
		log.info("==============获取联系接警记详情录结束==============");
		return sccAnswerAlarmVO;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveData(SccAnswerAlarmDTO sccAnswerAlarmDTO) {
		log.info("==============新增/编辑联系接警记详情录开始==============");
		//联系记录保存
		SccAnswerAlarm sccAnswerAlarm = Func.copy(sccAnswerAlarmDTO, SccAnswerAlarm.class);
		sccAnswerAlarm.setDeptId(AuthUtil.getDeptId());
		sccAnswerAlarm.setDeptName(iInspectionService.getDeptData(AuthUtil.getDeptId()));
		sccAnswerAlarm.setAlarmType(Func.isNotEmpty(sccAnswerAlarm.getAlarmType()) ? sccAnswerAlarm.getAlarmType() : Constant.ALARM_TYPE_OTHER);
		sccAnswerAlarm.setPushState(Constant.PUSH_STATE_ONE.equals(sccAnswerAlarmDTO.getSubmitType()) ? Constant.PUSH_STATE_ZERO : sccAnswerAlarmDTO.getSubmitType());
		sccAnswerAlarm.setState(Constant.PUSH_STATE_ONE.equals(sccAnswerAlarmDTO.getSubmitType()) ? Constant.HANDIN_STATE_AUDIT : Constant.HANDIN_STATE_DRAFT);
		boolean b;
		if (Func.isNotEmpty(sccAnswerAlarmDTO.getId())) {
			b = this.update(sccAnswerAlarm, new UpdateWrapper<SccAnswerAlarm>().lambda().eq(SccAnswerAlarm::getId, sccAnswerAlarmDTO.getId()).eq(SccAnswerAlarm::getPushState, Constant.PUSH_STATE_ZERO));
		} else {
			b = this.save(sccAnswerAlarm);
		}
		//保存相关附件
		if (b) {
			fileService.saveAttachments(sccAnswerAlarmDTO.getRelevantAttachments(), sccAnswerAlarm.getId());
		}
		log.info("==============新增/编辑联系接警记详情录结束==============");
		//判断是否进行警情推送
		if (sccAnswerAlarmDTO.getSubmitType().equals(Constant.SUBMIT_TYPE_ONE)) {
			// sccAlarmPushService.senAlarmNotice(sccAnswerAlarm);
			return startProcess(sccAnswerAlarm);
		}
		return true;
	}

	public boolean startProcess(SccAnswerAlarm sccAnswerAlarm) {
		R<BladeFlowDef> definitionRes = flowClient.getLatestProcessDefinitionByKey(ProcessConstant.SCC_ANSWER_ALARM_KEY);
		if (definitionRes.isSuccess()) {
			sccAnswerAlarm.setProcessDefinitionId(definitionRes.getData().getId());
		} else {
			throw new ServiceException("开启流程失败");
		}
		R<Integer> deptCategory = sysClient.getDeptCategory(Long.valueOf(AuthUtil.getUser().getDeptId()));
		if (!deptCategory.isSuccess()) {
			throw new ServiceException("查询部门类型失败，请检查后再试！");
		}
		Kv variables = Kv.create()
			.set(ProcessConstant.BUSINESS_ID_KEY, sccAnswerAlarm.getId())
			.set("deptCategory", deptCategory.getData())
			.set(ProcessConstant.START_PROC_USER_ID, AuthUtil.getUserId());
		String businessTable = FlowUtil.getBusinessTable(SccAlarmPush.class);
		R<BladeFlow> result = flowClient.startProcessInstanceById(sccAnswerAlarm.getProcessDefinitionId(), FlowUtil.getBusinessKey(businessTable, String.valueOf(sccAnswerAlarm.getId())), variables);
		if (result.isSuccess()) {
			log.debug("流程已启动,流程ID:" + result.getData().getProcessInstanceId());
			sccAnswerAlarm.setProcessInstanceId(result.getData().getProcessInstanceId());
		} else {
			throw new ServiceException("开启流程失败");
		}
		this.saveOrUpdate(sccAnswerAlarm);
		return true;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean removeData(List<String> toLongList) {
		log.info("==============删除联系接警记详情录开始==============");
		//删除联系记录
		//删除相关附件
		boolean b = this.removeByIds(toLongList);
		boolean b1 = fileService.removeFileData(toLongList);
		log.info("==============删除联系接警记详情录结束==============");
		return b && b1;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R handIn(SccAlarmPushDTO sccAlarmPushDTO) {
		log.info("==============警情信息提报开始==============");
		SccAlarmPush alarmPush = Func.copy(sccAlarmPushDTO, SccAlarmPush.class);
		alarmPush.setPushState(Constant.PUSH_STATE_TWO);
		alarmPush.setStatus(Constant.PUSH_STATUS_ONE);
		alarmPush.setState(Constant.HANDIN_STATE_AUDIT);
		boolean b = sccAlarmPushService.update(alarmPush, new UpdateWrapper<SccAlarmPush>().lambda()
			.eq(Func.isNotEmpty(sccAlarmPushDTO.getId()), SccAlarmPush::getId, sccAlarmPushDTO.getId())
			.eq(SccAlarmPush::getPushState, Constant.PUSH_STATE_ONE)
			.or().eq(Func.isNotEmpty(sccAlarmPushDTO.getId()), SccAlarmPush::getId, sccAlarmPushDTO.getId())
			.eq(SccAlarmPush::getState, Constant.HANDIN_STATE_REFUSE)
			.eq(Func.isNotEmpty(sccAlarmPushDTO.getId()), SccAlarmPush::getId, sccAlarmPushDTO.getId())
			.eq(SccAlarmPush::getPushState, Constant.PUSH_STATE_TWO)
			.or().eq(Func.isNotEmpty(sccAlarmPushDTO.getId()), SccAlarmPush::getId, sccAlarmPushDTO.getId())
			.eq(SccAlarmPush::getState, ProcessConstant.CANCEL_STATE)
			.eq(Func.isNotEmpty(sccAlarmPushDTO.getId()), SccAlarmPush::getId, sccAlarmPushDTO.getId())
			.eq(SccAlarmPush::getPushState, Constant.PUSH_STATE_TWO));
		if (!b) {
			return R.fail(400, "该警情信息已经被提报，请勿重复提报");
		}
		//更新附件和处理情况信息更新
		if (Func.isNotEmpty(sccAlarmPushDTO.getLinkId())) {
			fileService.saveAttachments(sccAlarmPushDTO.getRelevantAttachments(), sccAlarmPushDTO.getLinkId());
			SccAnswerAlarm answerAlarm = this.getById(sccAlarmPushDTO.getLinkId());
			answerAlarm.setTreatment(sccAlarmPushDTO.getTreatment());
			answerAlarm.setRemark(sccAlarmPushDTO.getRemark());
			this.updateById(answerAlarm);
		} else {
			fileService.saveAttachments(sccAlarmPushDTO.getRelevantAttachments(), sccAlarmPushDTO.getId());
		}

		R<BladeFlowDef> definitionRes = flowClient.getLatestProcessDefinitionByKey(ProcessConstant.SCC_ALARM_PUSH_KEY);
		if (definitionRes.isSuccess()) {
			alarmPush.setProcessDefinitionId(definitionRes.getData().getId());
		} else {
			throw new ServiceException("开启流程失败");
		}
		R<Integer> deptCategory = sysClient.getDeptCategory(Long.valueOf(AuthUtil.getUser().getDeptId()));
		R<Integer> sendDeptCategory = sysClient.getDeptCategory(Long.valueOf(sccAlarmPushDTO.getDeptId()));
		if (!deptCategory.isSuccess()) {
			throw new ServiceException("查询部门类型失败，请检查后再试！");
		}
		Kv variables = Kv.create()
			.set(ProcessConstant.BUSINESS_ID_KEY, alarmPush.getId())
			.set("deptCategory", deptCategory.getData())
			.set("sendDeptCategory", sendDeptCategory.getData()) //警情推送方的机构类型： 总、分、支
			.set(ProcessConstant.START_PROC_USER_ID, AuthUtil.getUserId());
		String businessTable = FlowUtil.getBusinessTable(SccAlarmPush.class);
		R<BladeFlow> result = flowClient.startProcessInstanceById(alarmPush.getProcessDefinitionId(), FlowUtil.getBusinessKey(businessTable, String.valueOf(alarmPush.getId())), variables);
		if (result.isSuccess()) {
			log.debug("流程已启动,流程ID:" + result.getData().getProcessInstanceId());
			alarmPush.setProcessInstanceId(result.getData().getProcessInstanceId());
		} else {
			throw new ServiceException("开启流程失败");
		}

		sccAlarmPushService.saveOrUpdate(alarmPush);

		log.info("==============警情信息提报结束==============");
		return R.success("警情信息提报成功");
	}

	@Override
	public List<AnswerAlarmDataVO> getAimStatisticsData(AnswerAlarmDataDTO answerAlarmDataDTO, List<String> aimDepts) {
		return baseMapper.getAimStatisticsData(answerAlarmDataDTO,aimDepts);
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public R afterFlowFinished(String id, Boolean pass, Map<String, Object> variables) {
		Boolean result = false;
		String state;
		if (null == pass) {
			state = ProcessConstant.CANCEL_STATE;
		} else if (pass) {
			state = ProcessConstant.PASS_STATE;
		} else {
			state = ProcessConstant.REJECT_STATE;
		}
		result = this.updateStateById(id, state);
		//审批通过
		if (result && Func.isNotEmpty(pass) && pass){
			SccAnswerAlarm sccAnswerAlarm = this.getById(id);
			sccAnswerAlarm.setPushState(Constant.PUSH_STATE_ONE);
			this.updateById(sccAnswerAlarm);
		}
		return R.success("执行成功");
	}

}
