/*
 *      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.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.security.common.Constant;
import org.security.common.config.CommonProperties;
import org.security.common.util.DataFormatUtil;
import org.security.common.util.DocumentNumberUtil;
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.trans.dailyDuties.service.IInspectionService;
import org.security.trans.dataStatistics.dto.StatisticsDataDTO;
import org.security.trans.dataStatistics.vo.RectificationNoticeDataVO;
import org.security.trans.securityCommandCenter.dto.ContinuedRecDataDTO;
import org.security.trans.securityCommandCenter.dto.SccUnlocaleCheckDTO;
import org.security.trans.securityCommandCenter.dto.SccUnlocaleCheckLineDTO;
import org.security.trans.securityCommandCenter.entity.SccCheck;
import org.security.trans.securityCommandCenter.entity.SccCheckLines;
import org.security.trans.securityCommandCenter.entity.SccUnlocaleCheck;
import org.security.trans.securityCommandCenter.entity.SccUnlocaleCheckLine;
import org.security.trans.securityCommandCenter.service.ISccUnlocaleCheckLineService;
import org.security.trans.securityCommandCenter.vo.ContinuedRecDataVO;
import org.security.trans.securityCommandCenter.vo.SccUnlocaleCheckLineVO;
import org.security.trans.securityCommandCenter.vo.SccUnlocaleCheckVO;
import org.security.trans.securityCommandCenter.mapper.SccUnlocaleCheckMapper;
import org.security.trans.securityCommandCenter.service.ISccUnlocaleCheckService;
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.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 安保指挥中心-非现场检查整改通知书 服务实现类
 *
 * @author BladeX
 * @since 2022-07-06
 */
@Slf4j
@Service
@AllArgsConstructor
public class SccUnlocaleCheckServiceImpl extends ServiceImpl<SccUnlocaleCheckMapper, SccUnlocaleCheck> implements ISccUnlocaleCheckService {
	private final IDepartmentService departmentService;
	private final ISccUnlocaleCheckLineService sccUnlocaleCheckLineService;
	private final IFileService fileService;
	private final CommonProperties commonProperties;
	private final ISysClient sysClient;
	private final IFlowClient flowClient;
	private final IInspectionService iInspectionService;

	@Override
	public IPage<SccUnlocaleCheckVO> selectSccUnlocaleCheckPage(IPage<SccUnlocaleCheckVO> page, SccUnlocaleCheckDTO sccUnlocaleCheckDTO) {
		List<SccUnlocaleCheckVO> unlocaleCheckList = new ArrayList<>();
		//获取非现场检查整改下发任务列表页数据
		if (Constant.SUBMIT_TYPE_ZERO.equals(sccUnlocaleCheckDTO.getMenuType())) {
			unlocaleCheckList = baseMapper.selectGiveUpData(page, sccUnlocaleCheckDTO);
			if (Func.isNotEmpty(unlocaleCheckList)) {
				log.info("==============获取非现场检查整改下发任务列表页数据开始==============");
				unlocaleCheckList.forEach(item -> {
					//暂存数据
					if (Constant.PROBLEM_STATE_ZORE.equals(item.getStatus()) && String.valueOf(AuthUtil.getUserId()).equals(item.getInspectStaff())) {
						item.setButtonStatus(Constant.BUTTON_STATE_ZERO);
					} else {
						item.setButtonStatus(Constant.BUTTON_STATE_THREE);
					}
				});
				log.info("==============获取非现场检查整改下发任务列表页数据结束==============");
			}
		}
		//获取非现场检查整改上报任务列表页数据
		if (Constant.SUBMIT_TYPE_ONE.equals(sccUnlocaleCheckDTO.getMenuType())) {
			log.info("==============获取非现场检查整改上报任务列表页数据开始==============");
			unlocaleCheckList = baseMapper.selectHandInData(page, sccUnlocaleCheckDTO);
			if (Func.isNotEmpty(unlocaleCheckList)){
				unlocaleCheckList.forEach(item ->{
					item.setInspectDeptName(departmentService.getById(item.getInspectDept()).getDeptName());
					item.setButtonStatus(Constant.BUTTON_STATE_THREE);
					if ((item.getRectificationResponsiblePerson().contains(String.valueOf(AuthUtil.getUser().getUserId()))
						&& item.getStatus().equals(Constant.PROBLEM_STATE_DRAFT_ONE))
						||(item.getRectificationResponsiblePerson().contains(String.valueOf(AuthUtil.getUser().getUserId()))
						&& (Constant.HANDIN_STATE_REFUSE.equals(item.getState())
						|| ProcessConstant.CANCEL_STATE.equals(item.getState())))){
						item.setButtonStatus(Constant.BUTTON_STATE_ONE);
					}
				});
			}
			log.info("==============获取非现场检查整改上报任务列表页数据结束==============");
		}
		//处理检查机构、检查人
		unlocaleCheckList.forEach(this::setUserAndDeptName);
		List<SccUnlocaleCheckVO> vos = unlocaleCheckList.stream().sorted(Comparator.comparing(SccUnlocaleCheckVO::getUpdatedTime,Comparator.nullsLast(Comparator.reverseOrder()))).collect(Collectors.toList());
		return page.setRecords(vos);
	}

