package com.prolog.rdc.tms.service.fleetManagement.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.prolog.cs.platform.power.model.Organization;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.exception.BizException;
import com.prolog.framework.core.exception.ParameterException;
import com.prolog.rdc.tms.config.enums.BelongToEnum;
import com.prolog.rdc.tms.config.enums.DepartmentBaseLinkBaseTypeEnum;
import com.prolog.rdc.tms.constant.BussinessConstant;
import com.prolog.rdc.tms.dao.mapper.TmsBaseCarriersMapper;
import com.prolog.rdc.tms.dao.mapper.TmsBaseDriverMapper;
import com.prolog.rdc.tms.dao.mapper.TmsDepartmentBaseLinkMapper;
import com.prolog.rdc.tms.dao.mapper.TmsVehicleContainerLinkMapper;
import com.prolog.rdc.tms.model.dto.basicConfigure.StandardTemplateDetailsListDTO;
import com.prolog.rdc.tms.model.entity.line.TmsBaseCarriersModel;
import com.prolog.rdc.tms.model.entity.line.TmsBaseDriverModel;
import com.prolog.rdc.tms.model.entity.line.TmsDepartmentBaseLinkModel;
import com.prolog.rdc.tms.model.entity.line.TmsVehicleContainerLink;
import com.prolog.rdc.tms.model.vo.basicConfigure.ImportLogAddVO;
import com.prolog.rdc.tms.model.vo.xlsimport.ContainerImportVO;
import com.prolog.rdc.tms.rmi.feign.UserFeign;
import com.prolog.rdc.tms.service.DepartmentBaseLinkService;
import com.prolog.rdc.tms.service.basicConfigure.ImportLogService;
import com.prolog.rdc.tms.service.basicConfigure.SysImportTemplethService;
import com.prolog.rdc.tms.util.FileUtils;
import com.prolog.rdc.tms.util.ImportUtils;
import com.prolog.wms.base.util.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.prolog.common.util.DateUtils;
import com.prolog.common.util.ToolKits;
import com.prolog.framework.core.pojo.Page;
import com.prolog.framework.core.restriction.Criteria;
import com.prolog.framework.core.restriction.Restriction;
import com.prolog.framework.core.restriction.Restrictions;
import com.prolog.framework.dao.util.PageUtils;
import com.prolog.product.core.framework.entity.UserEntity;
import com.prolog.product.core.framework.util.PlgFxUsrUtils;
import com.prolog.rdc.tms.constant.DataDictionaryConstant;
import com.prolog.rdc.tms.constant.SeriaNnumberConstant;
import com.prolog.rdc.tms.constant.StatusConstant;
import com.prolog.rdc.tms.dao.mapper.TmsBaseContainerMapper;
import com.prolog.rdc.tms.model.dto.fleetManagement.ContainerDTO;
import com.prolog.rdc.tms.model.dto.fleetManagement.ContainerViewDTO;
import com.prolog.rdc.tms.model.entity.line.TmsBaseContainerModel;
import com.prolog.rdc.tms.model.vo.fleetManagement.ContainerAddVO;
import com.prolog.rdc.tms.model.vo.fleetManagement.ContainerDeleteVO;
import com.prolog.rdc.tms.model.vo.fleetManagement.ContainerPopVO;
import com.prolog.rdc.tms.model.vo.fleetManagement.ContainerUpdateVO;
import com.prolog.rdc.tms.model.vo.fleetManagement.ContainerVO;
import com.prolog.rdc.tms.model.vo.fleetManagement.ContainerViewVO;
import com.prolog.rdc.tms.model.vo.fleetManagement.ContainerWhetherEnableVO;
import com.prolog.rdc.tms.service.SysCodeengineService;
import com.prolog.rdc.tms.service.SysRefdatadService;
import com.prolog.rdc.tms.service.fleetManagement.ContainerService;
import com.prolog.rdc.tms.util.PublicMethods;

import cn.hutool.core.date.DateUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 
 *
 * 车队管理-容器资料实现层
 *
 * @className :ContainerServiceImpl
 * @author :fanzw
 * @creationTime :2022/04/18
 * @description :
 *
 * @modifier :fanzw
 * @modifyTime :2022/04/18
 * @reviseRemarks:
 *
 * @version :1.0.0
 *
 */
@Slf4j
@Service
public class ContainerServiceImpl implements ContainerService {

	@Autowired
	private TmsBaseContainerMapper tmsBaseContainerMapper;

