/*
 *      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.dailyDuties.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import org.security.common.Constant;
import org.security.flow.core.constant.ProcessConstant;
import org.security.trans.app.vo.BacklogVO;
import org.security.trans.common.service.IFileService;
import org.security.trans.dailyDuties.dto.DeviceInspectionLineDTO;
import org.security.trans.dailyDuties.entity.DeviceInspection;
import org.security.trans.dailyDuties.entity.DeviceInspectionLine;
import org.security.trans.dailyDuties.vo.DeviceInspectionLineVO;
import org.security.trans.dailyDuties.mapper.DeviceInspectionLineMapper;
import org.security.trans.dailyDuties.service.IDeviceInspectionLineService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.security.trans.dailyDuties.vo.DeviceInspectionVO;
import org.security.trans.dailyDuties.vo.DevicePictureVO;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
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.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 任务-设备检查明细 服务实现类
 *
 * @author BladeX
 * @since 2022-03-25
 */
@Service
@AllArgsConstructor
public class DeviceInspectionLineServiceImpl extends ServiceImpl<DeviceInspectionLineMapper, DeviceInspectionLine> implements IDeviceInspectionLineService {

	private final IFileService fileService;
	@Override
	public IPage<DeviceInspectionLineVO> selectDeviceInspectionLinePage(IPage<DeviceInspectionLineVO> page, DeviceInspectionLineDTO deviceInspectionLineDTO) {
		Page<DeviceInspectionLine> queryPage = new Page<>(page.getCurrent(), page.getSize());
		QueryWrapper<DeviceInspectionLine> queryWrapper = new QueryWrapper<>();
		//获取持续整改记录明细
		if (Constant.PROBLEM_STATE_CONTINUED.equals(deviceInspectionLineDTO.getRectifyFlag())){
			queryWrapper.lambda().eq(DeviceInspectionLine::getId, deviceInspectionLineDTO.getFormId());
		}//获取非持续整改记录明细
		if (Constant.PROBLEM_STATE_USUUAL.equals(deviceInspectionLineDTO.getRectifyFlag())){
			queryWrapper.lambda().eq(DeviceInspectionLine::getFormId, deviceInspectionLineDTO.getFormId())
			.eq(DeviceInspectionLine::getRecFlag,Constant.PROBLEM_STATE_USUUAL);
		}
		//设备检查数据
		if("3".equals(deviceInspectionLineDTO.getRectifyFlag())){
			queryWrapper.lambda().eq(DeviceInspectionLine::getFormId, deviceInspectionLineDTO.getFormId());
		}
		Page<DeviceInspectionLine> resultPage = this.page(queryPage, queryWrapper);
		List<DeviceInspectionLine> records = resultPage.getRecords();
		List<DeviceInspectionLineVO> deviceInspectionLineVOList = Func.copy(records, DeviceInspectionLineVO.class);
		return new Page<DeviceInspectionLineVO>().
			setCurrent(resultPage.getCurrent())
			.setTotal(resultPage.getTotal())
			.setSize(resultPage.getSize())
			.setRecords(deviceInspectionLineVOList);
	}


	@Override
	public DevicePictureVO getPicture(String id) {
		DeviceInspectionLine deviceInspectionLine = this.getById(id);
		DevicePictureVO pictureVO = Func.copy(deviceInspectionLine,DevicePictureVO.class);
		//整改前图片
		pictureVO.setBeforePicList(fileService.getAttachments(deviceInspectionLine.getId(),deviceInspectionLine.getBeforePicIds()));
		//整改后图片
		pictureVO.setAfterPicList(fileService.getAttachments(deviceInspectionLine.getId(),deviceInspectionLine.getAfterPicIds()));
		return pictureVO;
	}

	@Override
	public List<BacklogVO> getData(BladeUser user, String deviceStateRectify, String problemStateContinued) {
		return baseMapper.getData(String.valueOf(user.getUserId()),deviceStateRectify,problemStateContinued);
	}

	@Override
	public List<DeviceInspectionVO> getContinuedRectifyData() {
		List<DeviceInspectionVO> vos = new ArrayList<>();
		List<DeviceInspectionLine> deviceInspectionLineList = baseMapper.getContinuedRectifyData();
		if (Func.isNotEmpty(deviceInspectionLineList)){
			deviceInspectionLineList.forEach(item -> {
				DeviceInspection deviceInspection = baseMapper.getDeviceInspection(item.getFormId());
				DeviceInspectionVO inspectionVO = Func.copy(deviceInspection, DeviceInspectionVO.class);
				inspectionVO.setId(item.getId());
				inspectionVO.setStatus(item.getStatus());
				inspectionVO.setRectifyFlag(Constant.PROBLEM_STATE_CONTINUED);
				vos.add(inspectionVO);
			});
		}
		return vos;
	}

	@Override
	public DeviceInspectionLineVO getDetailData(String id) {
		DeviceInspectionLine deviceInspectionLine = this.getById(id);
		DeviceInspectionLineVO vo = Func.copy(deviceInspectionLine, DeviceInspectionLineVO.class);
		vo.setBeforeImages(fileService.getAttachments(deviceInspectionLine.getId(),deviceInspectionLine.getBeforePicIds()));
		vo.setAfterImages(fileService.getAttachments(deviceInspectionLine.getId(),deviceInspectionLine.getAfterPicIds()));
		return vo;
	}


	@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) {
			DeviceInspectionLine deviceInspectionLine = this.getOne(new QueryWrapper<DeviceInspectionLine>().lambda()
				.eq(Func.isNotEmpty(id), DeviceInspectionLine::getId, id));
			if (Func.isNotEmpty(deviceInspectionLine)) {
				if (Func.isNotEmpty(pass) && pass) {
					//持续整改记录再次申请持续整改
					if (Constant.DEVICE_STATE_LEADER_CONFIRM.equals(deviceInspectionLine.getStatus())){
						result = this.update(new UpdateWrapper<DeviceInspectionLine>().lambda().set(DeviceInspectionLine::getStatus, Constant.DEVICE_STATE_RECTIFY).eq(DeviceInspectionLine::getId, deviceInspectionLine.getId()));
					}
					//持续整改记录提报
					if (Constant.PROBLEM_STATE_DRAFT_ONE.equals(deviceInspectionLine.getStatus())){
						result = this.update(new UpdateWrapper<DeviceInspectionLine>().lambda().set(DeviceInspectionLine::getStatus,Constant.DEVICE_STATE_RECTIFY_OVER).eq(DeviceInspectionLine::getId, deviceInspectionLine.getId()));
					}
				}
				if (!result){
					log.error("审批更新业务表单失败");
					return R.fail("审批更新业务表单失败");
				}

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

}