	//处理检查机构、检查人
	private void setUserAndDeptName(SccUnlocaleCheckVO item) {
		item.setInspectDept(departmentService.getById(item.getInspectDept()).getDeptName());
		String userName = baseMapper.getUserName(item.getInspectStaff());
		item.setInspectStaff(Func.isNotEmpty(userName) ? userName : item.getInspectStaff());
		item.setInspectedDept(departmentService.getById(item.getInspectedDept()).getDeptName());
		item.setRectificationResponsiblePerson(Func.isNotEmpty(item.getRectificationResponsiblePerson()) ? baseMapper.getUserName(item.getRectificationResponsiblePerson()) : "");
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveData(SccUnlocaleCheckDTO sccUnlocaleCheckDTO) {
		log.info("==============创建非现场检查整改通知书==============");
		SccUnlocaleCheck unlocaleCheck = Func.copy(sccUnlocaleCheckDTO, SccUnlocaleCheck.class);
		unlocaleCheck.setInspectDept(AuthUtil.getDeptId());
		unlocaleCheck.setInspectStaff(String.valueOf(AuthUtil.getUser().getUserId()));
		unlocaleCheck.setDeptId(AuthUtil.getDeptId());
		unlocaleCheck.setDeptName(iInspectionService.getDeptData(AuthUtil.getDeptId()));
		//生成文号
		unlocaleCheck.setDocumentNo(DocumentNumberUtil.createdDocumentNumber());
		log.info("整改通知书文号生成【】" + unlocaleCheck.getDocumentNo());
		//暂存---暂存    提交-----待下发
		unlocaleCheck.setStatus(Constant.SUBMIT_TYPE_ZERO.equals(sccUnlocaleCheckDTO.getSubmitType()) ? Constant.PROBLEM_STATE_ZORE : Constant.PROBLEM_STATE_DRAFT_ONE);
		unlocaleCheck.setState(Constant.HANDIN_STATE_DRAFT);
		//主表记录保存/更新
		if (Func.isNotEmpty(sccUnlocaleCheckDTO.getId())) {
			this.update(unlocaleCheck,new UpdateWrapper<SccUnlocaleCheck>().lambda()
				.eq(SccUnlocaleCheck::getId,sccUnlocaleCheckDTO.getId()).eq(SccUnlocaleCheck::getStatus,Constant.PROBLEM_STATE_DRAFT));
		}else {
			this.saveOrUpdate(unlocaleCheck);
		}
		//保存整改通知书相关附件
		fileService.saveAttachments(sccUnlocaleCheckDTO.getRelevantAttachments(),unlocaleCheck.getId());
		//整改明细记录保存
		if (Func.isNotEmpty(sccUnlocaleCheckDTO.getSccUnlocaleCheckLineDTOList())) {
			List<SccUnlocaleCheckLine> unlocaleCheckLines = Func.copy(sccUnlocaleCheckDTO.getSccUnlocaleCheckLineDTOList(), SccUnlocaleCheckLine.class);
			unlocaleCheckLines.forEach(item -> {
				item.setFormId(unlocaleCheck.getId());
				item.setRecFlag(Constant.PROBLEM_STATE_USUUAL);
				item.setStatus(Constant.PROBLEM_STATE_DRAFT_ONE);
				item.setState(Constant.HANDIN_STATE_DRAFT);
				item.setDeptId(AuthUtil.getDeptId());
				item.setOutletsName(departmentService.getById(item.getOutletsCode()).getDeptName());
			});
			sccUnlocaleCheckLineService.saveOrUpdateBatch(unlocaleCheckLines);
		}
		//前端点击了下发整改通知书，则将该记录挂载到流程上，该记录现在的状态是待下发，若审批通过回调变更该记录状态为待整改
		if (Constant.PROBLEM_STATE_SIX.equals(unlocaleCheck.getStatus())){
			//TODO 挂在流程
		}
		log.info("==============非现场检查整改通知书创建完成==============");
		return true;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean handInData(SccUnlocaleCheckDTO sccUnlocaleCheckDTO) throws ParseException {
		log.info("==============整改通知书提报开始==============");
		//暂存
		if (Constant.SUBMIT_TYPE_ZERO.equals(sccUnlocaleCheckDTO.getSubmitType())) {
			return true;
		}
		//提报非现场检查整改结果
		if (Constant.SUBMIT_TYPE_ONE.equals(sccUnlocaleCheckDTO.getSubmitType())) {
			//更新主表状态
			SccUnlocaleCheck unlocaleCheck = Func.copy(sccUnlocaleCheckDTO, SccUnlocaleCheck.class);
			//超时整改
			if (unlocaleCheck.getRectificationDeadline().before(DataFormatUtil.getLocalDate())) {
				unlocaleCheck.setStatus(Constant.PROBLEM_STATE_THREE);
			}//按时整改
			else {
				unlocaleCheck.setStatus(Constant.PROBLEM_STATE_WAIT_TWO);
			}
			unlocaleCheck.setState(Constant.HANDIN_STATE_AUDIT);
			//更新主表状态
			updateById(unlocaleCheck);
			//更新检查整改明细
			updateData(sccUnlocaleCheckDTO,unlocaleCheck.getState());
			//开启流程
			startFlow(unlocaleCheck);
		}
		log.info("==============整改通知书提报结束==============");
		return true;
	}

	/**
	 * 开启流程
	 */
	private void startFlow(SccUnlocaleCheck unlocaleCheck) {
		R<BladeFlowDef> definitionRes = flowClient.getLatestProcessDefinitionByKey(ProcessConstant.SCC_UNLOCAL_CHECK_KEY);
		if (definitionRes.isSuccess()) {
			unlocaleCheck.setProcessDefinitionId(definitionRes.getData().getId());
		} else {
			throw new ServiceException("开启流程失败");
		}
		String businessTable = FlowUtil.getBusinessTable(SccUnlocaleCheck.class);
		R<Integer> deptCategory = sysClient.getDeptCategory(Long.valueOf(AuthUtil.getUser().getDeptId()));
		if (!deptCategory.isSuccess()) {
			throw new ServiceException("查询部门类型失败，请检查后再试！");
		}
		R<Integer> sendDeptCategory = sysClient.getDeptCategory(Long.valueOf(unlocaleCheck.getDeptId()));
		if (!sendDeptCategory.isSuccess()) {
			throw new ServiceException("查询推送部门类型失败，请检查后再试！");
		}
		Kv variables = Kv.create()
			.set("deptCategory", deptCategory.getData())
			.set("sendDeptCategory", sendDeptCategory.getData())
			.set(ProcessConstant.BUSINESS_ID_KEY, unlocaleCheck.getId())
			.set(ProcessConstant.START_PROC_USER_ID, AuthUtil.getUserId());
		R<BladeFlow> result = flowClient.startProcessInstanceById(unlocaleCheck.getProcessDefinitionId(), FlowUtil.getBusinessKey(businessTable, String.valueOf(unlocaleCheck.getId())), variables);
		if (result.isSuccess()) {
			log.debug("流程已启动,流程ID:" + result.getData().getProcessInstanceId());
			unlocaleCheck.setProcessInstanceId(result.getData().getProcessInstanceId());
		} else {
			throw new ServiceException("开启流程失败");
		}
		updateById(unlocaleCheck);
	}

	@Override
	public SccUnlocaleCheckVO getData(String id) {
		log.info("==============获取整改通知书详情开始==============");
		//获取主表记录
		SccUnlocaleCheck sccUnlocaleCheck = this.getById(id);
		SccUnlocaleCheckVO sccUnlocaleCheckVO = Func.copy(sccUnlocaleCheck, SccUnlocaleCheckVO.class);
		sccUnlocaleCheckVO.setInspectStaffName(Func.isNotEmpty(sccUnlocaleCheck.getLinkId()) ? sccUnlocaleCheck.getInspectStaff() : baseMapper.getUserName(sccUnlocaleCheck.getInspectStaff()));
		//获取检查整改通知书相关附件
		sccUnlocaleCheckVO.setRelevantAttachments(fileService.getAttachments(sccUnlocaleCheck.getId(),sccUnlocaleCheck.getGroupName()));
		//获取明细记录
		List<SccUnlocaleCheckLine> list = sccUnlocaleCheckLineService.list(new QueryWrapper<SccUnlocaleCheckLine>().lambda()
			.eq(Func.isNotBlank(id), SccUnlocaleCheckLine::getFormId, id)
			.eq(SccUnlocaleCheckLine::getDelFlag,Constant.DELETE_FLAG_0)
			.ne(SccUnlocaleCheckLine::getStatus,Constant.PROBLEM_STATE_SIX)
		);
		if (Func.isNotEmpty(list)) {
			List<SccUnlocaleCheckLineVO> sccUnlocaleCheckLineVOList = Func.copy(list, SccUnlocaleCheckLineVO.class);
			sccUnlocaleCheckLineVOList.forEach(item -> {
				//获取附件信息
				item.setRelevantAttachments(fileService.getAttachments(item.getId(),item.getGroupName()));
			});
			sccUnlocaleCheckVO.setInspectDeptName(departmentService.getById(sccUnlocaleCheckVO.getInspectDept()).getDeptName());
			//检查日志记录产生的非现场检查整改通知书，被检查单位名称赋值
			sccUnlocaleCheckVO.setInspectedDeptName(departmentService.getById(sccUnlocaleCheckVO.getInspectedDept()).getDeptName());
			sccUnlocaleCheckVO.setSccUnlocaleCheckLineVOList(sccUnlocaleCheckLineVOList);
		}
		log.info("==============获取整改通知书详情结束==============");
		return sccUnlocaleCheckVO;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean removeData(List<Long> toLongList) {
		log.info("==============删除检查整改通知书开始==============");
		//删除主表记录
		//删除明细信息
		//删除相关附件
		List<String> detailIdList = new ArrayList<>();
		toLongList.forEach(item -> {
			List<SccUnlocaleCheckLine> list = sccUnlocaleCheckLineService.list(new QueryWrapper<SccUnlocaleCheckLine>().lambda().eq(Func.isNotEmpty(item), SccUnlocaleCheckLine::getFormId, item));
			if (Func.isNotEmpty(list)) {
				list.forEach(d -> {
					detailIdList.add(d.getId());
				});
			}
		});
		boolean b = this.removeByIds(toLongList);
		boolean b1 = sccUnlocaleCheckLineService.removeByIds(detailIdList);
		boolean b2 = fileService.removeFileData(detailIdList);
		log.info("==============删除检查整改通知书结束==============");
		return b && b1 && b2;
	}

	@Override
	public boolean startRectedNotice(SccCheck sccCheck, List<SccCheckLines> collect) {
		log.info("==============创建检查整改通知书开始==============");
		//创建检查整改通知书
		collect.forEach(item -> {
			//保存主表记录
			SccUnlocaleCheck unlocaleCheck = null;
			try {
				unlocaleCheck = saveSccUnlocaleCheck(sccCheck, item);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			this.save(unlocaleCheck);
			//保存明细表记录
			SccUnlocaleCheckLine sccUnlocaleCheckLine = saveSccUnlocaleCheckLine(item, unlocaleCheck);
			sccUnlocaleCheckLineService.save(sccUnlocaleCheckLine);
		});
		log.info("==============检查整改通知书创建完成==============");
		return true;
	}

	@Override
	public IPage<ContinuedRecDataVO> getContinuedPage(IPage<ContinuedRecDataVO> page, ContinuedRecDataDTO continuedRecDataDTO) {
		ArrayList<ContinuedRecDataVO> vos = new ArrayList<>();
		List<SccUnlocaleCheckLine> list = sccUnlocaleCheckLineService.getContinuedPage(page,continuedRecDataDTO);
		if (Func.isNotEmpty(list)){
			list.forEach(item ->{
				//获取主表信息
				SccUnlocaleCheck unlocaleCheck = this.getById(item.getFormId());
				ContinuedRecDataVO continuedRecDataVO = Func.copy(unlocaleCheck, ContinuedRecDataVO.class);
				continuedRecDataVO.setId(item.getId());
				continuedRecDataVO.setInspectDept(departmentService.getById(unlocaleCheck.getInspectDept()).getDeptName());
				continuedRecDataVO.setInspectStaff(Func.isNotEmpty(unlocaleCheck.getLinkId())? unlocaleCheck.getInspectStaff() : baseMapper.getUserName(unlocaleCheck.getInspectStaff()));
				continuedRecDataVO.setInspectedDept(departmentService.getById(unlocaleCheck.getInspectedDept()).getDeptName());
				continuedRecDataVO.setRectificationResponsiblePerson(Func.isNotEmpty(unlocaleCheck.getRectificationResponsiblePerson()) ? baseMapper.getUserName(unlocaleCheck.getRectificationResponsiblePerson()) : "");
				continuedRecDataVO.setRectificationDeadline(item.getRectificationDeadline());
				continuedRecDataVO.setStatus(item.getStatus());
				continuedRecDataVO.setState(item.getState());
				vos.add(continuedRecDataVO);
			});
		}
		return page.setRecords(vos);
	}

	@Override
	public SccUnlocaleCheckLineVO getContinuedDetail(String id) {
		SccUnlocaleCheckLine sccUnlocaleCheckLine = sccUnlocaleCheckLineService.getById(id);
		SccUnlocaleCheckLineVO vo = Func.copy(sccUnlocaleCheckLine, SccUnlocaleCheckLineVO.class);
		//获取相关附件
		vo.setRelevantAttachments(fileService.getAttachments(sccUnlocaleCheckLine.getId(),sccUnlocaleCheckLine.getGroupName()));
		return vo;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean handInContinuedRec(SccUnlocaleCheckLineDTO sccUnlocaleCheckLineDTO) throws ParseException {
		SccUnlocaleCheckLine unlocaleCheckLine = Func.copy(sccUnlocaleCheckLineDTO,SccUnlocaleCheckLine.class);
		//针对于持续整改记录，再次发起持续整改
		if (Constant.PROBLEM_STATE_CONTINUED.equals(sccUnlocaleCheckLineDTO.getRecordFlag())){
			//新增持续整改记录
			unlocaleCheckLine.setId(null);
			unlocaleCheckLine.setStatus(Constant.PROBLEM_STATE_SIX);
			unlocaleCheckLine.setState(Constant.HANDIN_STATE_DRAFT);
			unlocaleCheckLine.setDeptId(AuthUtil.getDeptId());
			sccUnlocaleCheckLineService.save(unlocaleCheckLine);
			//保存相关附件
			fileService.saveAttachments(sccUnlocaleCheckLineDTO.getRelevantAttachments(),unlocaleCheckLine.getId());
			//并且删除原明细记录
			sccUnlocaleCheckLineService.removeById(sccUnlocaleCheckLineDTO.getId());
		}
		//提报持续整改记录
		Date deadline = Func.isNotEmpty(sccUnlocaleCheckLineDTO.getRectificationDeadline()) ? sccUnlocaleCheckLineDTO.getRectificationDeadline() : sccUnlocaleCheckLineService.getById(sccUnlocaleCheckLineDTO.getId()).getRectificationDeadline();
		if (deadline.before(DataFormatUtil.getLocalDate())){
			unlocaleCheckLine.setStatus(Constant.PROBLEM_STATE_THREE);
		}else {
			unlocaleCheckLine.setStatus(Constant.PROBLEM_STATE_WAIT_TWO);
		}
		unlocaleCheckLine.setState(Constant.HANDIN_STATE_AUDIT);
		sccUnlocaleCheckLineService.saveOrUpdate(unlocaleCheckLine);
		//保存相关附件
		fileService.saveAttachments(sccUnlocaleCheckLineDTO.getRelevantAttachments(),unlocaleCheckLine.getId());
		R lineRes = sccUnlocaleCheckLineService.startProcess(unlocaleCheckLine, unlocaleCheckLine.getDeptId());
		if (!lineRes.isSuccess()) {
			return false;
		}
		return true;
	}

	@Override
	public List<SccUnlocaleCheck> getListData(String status) {
		return this.list(new QueryWrapper<SccUnlocaleCheck>().lambda().eq(Func.isNotEmpty(status),SccUnlocaleCheck::getStatus,status).eq(SccUnlocaleCheck::getDelFlag,Constant.DELETE_FLAG_0));
	}

	@Override
	public List<RectificationNoticeDataVO> getStatisticsData(StatisticsDataDTO statisticsDataDTO, List<String> aimDepts) {
		return baseMapper.getStatisticsData(statisticsDataDTO,aimDepts);
	}

	/**
	 *封装检查整改通知书明细表
	 */
	private SccUnlocaleCheckLine saveSccUnlocaleCheckLine(SccCheckLines item, SccUnlocaleCheck unlocaleCheck) {
		SccUnlocaleCheckLine sccUnlocaleCheckLine = new SccUnlocaleCheckLine();
		sccUnlocaleCheckLine.setFormId(unlocaleCheck.getId());
		sccUnlocaleCheckLine.setRecFlag(Constant.PROBLEM_STATE_USUUAL);
		sccUnlocaleCheckLine.setStatus(Constant.PROBLEM_STATE_DRAFT_ONE);
		sccUnlocaleCheckLine.setOutletsCode(item.getOutletsCode());
		sccUnlocaleCheckLine.setOutletsName(departmentService.getById(item.getOutletsCode()).getDeptName());
		sccUnlocaleCheckLine.setDiscoverProblemsTime(item.getCheckTime());
		sccUnlocaleCheckLine.setProblemsDescribe(item.getAbnormalConditions());
		sccUnlocaleCheckLine.setOutletsCodeFront(item.getOutletsCodeFront());
		return sccUnlocaleCheckLine;
	}

	/**
	 *封装检查整改通知书主表数据
	 */
	private SccUnlocaleCheck saveSccUnlocaleCheck(SccCheck sccCheck, SccCheckLines item) throws ParseException {
		SccUnlocaleCheck unlocaleCheck = new SccUnlocaleCheck();
		unlocaleCheck.setDocumentNo(DocumentNumberUtil.createdDocumentNumber());
		unlocaleCheck.setInspectDept(AuthUtil.getDeptId());
		unlocaleCheck.setInspectStaff(sccCheck.getPersonOnDuty());
		unlocaleCheck.setDeptId(AuthUtil.getDeptId());
		unlocaleCheck.setRectificationDeadline(DataFormatUtil.getLocalDate());
		unlocaleCheck.setDeptName(departmentService.getById(unlocaleCheck.getDeptId()).getDeptName());
		unlocaleCheck.setLinkId(item.getId());
		//待下发状态的整改通知书，审批通过后变成待整改
		unlocaleCheck.setStatus(Constant.PROBLEM_STATE_DRAFT_ONE);
		unlocaleCheck.setState(Constant.HANDIN_STATE_DRAFT);
		//营业网点检查
		if (Constant.CHECK_TYPE_OUTLETS.equals(sccCheck.getCheckType())){
			unlocaleCheck.setInspectedDept(item.getOutletsCode());
			unlocaleCheck.setNoticeType(Constant.NOTICE_TYPE_ONE);
		}
		//自助银行检查
		if (Constant.CHECK_TYPE_SELF_BANK.equals(sccCheck.getCheckType())){
			//获取自助银行的直属营业机构
			unlocaleCheck.setInspectedDept(baseMapper.getDeptId(item.getOutletsCode()));
			unlocaleCheck.setNoticeType(Constant.NOTICE_TYPE_TWO);
		}
		//根据机构号和角色名称获取责任整改人（整改机构的安全员）
		List<String> dutyPerson = baseMapper.getDutyPerson(unlocaleCheck.getInspectedDept(),commonProperties.getSecurityRoleName());
		unlocaleCheck.setRectificationResponsiblePerson(dutyPerson.size() > 0 ? StringUtils.join(dutyPerson,",") : null);


		return unlocaleCheck;
	}

	/**
	 * 更新检查整改明细
	 */
	private void updateData(SccUnlocaleCheckDTO sccUnlocaleCheckDTO,String state) {
		if (Func.isNotEmpty(sccUnlocaleCheckDTO.getSccUnlocaleCheckLineDTOList())) {
			sccUnlocaleCheckDTO.getSccUnlocaleCheckLineDTOList().forEach(item -> {
				SccUnlocaleCheckLine unlocaleCheckLine = Func.copy(item, SccUnlocaleCheckLine.class);
				//持续整改
				if (Constant.PROBLEM_STATE_CONTINUED.equals(item.getRecordFlag()) && !Constant.HANDIN_STATE_REFUSE.equals(state)){
					//更新原有记录
					unlocaleCheckLine.setStatus(Constant.PROBLEM_STATE_DRAFT_ONE);
					unlocaleCheckLine.setRecFlag(Constant.PROBLEM_STATE_USUUAL);
					sccUnlocaleCheckLineService.updateById(unlocaleCheckLine);
					//保存相关附件
					fileService.saveAttachments(item.getRelevantAttachments(), unlocaleCheckLine.getId());
					//新增持续整改记录
					SccUnlocaleCheckLine recCheckLine = new SccUnlocaleCheckLine();
					recCheckLine.setRecFlag(Constant.PROBLEM_STATE_CONTINUED);
					recCheckLine.setStatus(Constant.PROBLEM_STATE_SIX);
					recCheckLine.setState(Constant.HANDIN_STATE_DRAFT);
					recCheckLine.setDeptId(item.getDeptId());
					recCheckLine.setRectificationDeadline(item.getRectificationDeadline());
					recCheckLine.setFormId(item.getFormId());
					recCheckLine.setProblemsDescribe(item.getProblemsDescribe());
					recCheckLine.setDiscoverProblemsTime(item.getDiscoverProblemsTime());
					recCheckLine.setOutletsCode(item.getOutletsCode());
					recCheckLine.setOutletsCodeFront(item.getOutletsCodeFront());
					recCheckLine.setOutletsName(item.getOutletsName());
					sccUnlocaleCheckLineService.save(recCheckLine);
					//保存相关附件
					fileService.saveAttachments(item.getRelevantAttachments(), recCheckLine.getId());
				}
				else {
					sccUnlocaleCheckLineService.updateById(unlocaleCheckLine);
					//保存相关附件
					fileService.saveAttachments(item.getRelevantAttachments(), unlocaleCheckLine.getId());
				}
			});
		}
	}

	@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) {
			List<SccUnlocaleCheckLine> unlocaleCheckLines = sccUnlocaleCheckLineService.list(new QueryWrapper<SccUnlocaleCheckLine>().lambda()
				.eq(Func.isNotEmpty(id), SccUnlocaleCheckLine::getFormId, id)
				.eq(SccUnlocaleCheckLine::getDelFlag, Constant.DELETE_FLAG_0));
			if (Func.isNotEmpty(unlocaleCheckLines)) {
				//筛选出持续整改记录明细
				List<String> collect = unlocaleCheckLines.stream().filter(item -> Constant.PROBLEM_STATE_CONTINUED.equals(item.getRecFlag()) && Constant.PROBLEM_STATE_SIX.equals(item.getStatus())).map(SccUnlocaleCheckLine::getId).collect(Collectors.toList());
				if (Func.isNotEmpty(collect)) {
					if (Func.isNotEmpty(pass) && pass) {
						result = sccUnlocaleCheckLineService.update(new UpdateWrapper<SccUnlocaleCheckLine>().lambda().set(SccUnlocaleCheckLine::getStatus, Constant.PROBLEM_STATE_DRAFT_ONE).in(SccUnlocaleCheckLine::getId, collect));
					} else {
						result = sccUnlocaleCheckLineService.removeByIds(collect);
					}
					if (!result){
						log.error("审批更新业务表单失败");
						return R.fail("审批更新业务表单失败");
					}
				}
			}
		}
		return R.success("执行成功");
	}
}