	@Autowired
	private SysRefdatadService sysRefdatadService;

	@Autowired
	private SysCodeengineService sysCodeengineService;

	@Autowired
	private TmsDepartmentBaseLinkMapper tmsDepartmentBaseLinkMapper;

	@Autowired
	private TmsBaseCarriersMapper tmsBaseCarriersMapper;

	@Autowired
	private DepartmentBaseLinkService departmentBaseLinkService;

	@Autowired
	private UserFeign userFeign;

	@Autowired
	private ImportLogService importLogService;

	@Autowired
	private SysImportTemplethService sysImportTemplethService;

	@Autowired
	private ContainerService containerService;

	@Autowired
	private TmsBaseDriverMapper tmsBaseDriverMapper;

	@Autowired
	private TmsVehicleContainerLinkMapper tmsVehicleContainerLinkMapper;

	/**
	 * 容器资料分页查询
	 * 
	 * @param vo
	 * @return
	 */
	@SuppressWarnings("resource")
	@Override
	public Page<ContainerDTO> query(ContainerVO vo) {
		ToolKits.isParamNull(vo, "参数不能为空！");
		ToolKits.isParamNull(vo.getPageNum(), "当前页码不能为空");
		ToolKits.isParamNull(vo.getPageSize(), "每页条数不能为空");
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");
		vo.setEnterpriseId(user.getEnterpriseId());
		// 自有账号
		if (user.getUserType().equals(BussinessConstant.USER_TYPE_ZY)) {
			vo.setDepartmentIdList(user.getDepts());
		}
		// 承运商账号
		else if (user.getUserType().equals(BussinessConstant.USER_TYPE_CYS)) {
			vo.setAffiliationId(Long.valueOf(user.getLoginUserCompanyInfo().getId()));
		}
		// 司机账号
		else if (BussinessConstant.USER_TYPE_SJ.equals(user.getUserType())){
			TmsBaseDriverModel driverModel = tmsBaseDriverMapper.findById(user.getUserid(), TmsBaseDriverModel.class);
			if (ObjectUtil.isNull(driverModel)) {
				throw new BizException("司机不存在！");
			}
			if (DataDictionaryConstant.DRIVER_TYPE_OWN.equals(driverModel.getType())) {
				vo.setDepartmentIdList(user.getDepts());
			} else {
				vo.setAffiliationId(driverModel.getAffiliationId());
			}
		}
		PageUtils.startPage(vo.getPageNum(), vo.getPageSize());
		List<ContainerDTO> dtos = tmsBaseContainerMapper.findByCondition(vo);
		if (CollectionUtil.isNotEmpty(dtos)) {
			List<Long> baseId = dtos.stream().map(ContainerDTO::getId).collect(Collectors.toList());
			Criteria criteria = Criteria.forClass(TmsDepartmentBaseLinkModel.class);
			Restriction r1 = Restrictions.in("baseId", baseId.toArray());
			Restriction r2 = Restrictions.eq("baseType", DepartmentBaseLinkBaseTypeEnum.CONTAINER.getCode());
			criteria.setRestriction(Restrictions.and(r1, r2));
			List<TmsDepartmentBaseLinkModel> tmsDepartmentBaseLinkModelList = tmsDepartmentBaseLinkMapper.findByCriteria(criteria);
			Map<String, List<TmsDepartmentBaseLinkModel>> baseMap =
					tmsDepartmentBaseLinkModelList.stream().collect(Collectors.groupingBy(TmsDepartmentBaseLinkModel::getBaseId));
			// 容器类型
			List<Map<String, Object>> restMessage1 = sysRefdatadService.getDropDownById(DataDictionaryConstant.CONTAINER_TYPE, null, null, null);
			// 设备状态
			List<Map<String, Object>> restMessage3 = sysRefdatadService.getDropDownById(DataDictionaryConstant.MAINDATA_STATUS, null, null, null);
			// 归属
			List<Map<String, Object>> restMessage4 = sysRefdatadService.getDropDownById(BelongToEnum.BELONG_TO_TYPE, null, null, null);
			dtos.forEach(dto -> {
				dto.setTypeName(PublicMethods.change(restMessage1, String.valueOf(dto.getType())));
				dto.setStatusName(PublicMethods.change(restMessage3, String.valueOf(dto.getStatus())));
				dto.setBelongToName(PublicMethods.change(restMessage4, String.valueOf(dto.getBelongTo())));
				List<TmsDepartmentBaseLinkModel> linkList = baseMap.get(dto.getId().toString());
				if (CollectionUtil.isNotEmpty(linkList)) {
					dto.setDepartmentId(linkList.stream().map(TmsDepartmentBaseLinkModel::getDepartmentId).collect(Collectors.joining(",")));
					dto.setDepartmentCode(linkList.stream().map(TmsDepartmentBaseLinkModel::getDepartmentCode).collect(Collectors.joining(",")));
					dto.setDepartmentName(linkList.stream().map(TmsDepartmentBaseLinkModel::getDepartmentName).collect(Collectors.joining(",")));
				}
			});
		}
		Page<ContainerDTO> page = PageUtils.getPage(dtos);
		return page;
	}

