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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.security.common.Constant;
import org.security.ht.entity.basic.Device;
import org.security.trans.settings.dto.DeviceCategorySettingsDTO;
import org.security.trans.settings.entity.DeviceCategorySettings;
import org.security.trans.settings.entity.DeviceInspectionSettings;
import org.security.trans.settings.service.IDeviceInspectionSettingsService;
import org.security.trans.settings.vo.DeviceCategorySettingsVO;
import org.security.trans.settings.mapper.DeviceCategorySettingsMapper;
import org.security.trans.settings.service.IDeviceCategorySettingsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.node.ForestNodeMerger;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
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.List;
import java.util.Map;

/**
 * 系统配置-设备类型设置 服务实现类
 *
 * @author BladeX
 * @since 2022-03-03
 */
@Service
@Slf4j
@AllArgsConstructor
public class DeviceCategorySettingsServiceImpl extends ServiceImpl<DeviceCategorySettingsMapper, DeviceCategorySettings> implements IDeviceCategorySettingsService {
	private final static String PARENT_ID = "parentId";
	private final IDeviceInspectionSettingsService deviceInspectionSettingsService;


	@Override
	public IPage<DeviceCategorySettingsVO> selectDeviceCategorySettingsPage(IPage<DeviceCategorySettingsVO> page, DeviceCategorySettingsVO deviceCategorySettings) {
		return page.setRecords(baseMapper.selectDeviceCategorySettingsPage(page, deviceCategorySettings));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveDeviceCategorySettings(DeviceCategorySettingsDTO deviceCategorySettingsDTO) throws ParseException {
		DeviceCategorySettings deviceCategorySettings = Func.copy(deviceCategorySettingsDTO,DeviceCategorySettings.class);
		if(deviceCategorySettings.getParentId() == null || deviceCategorySettings.getParentId().longValue() == 0){
			deviceCategorySettings.setParentId(new Long(0));
		}
		deviceCategorySettings.setDelFlag(Constant.DELETE_FLAG_0);
		super.saveOrUpdate(deviceCategorySettings);
		List<DeviceInspectionSettings> lineList = deviceCategorySettingsDTO.getDeviceInspectionList();
		if (Func.isNotEmpty(lineList)){
			lineList.forEach(item -> {
				item.setDeviceCatgId(deviceCategorySettings.getId().toString());
			});
			//更新明细表-设备检查项-数据
			deviceInspectionSettingsService.saveOrUpdateBatch(lineList);
		}
		this.saveOrUpdate(deviceCategorySettings);
		//更新设备表的检查频率
		if (Func.isNotEmpty(deviceCategorySettings.getCheckFreq())){
			baseMapper.updateDeviceFrequence(String.valueOf(deviceCategorySettings.getId()),deviceCategorySettings.getCheckFreq());
		}
		return true;
	}

	@Override
	public List<DeviceCategorySettingsVO> tree(DeviceCategorySettingsDTO deviceCategorySettingsDTO) {
		return ForestNodeMerger.merge(baseMapper.tree(deviceCategorySettingsDTO));
	}

	@Override
	public List<DeviceCategorySettingsVO> lazyTree(Long parentId) {
		return ForestNodeMerger.merge(baseMapper.lazyTree(parentId));
	}

	@Override
	public List<DeviceCategorySettingsVO> lazyList(Long parentId, Map<String, Object> param) {
		if (Func.isEmpty(Func.toStr(param.get(PARENT_ID)))) {
			parentId = null;
		}
		return baseMapper.lazyList(parentId, param);
	}

	@Override
	public List<DeviceCategorySettingsVO> cascadeSelection() {
		List<DeviceCategorySettingsVO> deviceCategorySettingsVOS = baseMapper.cascade();
		return ForestNodeMerger.merge(deviceCategorySettingsVOS);
	}

	@Override
	public DeviceCategorySettingsVO getDetailById(String id){
		DeviceCategorySettings deviceCategorySettings =super.getById(id);
		DeviceCategorySettingsVO deviceCategorySettingsVO = Func.copy(deviceCategorySettings,DeviceCategorySettingsVO.class);
		//获取明细信息
		List<DeviceInspectionSettings> lineList = deviceInspectionSettingsService.list(new QueryWrapper<DeviceInspectionSettings>().eq("DEVICE_CATG_ID", id));
		if(Func.isNotEmpty(lineList)){
			deviceCategorySettingsVO.setDeviceInspectionList(lineList);
		}
		return deviceCategorySettingsVO;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R removeDeviceCategory(List<Long> toLongList){
		toLongList.forEach(ele -> {
			String item = String.valueOf(ele);
			QueryWrapper<DeviceCategorySettings> queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().eq(DeviceCategorySettings::getParentId, item).eq(DeviceCategorySettings::getDelFlag, Constant.DELETE_FLAG_0);
			List<DeviceCategorySettings> dcList = this.baseMapper.selectList(queryWrapper);
			if(dcList.size()>0){
				log.info("=====设备类型【{}】存在使用中的子级类型，无法删除",item);
				throw new ServiceException("当前设备类型存在使用中的子级类型，无法删除");
			}
			List<Device> deviceList = this.baseMapper.deviceList(item);
			if(deviceList.size()>0){
				log.info("=====设备类型【{}】存在使用中的设备，无法删除",item);
				throw new ServiceException("当前设备类型存在使用中的设备，无法删除");
			}
		});
		return R.status(this.removeByIds(toLongList));
	}
}
