/*
 *      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.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.AllArgsConstructor;
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.common.service.IFileService;
import org.security.trans.securityCommandCenter.dto.ContinuedRecDataDTO;
import org.security.trans.securityCommandCenter.dto.SccUnlocaleCheckLineDTO;
import org.security.trans.securityCommandCenter.entity.SccUnlocaleCheck;
import org.security.trans.securityCommandCenter.entity.SccUnlocaleCheckLine;
import org.security.trans.securityCommandCenter.vo.ContinuedRecDataVO;
import org.security.trans.securityCommandCenter.vo.SccUnlocaleCheckLineVO;
import org.security.trans.securityCommandCenter.mapper.SccUnlocaleCheckLineMapper;
import org.security.trans.securityCommandCenter.service.ISccUnlocaleCheckLineService;
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.support.Kv;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.api.R;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 安保指挥中心-非现场检查整改明细 服务实现类
 *
 * @author BladeX
 * @since 2022-07-06
 */
@Service
@AllArgsConstructor
public class SccUnlocaleCheckLineServiceImpl extends ServiceImpl<SccUnlocaleCheckLineMapper, SccUnlocaleCheckLine> implements ISccUnlocaleCheckLineService {
	private final IFileService fileService;
	private final ISysClient sysClient;
	private final IFlowClient flowClient;

	@Override
	public IPage<SccUnlocaleCheckLineVO> selectSccUnlocaleCheckLinePage(IPage<SccUnlocaleCheckLineVO> page, SccUnlocaleCheckLineVO sccUnlocaleCheckLine) {
		return page.setRecords(baseMapper.selectSccUnlocaleCheckLinePage(page, sccUnlocaleCheckLine));
	}

	@Override
	public List<SccUnlocaleCheckLine> getContinuedPage(IPage<ContinuedRecDataVO> page, ContinuedRecDataDTO continuedRecDataDTO) {
		return baseMapper.getContinuedPage(page,continuedRecDataDTO);
	}

	@Override
	public SccUnlocaleCheckLineVO getData(String id) {
		SccUnlocaleCheckLine unlocaleCheckLine = this.getById(id);
		SccUnlocaleCheckLineVO vo = Func.copy(unlocaleCheckLine, SccUnlocaleCheckLineVO.class);
		//获取检查整改通知书明细相关附件
		vo.setRelevantAttachments(fileService.getAttachments(vo.getId(),vo.getGroupName()));
		return vo;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveData(SccUnlocaleCheckLineDTO sccUnlocaleCheckLineDTO) {
		SccUnlocaleCheckLine checkLine = Func.copy(sccUnlocaleCheckLineDTO, SccUnlocaleCheckLine.class);
		checkLine.setRectificationEndTime(new Date());
		checkLine.setDeptId(AuthUtil.getDeptId());
//		checkLine.setRecFlag(Func.isNotEmpty(sccUnlocaleCheckLineDTO.getRecordFlag()) ? sccUnlocaleCheckLineDTO.getRecordFlag() : Constant.PROBLEM_STATE_USUUAL);
		this.saveOrUpdate(checkLine);
		//保存附件
		fileService.saveAttachments(sccUnlocaleCheckLineDTO.getRelevantAttachments(),checkLine.getId());
		return true;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R startProcess(SccUnlocaleCheckLine unlocaleCheckLine, String deptId) {
		R<BladeFlowDef> definitionRes = flowClient.getLatestProcessDefinitionByKey(ProcessConstant.SCC_UNLOCAL_CHECK_CONTINUE_KEY);
		if (definitionRes.isSuccess()) {
			unlocaleCheckLine.setProcessDefinitionId(definitionRes.getData().getId());
		} else {
			return R.fail("开启流程失败");
		}
		String businessTable = FlowUtil.getBusinessTable(SccUnlocaleCheckLine.class);
		R<Integer> deptCategory = sysClient.getDeptCategory(Long.valueOf(AuthUtil.getUser().getDeptId()));
		if (!deptCategory.isSuccess()) {
			return R.fail("查询部门类型失败，请检查后再试！");
		}
		R<Integer> sendDeptCategory = sysClient.getDeptCategory(Long.valueOf(deptId));
		if (!sendDeptCategory.isSuccess()) {
			return R.fail("查询推送部门类型失败，请检查后再试！");
		}
		Kv variables = Kv.create()
			.set("deptCategory", deptCategory.getData())
			.set("sendDeptCategory", sendDeptCategory.getData())
			.set(ProcessConstant.BUSINESS_ID_KEY, unlocaleCheckLine.getId())
			.set(ProcessConstant.START_PROC_USER_ID, AuthUtil.getUserId());
		R<BladeFlow> result = flowClient.startProcessInstanceById(unlocaleCheckLine.getProcessDefinitionId(), FlowUtil.getBusinessKey(businessTable, String.valueOf(unlocaleCheckLine.getId())), variables);
		if (result.isSuccess()) {
			unlocaleCheckLine.setProcessInstanceId(result.getData().getProcessInstanceId());
		} else {
			return R.fail("开启流程失败");
		}
		return R.status(this.updateById(unlocaleCheckLine));
	}

	@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) {
			SccUnlocaleCheckLine unlocaleCheckLines = this.getOne(new QueryWrapper<SccUnlocaleCheckLine>().lambda()
				.eq(Func.isNotEmpty(id), SccUnlocaleCheckLine::getId, id)
				.eq(SccUnlocaleCheckLine::getDelFlag, Constant.DELETE_FLAG_0));
			if (Func.isNotEmpty(unlocaleCheckLines)) {
					if (Func.isNotEmpty(pass) && pass) {
						//持续整改记录再次申请持续整改
						if (Constant.PROBLEM_STATE_SIX.equals(unlocaleCheckLines.getStatus())){
							result = this.update(new UpdateWrapper<SccUnlocaleCheckLine>().lambda().set(SccUnlocaleCheckLine::getStatus, Constant.PROBLEM_STATE_DRAFT_ONE).eq(SccUnlocaleCheckLine::getId, unlocaleCheckLines.getId()));
						}
						//持续整改记录提报
						if (Constant.PROBLEM_STATE_DRAFT_ONE.equals(unlocaleCheckLines.getStatus())){
							String aimStatus = Func.isEmpty(unlocaleCheckLines.getRectificationDeadline()) || unlocaleCheckLines.getRectificationDeadline().before(new Date()) ? Constant.PROBLEM_STATE_WAIT_TWO : Constant.PROBLEM_STATE_THREE;
							result = this.update(new UpdateWrapper<SccUnlocaleCheckLine>().lambda().set(SccUnlocaleCheckLine::getStatus,aimStatus).eq(SccUnlocaleCheckLine::getId, unlocaleCheckLines.getId()));
						}
					}
					if (!result){
						log.error("审批更新业务表单失败");
						return R.fail("审批更新业务表单失败");
					}

			}
		}
		return R.success("执行成功");
	}

}