	/**
	 * 容器资料弹窗
	 * 
	 * @param vo
	 * @return
	 */
	@SuppressWarnings("resource")
	@Override
	public Page<ContainerDTO> pop(ContainerPopVO vo) {
		ContainerVO containerVO = new ContainerVO();
		BeanUtils.copyProperties(vo, containerVO);
		containerVO.setStatus(DataDictionaryConstant.STATUS_ENABLE);
		return query(containerVO);
	}

	@Override
	public Page<ContainerDTO> queryByVehicle(ContainerVO vo) {
		if (StrUtil.isNotBlank(vo.getVehiclePlateNumber())) {
			Criteria criteria = Criteria.forClass(TmsVehicleContainerLink.class);
			Restriction r1 = Restrictions.eq("vehiclePlateNumber", vo.getVehiclePlateNumber());
			criteria.setRestriction(Restrictions.and(r1));
			List<TmsVehicleContainerLink> tmsVehicleContainerLinkList = tmsVehicleContainerLinkMapper.findByCriteria(criteria);
			if (CollectionUtil.isNotEmpty(tmsVehicleContainerLinkList)) {
				vo.setContainerIdList(tmsVehicleContainerLinkList.stream().map(TmsVehicleContainerLink::getContainerId).collect(Collectors.toList()));
			}
		}
		vo.setStatus(DataDictionaryConstant.STATUS_ENABLE);
		return query(vo);
	}

	/**
	 * 容器资料查看
	 * 
	 * @param vo
	 * @return
	 */
	@Override
	public ContainerViewDTO view(ContainerViewVO vo) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");
		ToolKits.isParamNull(vo.getId(), "容器ID不能为空");

		TmsBaseContainerModel model = tmsBaseContainerMapper.findById(vo.getId(), TmsBaseContainerModel.class);
		ToolKits.isParamNull(model, "容器ID[" + vo.getId() + "]有误,查询为空!");

		// 容器类型
		List<Map<String, Object>> restMessage1 = sysRefdatadService.getDropDownById(DataDictionaryConstant.CONTAINER_TYPE, null, null, null);
		// 设备状态
		List<Map<String, Object>> restMessage3 = sysRefdatadService.getDropDownById(DataDictionaryConstant.MAINDATA_STATUS, null, null, null);
		// 归属
		List<Map<String, Object>> restMessage4 = sysRefdatadService.getDropDownById(BelongToEnum.BELONG_TO_TYPE, null, null, null);
		ContainerViewDTO dto = new ContainerViewDTO();
		BeanUtils.copyProperties(model, dto);
		dto.setTypeName(PublicMethods.change(restMessage1, String.valueOf(model.getType())));
		dto.setBelongToName(PublicMethods.change(restMessage4, String.valueOf(model.getBelongTo())));
		dto.setStatusName(PublicMethods.change(restMessage3, String.valueOf(model.getStatus())));
		Map<String, Object> findMap = Maps.newHashMap();
		findMap.put("baseType", DepartmentBaseLinkBaseTypeEnum.DEVICE.getCode());
		findMap.put("baseId", vo.getId());
		List<TmsDepartmentBaseLinkModel> linkList = tmsDepartmentBaseLinkMapper.findByMap(findMap, TmsDepartmentBaseLinkModel.class);
		if (CollectionUtil.isNotEmpty(linkList)) {
			dto.setDepartmentId(linkList.stream().map(TmsDepartmentBaseLinkModel::getDepartmentId).collect(Collectors.joining(",")));
			dto.setDepartmentCode(linkList.stream().map(TmsDepartmentBaseLinkModel::getDepartmentCode).collect(Collectors.joining(",")));
			dto.setDepartmentName(linkList.stream().map(TmsDepartmentBaseLinkModel::getDepartmentName).collect(Collectors.joining(",")));
		}
		return dto;
	}

	/**
	 * 容器资料新增
	 * 
	 * @param vo
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void save(ContainerAddVO vo) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");
		ToolKits.isParamNull(vo.getCode(), "容器编号不能为空");
		ToolKits.isParamNull(vo.getName(), "容器名称不能为空");
		ToolKits.isParamNull(vo.getType(), "容器类型不能为空");
		ToolKits.isParamNull(vo.getDepartmentId(), "部门不能为空");
		ToolKits.isParamNull(vo.getDepartmentCode(), "部门编号不能为空");
		ToolKits.isParamNull(vo.getDepartmentName(), "部门名称不能为空");
		ToolKits.isParamNull(vo.getBelongTo(), "归属不能为空");
		// 判断容器编号是否已存在
		PublicMethods.isThereAnyinformation(TmsBaseContainerModel.class, "code", vo.getCode(), "enterpriseId", user.getEnterpriseId(), tmsBaseContainerMapper, "容器编码已存在");
		// 判断容器名称是否已存在
		PublicMethods.isThereAnyinformation(TmsBaseContainerModel.class, "name", vo.getName(), "enterpriseId", user.getEnterpriseId(), tmsBaseContainerMapper, "容器名称已存在");
		if (BelongToEnum.OWN.getCode().equals(vo.getBelongTo())) {
			if (user.getUserType().equals(BussinessConstant.USER_TYPE_CYS)) {
				if (StrUtil.isNotBlank(user.getLoginUserCompanyInfo().getId())) {
					vo.setAffiliationId(Long.valueOf(user.getLoginUserCompanyInfo().getId()));
				}
				vo.setAffiliationCode(user.getLoginUserCompanyInfo().getCode());
				vo.setAffiliationName(user.getLoginUserCompanyInfo().getName());
			}
		} else {
			ToolKits.isParamNull(vo.getAffiliationId(), "隶属机构编码不为空");
			ToolKits.isParamNull(vo.getAffiliationCode(), "隶属机构编码不为空");
			ToolKits.isParamNull(vo.getAffiliationName(), "隶属机构名称不为空");
			Criteria criteria = Criteria.forClass(TmsBaseCarriersModel.class);
			Restriction r1 = Restrictions.eq("id", vo.getAffiliationId());
			Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
			criteria.setRestriction(Restrictions.and(r1, r2));
			List<TmsBaseCarriersModel> tmsBaseCarriersModels = tmsBaseCarriersMapper.findByCriteria(criteria);
			ToolKits.isParamNull(tmsBaseCarriersModels, "未找到对应的隶属机构[" + vo.getAffiliationName() + "]");
			TmsBaseCarriersModel tmsBaseCarriersModel = tmsBaseCarriersModels.get(0);
			if (StatusConstant.STATUS_DISABLE.equals(tmsBaseCarriersModel.getStatus())) {
				throw new BizException("隶属机构【" + vo.getAffiliationName() + "】已被停用");
			}
		}
		String id = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.CONTAINER_ID, "L");
		ToolKits.isParamNull(id, "获取容器ID失败！");
		Date date = DateUtil.date();
		TmsBaseContainerModel model = new TmsBaseContainerModel();
		BeanUtils.copyProperties(vo, model);
		model.setId(Long.valueOf(id));
		model.setStatus(DataDictionaryConstant.STATUS_CREATE);
		model.setEnterpriseId(user.getEnterpriseId());
		model.setEnterpriseName(user.getEnterpriseName());
		model.setCreateperson(user.getNickname());
		model.setCreatetime(DateUtils.nowDate());
		model.setUpdateperson(user.getNickname());
		model.setUpdatetime(date);
		tmsBaseContainerMapper.save(model);
		departmentBaseLinkService.addLink(DepartmentBaseLinkBaseTypeEnum.CONTAINER, id, vo.getDepartmentId(), vo.getDepartmentCode(), vo.getDepartmentName());
	}

	/**
	 * 容器资料修改
	 * 
	 * @param vo
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(ContainerUpdateVO vo) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");
		ToolKits.isParamNull(vo.getId(), "容器ID不能为空");
		ToolKits.isParamNull(vo.getType(), "容器类型不能为空");
		ToolKits.isParamNull(vo.getDepartmentId(), "部门不能为空");
		ToolKits.isParamNull(vo.getDepartmentCode(), "部门编号不能为空");
		ToolKits.isParamNull(vo.getDepartmentName(), "部门名称不能为空");
		ToolKits.isParamNull(vo.getBelongTo(), "归属不能为空");
		if (BelongToEnum.OWN.getCode().equals(vo.getBelongTo())) {
			if (user.getUserType().equals(BussinessConstant.USER_TYPE_CYS)) {
				if (StrUtil.isNotBlank(user.getLoginUserCompanyInfo().getId())) {
					vo.setAffiliationId(Long.valueOf(user.getLoginUserCompanyInfo().getId()));
				}
				vo.setAffiliationCode(user.getLoginUserCompanyInfo().getCode());
				vo.setAffiliationName(user.getLoginUserCompanyInfo().getName());
			}
		} else {
			ToolKits.isParamNull(vo.getAffiliationId(), "隶属机构编码不为空");
			ToolKits.isParamNull(vo.getAffiliationCode(), "隶属机构编码不为空");
			ToolKits.isParamNull(vo.getAffiliationName(), "隶属机构名称不为空");
			Criteria criteria = Criteria.forClass(TmsBaseCarriersModel.class);
			Restriction r1 = Restrictions.eq("id", vo.getAffiliationId());
			Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
			criteria.setRestriction(Restrictions.and(r1, r2));
			List<TmsBaseCarriersModel> tmsBaseCarriersModels = tmsBaseCarriersMapper.findByCriteria(criteria);
			ToolKits.isParamNull(tmsBaseCarriersModels, "未找到对应的隶属机构[" + vo.getAffiliationName() + "]");
			TmsBaseCarriersModel tmsBaseCarriersModel = tmsBaseCarriersModels.get(0);
			if (StatusConstant.STATUS_DISABLE.equals(tmsBaseCarriersModel.getStatus())) {
				throw new BizException("隶属机构【" + vo.getAffiliationName() + "】已被停用");
			}
		}
		TmsBaseContainerModel model = tmsBaseContainerMapper.findById(vo.getId(), TmsBaseContainerModel.class);
		ToolKits.isParamNull(model, "容器ID[" + vo.getId() + "]有误,查询为空!");
		model.setLength(vo.getLength());
		model.setWidth(vo.getWidth());
		model.setHeight(vo.getHeight());
		model.setWeight(vo.getWeight());
		model.setVolume(vo.getVolume());
		model.setMemo(vo.getMemo());
		model.setAffiliationId(vo.getAffiliationId());
		model.setAffiliationCode(vo.getAffiliationCode());
		model.setAffiliationName(vo.getAffiliationName());
		model.setBelongTo(vo.getBelongTo());
		model.setType(vo.getType());
		model.setUpdateperson(user.getNickname());
		model.setUpdatetime(DateUtils.nowDate());
		tmsBaseContainerMapper.update(model);
		departmentBaseLinkService.deleteLink(DepartmentBaseLinkBaseTypeEnum.CONTAINER, Lists.newArrayList(String.valueOf(vo.getId())));
		departmentBaseLinkService.addLink(DepartmentBaseLinkBaseTypeEnum.CONTAINER, String.valueOf(vo.getId()), vo.getDepartmentId(), vo.getDepartmentCode(), vo.getDepartmentName());
	}

	/**
	 * 容器资料是否启用
	 * @param containerWhetherEnableVO
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void whetherEnable(ContainerWhetherEnableVO containerWhetherEnableVO) {
		ToolKits.isParamNull(containerWhetherEnableVO, "容器资料是否启用请求不为空");
		ToolKits.isParamNull(containerWhetherEnableVO.getIds(), "容器ID集不能为空");
		ToolKits.isParamNull(containerWhetherEnableVO.getStatus(), "状态不能为空");
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");
		Criteria criteria = Criteria.forClass(TmsBaseContainerModel.class);
		Restriction r1 = Restrictions.in("id", containerWhetherEnableVO.getIds().toArray());
		criteria.setRestriction(r1);
		Map<String, Object> map = Maps.newHashMap();
		map.put("status", containerWhetherEnableVO.getStatus());
		map.put("updateperson", user.getNickname());
		map.put("updatetime", DateUtil.date());
		tmsBaseContainerMapper.updateMapByCriteria(map, criteria);
	}

	/**
	 * 容器资料删除
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delete(ContainerDeleteVO containerDeleteVO) {
		ToolKits.isParamNull(containerDeleteVO, "容器资料删除请求不为空");
		ToolKits.isParamNull(containerDeleteVO.getIds(), "容器ID集不能为空！");
		// 执行删除
		tmsBaseContainerMapper.deleteByIds(containerDeleteVO.getIds().toArray(), TmsBaseContainerModel.class);
		departmentBaseLinkService.deleteLink(DepartmentBaseLinkBaseTypeEnum.CONTAINER,
				containerDeleteVO.getIds().stream().map(String::valueOf).collect(Collectors.toList()));
	}

	@Override
	public void importContainer(MultipartFile file) {
		// 导入文件判断
		FileUtils.multipartFileJudge(file);
		Properties properties = new Properties();
		// 待转换的对象
		Class<ContainerImportVO> importVOClass = ContainerImportVO.class;
		// 标准模板查询
		List<StandardTemplateDetailsListDTO> standardTemplateDetailsListDTOs =
				sysImportTemplethService.listStandardTemplateDetailsData(DataDictionaryConstant.CONTAINER_IMPORT);
		standardTemplateDetailsListDTOs.forEach(standardTemplateDetailsListDTO ->
				properties.setProperty(standardTemplateDetailsListDTO.getStdColNo(), standardTemplateDetailsListDTO.getCustColName())
		);
		// @ExcelProperty注解属性修改
		ImportUtils.setHeaderValue(properties, importVOClass);
		// EXCEL转对象
		List<ContainerImportVO> importVOs;
		try {
			importVOs = ExcelUtils.read(file, importVOClass);
		} catch (Exception e) {
			log.error("容器导入异常", e);
			throw new ParameterException("EXCEL转对象失败:" + e.getMessage());
		}
		ToolKits.isParamNull(importVOs, "EXCEL文件内容为空,请重新导入");
		log.info("容器导入详情:{}", JSON.toJSONString(importVOs));
		String importBatchNumber = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.IMPORT_BATCHNO, "L");
		ToolKits.isParamNull(importBatchNumber, "导入批次获取失败");
		// 导入日志对象
		ImportLogAddVO logAddVO = new ImportLogAddVO();
		logAddVO.setImportObjNo(DataDictionaryConstant.CONTAINER_IMPORT);
		logAddVO.setImportBatchNumber(importBatchNumber);
		logAddVO.setStatus(DataDictionaryConstant.IMPORT_STATUS_YES);
		logAddVO.setSuccessNum(importVOs.size());
		logAddVO.setFailNum(0);
		try {
			containerService.saveImportContainer(importVOs, importBatchNumber);
			// 导入执行
			importLogService.addImportLogData(logAddVO);
		} catch (Exception e) {
			logAddVO.setStatus(DataDictionaryConstant.IMPORT_STATUS_NO);
			logAddVO.setSuccessNum(0);
			logAddVO.setFailNum(importVOs.size());
			logAddVO.setFailReason(e.getMessage());
			importLogService.addImportLogData(logAddVO);
			log.error("导入失败", e);
			throw new BizException(e.getMessage());
		}
	}

	@Override
	public void saveImportContainer(List<ContainerImportVO> importVOs, String importBatchNumber) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		RestMessage<List<Organization>> departmentRes = userFeign.search(null, null, null, String.valueOf(user.getEnterpriseId()));
		if (!departmentRes.isSuccess()) {
			throw new BizException("企业部门不存在!");
		}
		List<Organization> departmentList = departmentRes.getData();
		Criteria carrierCriteria = Criteria.forClass(TmsBaseCarriersModel.class);
		Restriction carrierRestriction = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		carrierCriteria.setRestriction(carrierRestriction);
		List<TmsBaseCarriersModel> tmsBaseCarriersModels = tmsBaseCarriersMapper.findByCriteria(carrierCriteria);
		Map<String, TmsBaseCarriersModel> carriersMap = tmsBaseCarriersModels.stream().collect(Collectors.toMap(t1 -> t1.getName(),
				t2 -> t2, (t1, t2) -> t2));
		//校验数据
		check(importVOs, departmentList, carriersMap);

		importVOs.forEach(containerImportVO -> {
			String id = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.CONTAINER_ID, "L");
			ToolKits.isParamNull(id, "获取设备ID失败！");
			TmsBaseCarriersModel carriersModel = carriersMap.get(containerImportVO.getAffiliationName());
			Date date = DateUtil.date();
			TmsBaseContainerModel model = new TmsBaseContainerModel();
			model.setId(Long.valueOf(id));
			model.setCode(containerImportVO.getCode());
			model.setName(containerImportVO.getName());
			model.setType(Integer.valueOf(containerImportVO.getType()));
			model.setMemo(containerImportVO.getMemo());
			if (BelongToEnum.OWN.getCode().equals(containerImportVO.getBelongTo())) {
				if (user.getUserType().equals(BussinessConstant.USER_TYPE_CYS)) {
					if (StrUtil.isNotBlank(user.getLoginUserCompanyInfo().getId())) {
						model.setAffiliationId(Long.valueOf(user.getLoginUserCompanyInfo().getId()));
					}
					model.setAffiliationCode(user.getLoginUserCompanyInfo().getCode());
					model.setAffiliationName(user.getLoginUserCompanyInfo().getName());
				}
			} else {
				if (ObjectUtil.isNotNull(carriersModel)) {
					model.setAffiliationId(carriersModel.getId());
					model.setAffiliationCode(carriersModel.getCode());
					model.setAffiliationName(carriersModel.getName());
				}
			}
			model.setBelongTo(containerImportVO.getBelongTo());
			model.setStatus(DataDictionaryConstant.STATUS_CREATE);
			model.setEnterpriseId(user.getEnterpriseId());
			model.setEnterpriseName(user.getEnterpriseName());
			model.setCreateperson(user.getNickname());
			model.setCreatetime(date);
			model.setUpdateperson(user.getNickname());
			model.setUpdatetime(date);
			model.setImportBatchNumber(importBatchNumber);
			model.setLength(containerImportVO.getLength());
			model.setWidth(containerImportVO.getWidth());
			model.setHeight(containerImportVO.getHeight());
			model.setWeight(containerImportVO.getWeight());
			if (ObjectUtil.isNotNull(containerImportVO.getVolume())) {
				model.setVolume(containerImportVO.getVolume());
			} else {
				if (ObjectUtil.isNotNull(containerImportVO.getLength()) && ObjectUtil.isNotNull(containerImportVO.getWidth()) && ObjectUtil.isNotNull(containerImportVO.getHeight())) {
					model.setVolume(containerImportVO.getLength().multiply(containerImportVO.getWidth().multiply(containerImportVO.getHeight())));
				}
			}
			tmsBaseContainerMapper.save(model);
			List<String> departmentNames = Lists.newArrayList(containerImportVO.getDepartment().replace("，",",").split(","));
			departmentBaseLinkService.addLink(DepartmentBaseLinkBaseTypeEnum.CONTAINER, id,
					departmentList.stream().filter(department -> departmentNames.contains(department.getName())).collect(Collectors.toList()));
		});
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void rollbackData(String batchno) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");
		Criteria criteria = Criteria.forClass(TmsBaseContainerModel.class);
		Restriction r1 = Restrictions.eq("importBatchNumber", batchno);
		criteria.setRestriction(r1);
		List<TmsBaseContainerModel> tmsBaseContainerModelList = tmsBaseContainerMapper.findByCriteria(criteria);
		if (ToolKits.isEmpty(tmsBaseContainerModelList)) {
			throw new BizException("批次号[" + batchno + "]错误,查询为空!");
		}
		ContainerDeleteVO containerDeleteVO = new ContainerDeleteVO();
		containerDeleteVO.setIds(tmsBaseContainerModelList.stream().map(TmsBaseContainerModel::getId).
				map(String::valueOf).collect(Collectors.toList()));
		delete(containerDeleteVO);
	}

	@Override
	public List<ContainerDTO> findByIdList(List<Long> idList) {
		List<ContainerDTO> list = Lists.newArrayList();
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		Criteria criteria = Criteria.forClass(TmsBaseContainerModel.class);
		Restriction r1 = Restrictions.in(TmsBaseContainerModel::getId, idList);
		Restriction r2 = Restrictions.eq(TmsBaseContainerModel::getEnterpriseId, user.getEnterpriseId());
		criteria.setRestriction(Restrictions.and(r1, r2));
		List<TmsBaseContainerModel> tmsBaseContainerModelList = tmsBaseContainerMapper.findByCriteria(criteria);
		if (CollectionUtil.isNotEmpty(tmsBaseContainerModelList)) {
			list = tmsBaseContainerModelList.stream().map(model ->
					BeanUtil.copyProperties(model, ContainerDTO.class)).collect(Collectors.toList());
		}
		return list;
	}

	/**
	 * 校验导入数据
	 * @param importVOs
	 * @param departmentList
	 * @param carriersMap
	 */
	private void check(List<ContainerImportVO> importVOs, List<Organization> departmentList,
					   Map<String, TmsBaseCarriersModel> carriersMap) {
		for (int i = 0; i < importVOs.size(); i++) {
			if (ToolKits.isEmpty(importVOs.get(i).getCode())) {
				throw new BizException("第" + (i+1) + "行导入数据,容器编码不能为空");
			}
			if (ToolKits.isEmpty(importVOs.get(i).getName())) {
				throw new BizException("第" + (i+1) + "行导入数据,容器名称不能为空");
			}
			if (ToolKits.isEmpty(importVOs.get(i).getType())) {
				throw new BizException("第" + (i+1) + "行导入数据,容器类型不能为空");
			}
			if (ToolKits.isEmpty(importVOs.get(i).getDepartment())) {
				throw new BizException("第" + (i+1) + "行导入数据,部门不能为空");
			}
			if (ToolKits.isEmpty(importVOs.get(i).getBelongTo())) {
				throw new BizException("第" + (i+1) + "行导入数据,归属不能为空");
			}
			if (!BelongToEnum.OWN.getCode().equals(importVOs.get(i).getBelongTo())) {
				if (ToolKits.isEmpty(importVOs.get(i).getAffiliationName())) {
					throw new BizException("第" + (i+1) + "行导入数据,归属不为自有,隶属机构不能为空");
				}
			}
		}
		// 验证导入文件中设备编号是否重复
		Map<String, Long> codeMap = importVOs.stream().collect(Collectors.groupingBy(ContainerImportVO::getCode, Collectors.counting()));
		for (Map.Entry<String, Long> longEntry : codeMap.entrySet()) {
			if (longEntry.getValue() > 1) {
				throw new ParameterException(String.format("导入文件中，容器编号【%s】重复", longEntry.getKey()));
			}
		}
		// 验证导入文件中设备名称是否重复
		Map<String, Long> nameMap = importVOs.stream().collect(Collectors.groupingBy(ContainerImportVO::getName, Collectors.counting()));
		for (Map.Entry<String, Long> longEntry : nameMap.entrySet()) {
			if (longEntry.getValue() > 1) {
				throw new ParameterException(String.format("导入文件中，容器编号【%s】重复", longEntry.getKey()));
			}
		}
		Set<String> codeList = codeMap.keySet();
		Set<String> nameList = nameMap.keySet();
		Criteria criteria = Criteria.forClass(TmsBaseContainerModel.class);
		Restriction r1 = Restrictions.in("code", codeList.toArray());
		criteria.setRestriction(r1);
		List<TmsBaseContainerModel> tmsBaseContainerModelList = tmsBaseContainerMapper.findByCriteria(criteria);
		if (CollectionUtil.isNotEmpty(tmsBaseContainerModelList)) {
			throw new ParameterException(String.format("导入文件中，容器编号已存在"));
		}
		Criteria namecriteria = Criteria.forClass(TmsBaseContainerModel.class);
		Restriction rname = Restrictions.in("name", nameList.toArray());
		namecriteria.setRestriction(rname);
		List<TmsBaseContainerModel> tmsBaseContainerModelList1 = tmsBaseContainerMapper.findByCriteria(namecriteria);
		if (CollectionUtil.isNotEmpty(tmsBaseContainerModelList1)) {
			throw new ParameterException(String.format("导入文件中，容器名称已存在"));
		}
		Map<String, Organization> departmentMap = departmentList.stream().collect(Collectors.toMap(t1 -> t1.getName(),
				t2 -> t2, (t1, t2) -> t2));
		List<String> departmentNameList = importVOs.stream().flatMap(deviceImportVO ->
						Stream.of(deviceImportVO.getDepartment().replace("，",",").split(","))).
				distinct().collect(Collectors.toList());
		departmentNameList.forEach(departmentName -> {
			if (!departmentMap.keySet().contains(departmentName)) {
				throw new BizException("部门【"+departmentName+"】不存在!");
			}
		});
		List<String> affiliationNameList = importVOs.stream().map(ContainerImportVO::getAffiliationName).
				filter(StrUtil::isNotBlank).collect(Collectors.toList());
		affiliationNameList.forEach(affiliationName -> {
			if (!carriersMap.keySet().contains(affiliationName)) {
				throw new BizException("隶属机构【" + affiliationName + "】不存在!");
			}
			if (StatusConstant.STATUS_DISABLE.equals(carriersMap.get(affiliationName).getStatus())) {
				throw new BizException("隶属机构【" + affiliationName + "】已被停用");
			}
		});
	}
}
