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

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Maps;
import com.prolog.common.util.ToolKits;
import com.prolog.cs.platform.power.model.Organization;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.exception.ParameterException;
import com.prolog.framework.core.exception.PrologException;
import com.prolog.framework.core.pojo.Page;
import com.prolog.framework.core.restriction.Criteria;
import com.prolog.framework.core.restriction.Order;
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.easyexcel.util.ExcelUtils;
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.RabbitMQConstant;
import com.prolog.rdc.tms.constant.SeriaNnumberConstant;
import com.prolog.rdc.tms.constant.StatusConstant;
import com.prolog.rdc.tms.dao.mapper.TmsBaseVehicleMapper;
import com.prolog.rdc.tms.dao.mapper.TmsBaseVehicleTypeMapper;
import com.prolog.rdc.tms.model.dto.basicConfigure.StandardTemplateDetailsListDTO;
import com.prolog.rdc.tms.model.dto.fleetManagement.VehicleTypeCheckDTO;
import com.prolog.rdc.tms.model.dto.fleetManagement.VehicleTypeImportPageDTO;
import com.prolog.rdc.tms.model.dto.fleetManagement.VehicleTypePagingQueryDTO;
import com.prolog.rdc.tms.model.dto.fleetManagement.VehicleTypePopupDTO;
import com.prolog.rdc.tms.model.entity.line.TmsBaseVehicleModel;
import com.prolog.rdc.tms.model.entity.line.TmsBaseVehicleTypeModel;
import com.prolog.rdc.tms.model.vo.basicConfigure.ImportLogAddVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.ImportPageVO;
import com.prolog.rdc.tms.model.vo.fleetManagement.VehicleTypeAddVO;
import com.prolog.rdc.tms.model.vo.fleetManagement.VehicleTypeByIdVO;
import com.prolog.rdc.tms.model.vo.fleetManagement.VehicleTypeCheckVO;
import com.prolog.rdc.tms.model.vo.fleetManagement.VehicleTypeDeleteVO;
import com.prolog.rdc.tms.model.vo.fleetManagement.VehicleTypeModifyVO;
import com.prolog.rdc.tms.model.vo.fleetManagement.VehicleTypePagingQueryVO;
import com.prolog.rdc.tms.model.vo.fleetManagement.VehicleTypePopupVO;
import com.prolog.rdc.tms.model.vo.fleetManagement.VehicleTypeWhetherEnableVO;
import com.prolog.rdc.tms.model.vo.xlsimport.VehicleTypeImportVO;
import com.prolog.rdc.tms.rmi.feign.UserFeign;
import com.prolog.rdc.tms.service.SysCodeengineService;
import com.prolog.rdc.tms.service.SysRefdatadService;
import com.prolog.rdc.tms.service.basicConfigure.ImportLogService;
import com.prolog.rdc.tms.service.basicConfigure.SysImportTemplethService;
import com.prolog.rdc.tms.service.fleetManagement.VehicleTypeService;
import com.prolog.rdc.tms.util.FileUtils;
import com.prolog.rdc.tms.util.ImportUtils;
import com.prolog.rdc.tms.util.PublicMethods;
import com.prolog.wms.base.util.JsonMapper;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 车队管理-车型管理实现层
 *
 * @author Eton Woo
 * @date 2022/03/11
 */
@Slf4j
@Service
public class VehicleTypeServiceImpl implements VehicleTypeService {

	@Autowired
	private SysRefdatadService sysRefdatadService;

	@Autowired
	private TmsBaseVehicleTypeMapper tmsBaseVehicleTypeMapper;

	@Autowired
	private TmsBaseVehicleMapper tmsBaseVehicleMapper;

	@Autowired
	private SysCodeengineService sysCodeengineService;

	@Autowired
	private ImportLogService importLogService;

	@Autowired
	private SysImportTemplethService sysImportTemplethService;

	@Autowired
	private AmqpTemplate amqpTemplate;

	@Autowired
	private UserFeign userFeign;

	/**
	 * 车型资料分页查询
	 */
	@SuppressWarnings("resource")
	@Override
	public Page<VehicleTypePagingQueryDTO> pageVehicleTypeData(VehicleTypePagingQueryVO vehicleTypePagingQueryVO) {
		ToolKits.isParamNull(vehicleTypePagingQueryVO, "车型资料查询请求不为空");
		ToolKits.isParamNull(vehicleTypePagingQueryVO.getPageNum(), "页码不为空");
		ToolKits.isParamNull(vehicleTypePagingQueryVO.getPageSize(), "页数不为空");

		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		// 相应对象集合
		List<VehicleTypePagingQueryDTO> vehicleTypePagingQueryDTOs = new ArrayList<VehicleTypePagingQueryDTO>();

		// 车型品牌
		List<Map<String, Object>> restMessage1 = sysRefdatadService.getDropDownById(DataDictionaryConstant.VEHICLE_TYPE_BRAND, null, null, null);

		// 车型类别
		List<Map<String, Object>> restMessage2 = sysRefdatadService.getDropDownById(DataDictionaryConstant.VEHICLE_TYPE_CATEGORY, null, null, null);

		// 车型状态
		List<Map<String, Object>> restMessage3 = sysRefdatadService.getDropDownById(DataDictionaryConstant.MAINDATA_STATUS, null, null, null);

		// 分页
		PageUtils.startPage(vehicleTypePagingQueryVO.getPageNum(), vehicleTypePagingQueryVO.getPageSize());

		Criteria criteria = Criteria.forClass(TmsBaseVehicleTypeModel.class);
		Restriction r1 = ToolKits.isEmpty(vehicleTypePagingQueryVO.getVehicleTypeCode()) ? null : Restrictions.like("code", "%" + vehicleTypePagingQueryVO.getVehicleTypeCode() + "%");
		Restriction r2 = ToolKits.isEmpty(vehicleTypePagingQueryVO.getVehicleTypeName()) ? null : Restrictions.like("name", "%" + vehicleTypePagingQueryVO.getVehicleTypeName() + "%");
		Restriction r3 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		criteria.setRestriction(Restrictions.and(r1, r2, r3));
		criteria.setOrder(Order.newInstance().desc(new String[] { "updatetime" }));
		List<TmsBaseVehicleTypeModel> tmsBaseVehicleTypeModels = tmsBaseVehicleTypeMapper.findByCriteria(criteria);

		for (TmsBaseVehicleTypeModel item : tmsBaseVehicleTypeModels) {
			// 响应对象
			VehicleTypePagingQueryDTO vehicleTypePagingQueryDTO = new VehicleTypePagingQueryDTO();
			BeanUtils.copyProperties(item, vehicleTypePagingQueryDTO);
			vehicleTypePagingQueryDTO.setBrandName(PublicMethods.change(restMessage1, String.valueOf(vehicleTypePagingQueryDTO.getBrand())));
			vehicleTypePagingQueryDTO.setTypeName(PublicMethods.change(restMessage2, String.valueOf(vehicleTypePagingQueryDTO.getType())));
			vehicleTypePagingQueryDTO.setStatusName(PublicMethods.change(restMessage3, String.valueOf(vehicleTypePagingQueryDTO.getStatus())));
			vehicleTypePagingQueryDTOs.add(vehicleTypePagingQueryDTO);
		}

		Page<VehicleTypePagingQueryDTO> page = PageUtils.getPage(vehicleTypePagingQueryDTOs);
		if (tmsBaseVehicleTypeModels instanceof com.github.pagehelper.Page) {
			com.github.pagehelper.Page<TmsBaseVehicleTypeModel> p0 = (com.github.pagehelper.Page<TmsBaseVehicleTypeModel>) tmsBaseVehicleTypeModels;
			page.setPageCount(p0.getPages());
			page.setPageNum(p0.getPageNum());
			page.setPageSize(p0.getPageSize());
			page.setTotalCount(p0.getTotal());
			page.setStartRow(p0.getStartRow());
			page.setEndRow(p0.getEndRow());
		}

		return page;
	}

	/**
	 * 车型资料查看
	 */
	@Override
	public VehicleTypeCheckDTO getVehicleTypeData(VehicleTypeCheckVO vehicleTypeCheckVO) {
		ToolKits.isParamNull(vehicleTypeCheckVO, "车型资料查看请求不为空");
		ToolKits.isParamNull(vehicleTypeCheckVO.getVehicleTypeId(), "车型ID不为空");

		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		Criteria criteria = Criteria.forClass(TmsBaseVehicleTypeModel.class);
		Restriction r1 = Restrictions.eq("id", vehicleTypeCheckVO.getVehicleTypeId());
		Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		criteria.setRestriction(Restrictions.and(r1, r2));
		List<TmsBaseVehicleTypeModel> tmsBaseVehicleTypeModels = tmsBaseVehicleTypeMapper.findByCriteria(criteria);

		if (tmsBaseVehicleTypeModels.size() == 0) {
			throw new ParameterException("车型ID【" + vehicleTypeCheckVO.getVehicleTypeId() + "】数据不存在，查询失败");
		} else if (tmsBaseVehicleTypeModels.size() > 1) {
			throw new ParameterException("车型ID【" + vehicleTypeCheckVO.getVehicleTypeId() + "】存在重复数据，查询失败");
		}

		// 车型品牌
		List<Map<String, Object>> restMessage1 = sysRefdatadService.getDropDownById(DataDictionaryConstant.VEHICLE_TYPE_BRAND, null, null, null);

		// 车型类别
		List<Map<String, Object>> restMessage2 = sysRefdatadService.getDropDownById(DataDictionaryConstant.VEHICLE_TYPE_CATEGORY, null, null, null);

		// 车型资料对象
		TmsBaseVehicleTypeModel tmsBaseVehicleTypeModel = tmsBaseVehicleTypeModels.get(0);

		// 响应对象
		VehicleTypeCheckDTO vehicleTypeCheckDTO = new VehicleTypeCheckDTO();
		BeanUtils.copyProperties(tmsBaseVehicleTypeModel, vehicleTypeCheckDTO);
		vehicleTypeCheckDTO.setBrandName(PublicMethods.change(restMessage1, String.valueOf(vehicleTypeCheckDTO.getBrand())));
		vehicleTypeCheckDTO.setTypeName(PublicMethods.change(restMessage2, String.valueOf(vehicleTypeCheckDTO.getType())));

		return vehicleTypeCheckDTO;
	}

	/**
	 * 根据载重载方查询车型资料
	 * @param vehicleTypeCheckVO
	 * @return
	 */
	public VehicleTypeCheckDTO queryVehicleTypeByWeightVolume(VehicleTypeCheckVO vehicleTypeCheckVO) {
		ToolKits.isParamNull(vehicleTypeCheckVO, "车型资料查看请求不为空");

		VehicleTypeCheckDTO vehicleTypeCheckDTO = new VehicleTypeCheckDTO();
		if (ObjectUtil.isEmpty(vehicleTypeCheckVO.getWeight()) && ObjectUtil.isEmpty(vehicleTypeCheckVO.getVolume())) {
			return vehicleTypeCheckDTO;
		}

		Criteria criteria = Criteria.forClass(TmsBaseVehicleTypeModel.class);
		Restriction r1 = null;
		Restriction r2 = null;
		if (ObjectUtil.isNotEmpty(vehicleTypeCheckVO.getVolume()) && NumberUtil.isGreater(vehicleTypeCheckVO.getVolume(), BigDecimal.ZERO)) {
			r2 = Restrictions.ge(TmsBaseVehicleTypeModel::getVolume, vehicleTypeCheckVO.getVolume());
		}
		if (ObjectUtil.isNotEmpty(vehicleTypeCheckVO.getWeight())&& NumberUtil.isGreater(vehicleTypeCheckVO.getWeight(), BigDecimal.ZERO)) {
			r1 = Restrictions.ge(TmsBaseVehicleTypeModel::getWeight, vehicleTypeCheckVO.getWeight());
		}
		Restriction r3 = Restrictions.eq(TmsBaseVehicleTypeModel::getStatus, StatusConstant.STATUS_ENABLE);
		criteria.setRestriction(Restrictions.and(r1, r2,r3));
		if (ObjectUtil.isEmpty(vehicleTypeCheckVO.getWeight()) || NumberUtil.isLessOrEqual(vehicleTypeCheckVO.getWeight(),BigDecimal.ZERO)) {
			criteria.setOrder(Order.newInstance().asc(new String[]{"volume"}));
		} else {
			criteria.setOrder(Order.newInstance().asc(new String[] { "weight" }));
		}
		List<TmsBaseVehicleTypeModel> tmsBaseVehicleTypeModels = tmsBaseVehicleTypeMapper.findByCriteria(criteria);
		if (ObjectUtil.isNotEmpty(tmsBaseVehicleTypeModels)) {
			vehicleTypeCheckDTO.setId(tmsBaseVehicleTypeModels.get(0).getId());
			vehicleTypeCheckDTO.setCode(tmsBaseVehicleTypeModels.get(0).getCode());
			vehicleTypeCheckDTO.setName(tmsBaseVehicleTypeModels.get(0).getName());
			vehicleTypeCheckDTO.setWeight(tmsBaseVehicleTypeModels.get(0).getWeight());
			vehicleTypeCheckDTO.setVolume(tmsBaseVehicleTypeModels.get(0).getVolume());
		}
		return vehicleTypeCheckDTO;
	}
	/**
	 * 车型资料是否启用
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void whetherEnableVehicleTypeData(VehicleTypeWhetherEnableVO vehicleTypeWhetherEnableVO) throws Exception {
		ToolKits.isParamNull(vehicleTypeWhetherEnableVO, "车型资料是否启用请求不为空");
		ToolKits.isParamNull(vehicleTypeWhetherEnableVO.getVehicleTypeByIds(), "车型ID集不为空");
		ToolKits.isParamNull(vehicleTypeWhetherEnableVO.getStatus(), "状态不为空");

		Assert.isTrue(vehicleTypeWhetherEnableVO.getStatus() == StatusConstant.STATUS_ENABLE || vehicleTypeWhetherEnableVO.getStatus() == StatusConstant.STATUS_DISABLE, "车型状态【" + vehicleTypeWhetherEnableVO.getStatus() + "】错误");

		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		// 当前日期
		Date date = DateUtil.date();

		for (VehicleTypeByIdVO vehicleTypeByIdVO : vehicleTypeWhetherEnableVO.getVehicleTypeByIds()) {
			ToolKits.isParamNull(vehicleTypeByIdVO.getVehicleTypeId(), "车型ID不为空");

			// 根据ID查询车型
			TmsBaseVehicleTypeModel tmsBaseVehicleTypeModel = tmsBaseVehicleTypeMapper.findById(vehicleTypeByIdVO.getVehicleTypeId(), TmsBaseVehicleTypeModel.class);
			ToolKits.isParamNull(tmsBaseVehicleTypeModel, "车型ID【" + vehicleTypeByIdVO.getVehicleTypeId() + "】不存在");

			tmsBaseVehicleTypeModel.setStatus(vehicleTypeWhetherEnableVO.getStatus());
			tmsBaseVehicleTypeModel.setUpdateperson(user.getNickname());
			tmsBaseVehicleTypeModel.setUpdatetime(date);
			tmsBaseVehicleTypeMapper.update(tmsBaseVehicleTypeModel);

			// 停用--清空当前车型的车辆
			if (vehicleTypeWhetherEnableVO.getStatus() == StatusConstant.STATUS_DISABLE) {
				Criteria criteria = Criteria.forClass(TmsBaseVehicleModel.class);
				Restriction r1 = Restrictions.eq("vehicleTypeId", vehicleTypeByIdVO.getVehicleTypeId());
				criteria.setRestriction(r1);

				Map<String, Object> map = Maps.newHashMap();
				map.put("vehicleTypeId", null);
				map.put("vehicleTypeCode", "");
				map.put("vehicleTypeName", "");
				tmsBaseVehicleMapper.updateMapByCriteria(map, criteria);
			}
		}
	}

	/**
	 * 车型资料新增
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void addVehicleTypeData(VehicleTypeAddVO vehicleTypeAddVO) throws Exception {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		ToolKits.isParamNull(vehicleTypeAddVO, "车型资料新增请求不为空");
		ToolKits.isParamNull(vehicleTypeAddVO.getCode(), "车型编码不为空");
		ToolKits.isParamNull(vehicleTypeAddVO.getName(), "车型名称不为空");
		ToolKits.isParamNull(vehicleTypeAddVO.getType(), "车型类别不为空");

		// 判断车型编码是否已存在
		PublicMethods.isThereAnyinformation(TmsBaseVehicleTypeModel.class, "code", vehicleTypeAddVO.getCode(), "enterpriseId", user.getEnterpriseId(), "status", StatusConstant.STATUS_ENABLE, tmsBaseVehicleTypeMapper, "车型编码已存在");
		PublicMethods.isThereAnyinformation(TmsBaseVehicleTypeModel.class, "code", vehicleTypeAddVO.getCode(), "enterpriseId", user.getEnterpriseId(), "status", StatusConstant.STATUS_DISABLE, tmsBaseVehicleTypeMapper, "车型编码已存在，请直接启用");

		// 判断车型名称是否已存在
		PublicMethods.isThereAnyinformation(TmsBaseVehicleTypeModel.class, "name", vehicleTypeAddVO.getName(), "enterpriseId", user.getEnterpriseId(), "status", StatusConstant.STATUS_ENABLE, tmsBaseVehicleTypeMapper, "车型名称已存在");
		PublicMethods.isThereAnyinformation(TmsBaseVehicleTypeModel.class, "name", vehicleTypeAddVO.getName(), "enterpriseId", user.getEnterpriseId(), "status", StatusConstant.STATUS_DISABLE, tmsBaseVehicleTypeMapper, "车型名称已存在，请直接启用");

		// 获取当前账号的顶级部门
		RestMessage<List<Organization>> restMessage = userFeign.search("0", null, null, String.valueOf(user.getEnterpriseId()));
		if (!restMessage.isSuccess()) {
			throw new PrologException("获取部门信息API错误:" + restMessage.getMessage());
		}
		List<Organization> organizations = restMessage.getData();
		ToolKits.isParamNull(organizations, "顶级部门不存在,请先维护部门!");

		// 车型ID
		String vehicleTypeId = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_BASE_VEHICLE_TYPE_ID, "L");
		ToolKits.isParamNull(vehicleTypeId, "车型ID生成失败");

		// 当前日期
		Date date = DateUtil.date();

		// 车型资料对象
		TmsBaseVehicleTypeModel tmsBaseVehicleTypeModel = new TmsBaseVehicleTypeModel();
		BeanUtils.copyProperties(vehicleTypeAddVO, tmsBaseVehicleTypeModel);
		tmsBaseVehicleTypeModel.setId(Long.valueOf(vehicleTypeId));
		tmsBaseVehicleTypeModel.setStatus(StatusConstant.STATUS_ENABLE);
		tmsBaseVehicleTypeModel.setSource(DataDictionaryConstant.SOURCE_ADD);
		tmsBaseVehicleTypeModel.setEnterpriseId(user.getEnterpriseId());
		tmsBaseVehicleTypeModel.setEnterpriseName(user.getEnterpriseName());
		tmsBaseVehicleTypeModel.setCreateperson(user.getNickname());
		tmsBaseVehicleTypeModel.setCreatetime(date);

		tmsBaseVehicleTypeModel.setDepartmentId(organizations.get(0).getId());
		tmsBaseVehicleTypeModel.setDepartmentCode(organizations.get(0).getCode());
		tmsBaseVehicleTypeModel.setDepartmentName(organizations.get(0).getName());
		tmsBaseVehicleTypeMapper.save(tmsBaseVehicleTypeModel);
	}

	/**
	 * 车型资料修改
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void modifyVehicleTypeData(VehicleTypeModifyVO vehicleTypeModifyVO) throws Exception {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");
		ToolKits.isParamNull(vehicleTypeModifyVO, "车型资料新增请求不为空");
		ToolKits.isParamNull(vehicleTypeModifyVO.getId(), "车型ID不为空");
		ToolKits.isParamNull(vehicleTypeModifyVO.getCode(), "车型编码不为空");
		ToolKits.isParamNull(vehicleTypeModifyVO.getName(), "车型名称不为空");
		ToolKits.isParamNull(vehicleTypeModifyVO.getType(), "车型类别不为空");

		// 根据ID查询车型资料
		TmsBaseVehicleTypeModel tmsBaseVehicleTypeModel = tmsBaseVehicleTypeMapper.findById(vehicleTypeModifyVO.getId(), TmsBaseVehicleTypeModel.class);
		ToolKits.isParamNull(tmsBaseVehicleTypeModel, "车型ID【" + vehicleTypeModifyVO.getId() + "】不存在");

		Assert.isTrue(tmsBaseVehicleTypeModel.getStatus() == StatusConstant.STATUS_ENABLE, "车型已停用不能修改");

		BeanUtils.copyProperties(vehicleTypeModifyVO, tmsBaseVehicleTypeModel);
		tmsBaseVehicleTypeModel.setUpdateperson(user.getNickname());
		tmsBaseVehicleTypeModel.setUpdatetime(DateUtil.date());
		tmsBaseVehicleTypeMapper.update(tmsBaseVehicleTypeModel);
	}

	/**
	 * 车型资料弹窗
	 */
	@SuppressWarnings("resource")
	@Override
	public Page<VehicleTypePopupDTO> popupVehicleTypeData(VehicleTypePopupVO vehicleTypePopupVO) {
		ToolKits.isParamNull(vehicleTypePopupVO, "车型资料查询请求不为空");
		ToolKits.isParamNull(vehicleTypePopupVO.getPageNum(), "页码不为空");
		ToolKits.isParamNull(vehicleTypePopupVO.getPageSize(), "页数不为空");

		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		// 相应对象集合
		List<VehicleTypePopupDTO> vehicleTypePopupDTOs = new ArrayList<VehicleTypePopupDTO>();

		// 车型品牌
		List<Map<String, Object>> restMessage1 = sysRefdatadService.getDropDownById(DataDictionaryConstant.VEHICLE_TYPE_BRAND, null, null, null);

		// 车型类别
		List<Map<String, Object>> restMessage2 = sysRefdatadService.getDropDownById(DataDictionaryConstant.VEHICLE_TYPE_CATEGORY, null, null, null);

		// 商品状态
		List<Map<String, Object>> restMessage3 = sysRefdatadService.getDropDownById(DataDictionaryConstant.MAINDATA_STATUS, null, null, null);

		// 分页
		PageUtils.startPage(vehicleTypePopupVO.getPageNum(), vehicleTypePopupVO.getPageSize());

		Criteria criteria = Criteria.forClass(TmsBaseVehicleTypeModel.class);
		Restriction r1 = ToolKits.isEmpty(vehicleTypePopupVO.getVehicleTypeCode()) ? null : Restrictions.like("code", "%" + vehicleTypePopupVO.getVehicleTypeCode() + "%");
		Restriction r2 = ToolKits.isEmpty(vehicleTypePopupVO.getVehicleTypeName()) ? null : Restrictions.like("name", "%" + vehicleTypePopupVO.getVehicleTypeName() + "%");
		Restriction r3 = Restrictions.eq("status", StatusConstant.STATUS_ENABLE);
		Restriction r4 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		criteria.setRestriction(Restrictions.and(r1, r2, r3, r4));
		criteria.setOrder(Order.newInstance().desc(new String[] { "updatetime" }));
		List<TmsBaseVehicleTypeModel> tmsBaseVehicleTypeModels = tmsBaseVehicleTypeMapper.findByCriteria(criteria);

		for (TmsBaseVehicleTypeModel item : tmsBaseVehicleTypeModels) {
			// 响应对象
			VehicleTypePopupDTO vehicleTypePopupDTO = new VehicleTypePopupDTO();
			BeanUtils.copyProperties(item, vehicleTypePopupDTO);
			vehicleTypePopupDTO.setBrandName(PublicMethods.change(restMessage1, String.valueOf(vehicleTypePopupDTO.getBrand())));
			vehicleTypePopupDTO.setTypeName(PublicMethods.change(restMessage2, String.valueOf(vehicleTypePopupDTO.getType())));
			vehicleTypePopupDTO.setStatusName(PublicMethods.change(restMessage3, String.valueOf(vehicleTypePopupDTO.getStatus())));
			vehicleTypePopupDTOs.add(vehicleTypePopupDTO);
		}

		Page<VehicleTypePopupDTO> page = PageUtils.getPage(vehicleTypePopupDTOs);
		if (tmsBaseVehicleTypeModels instanceof com.github.pagehelper.Page) {
			com.github.pagehelper.Page<TmsBaseVehicleTypeModel> p0 = (com.github.pagehelper.Page<TmsBaseVehicleTypeModel>) tmsBaseVehicleTypeModels;
			page.setPageCount(p0.getPages());
			page.setPageNum(p0.getPageNum());
			page.setPageSize(p0.getPageSize());
			page.setTotalCount(p0.getTotal());
			page.setStartRow(p0.getStartRow());
			page.setEndRow(p0.getEndRow());
		}

		return page;
	}

	/**
	 * 车型资料删除
	 *
	 * @param list
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteVehicleTypeData(List<VehicleTypeDeleteVO> list) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		List<Long> ids = list.stream().filter(o -> ToolKits.isNotEmpty(o.getId())).distinct().map(VehicleTypeDeleteVO::getId).collect(Collectors.toList());
		ToolKits.isParamNull(ids, "车型ID不能为空");

		// 车辆修改
		Criteria criteria = Criteria.forClass(TmsBaseVehicleModel.class);
		Restriction r1 = Restrictions.in("vehicleTypeId", ids.toArray());
		criteria.setRestriction(r1);

		Map<String, Object> map = Maps.newHashMap();
		map.put("vehicleTypeId", null);
		map.put("vehicleTypeCode", "");
		map.put("vehicleTypeName", "");
		tmsBaseVehicleMapper.updateMapByCriteria(map, criteria);

		// 车型删除
		tmsBaseVehicleTypeMapper.deleteByIds(ids.toArray(), TmsBaseVehicleTypeModel.class);
	}

	/**
	 * 车型导入
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void batchImportVehicleTypeData(MultipartFile file, String importBatchNumber) throws Exception {
		// 人员权限
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");
		// 导入文件判断
		FileUtils.multipartFileJudge(file);
		// 导入日志对象
		ImportLogAddVO logAddVO = new ImportLogAddVO();
		logAddVO.setImportObjNo(DataDictionaryConstant.VEHICLE_TYPE_IMPORT);
		logAddVO.setImportBatchNumber(importBatchNumber);
		// 导入统计
		int count = 0;
		try {
			// 导入执行
			count = this.importProcess(file, importBatchNumber, user);
			logAddVO.setStatus(DataDictionaryConstant.IMPORT_STATUS_YES);
			logAddVO.setSuccessNum(count);
			logAddVO.setFailNum(0);
			importLogService.addImportLogData(logAddVO);
		} catch (Exception e) {
			Class<VehicleTypeImportVO> importVOClass = VehicleTypeImportVO.class;
			List<VehicleTypeImportVO> importVOs = ExcelUtils.read(file, importVOClass);

			logAddVO.setStatus(DataDictionaryConstant.IMPORT_STATUS_NO);
			logAddVO.setSuccessNum(0);
			logAddVO.setFailNum(importVOs.size());
			logAddVO.setFailReason(e.getMessage());
			// 为了避免导入失败时导入日志的保存事务也被回滚,所以采用消息队列异步保存导入失败的日志
			amqpTemplate.convertAndSend(RabbitMQConstant.VEHICLE_TYPE_IMPORT_LOG, logAddVO);
			e.printStackTrace();
			throw new ParameterException(e.getMessage());
		}
	}

	// 异步保存导入失败日志
	@RabbitListener(queues = RabbitMQConstant.VEHICLE_TYPE_IMPORT_LOG)
	@Transactional(rollbackFor = Exception.class)
	public void saveFailImportLog(ImportLogAddVO logAddVO) {
		try {
			importLogService.addImportLogData(logAddVO);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 车型导入过程
	 *
	 * @param file
	 * @param importBatchNumber
	 * @return
	 */
	public int importProcess(MultipartFile file, String importBatchNumber, UserEntity user) {
		Date date = new Date();

		Properties properties = new Properties();
		// 待转换的对象
		Class<VehicleTypeImportVO> importVOClass = VehicleTypeImportVO.class;
		// 标准模板查询
		List<StandardTemplateDetailsListDTO> standardTemplateDetailsListDTOs = sysImportTemplethService.listStandardTemplateDetailsData(DataDictionaryConstant.VEHICLE_TYPE_IMPORT);
		for (StandardTemplateDetailsListDTO standardTemplateDetailsListDTO : standardTemplateDetailsListDTOs) {
			// 属性字段和注解属性字段值 键值对
			properties.setProperty(standardTemplateDetailsListDTO.getStdColNo(), standardTemplateDetailsListDTO.getCustColName());
		}
		// @ExcelProperty注解属性修改
		ImportUtils.setHeaderValue(properties, importVOClass);

		// EXCEL转对象
		List<VehicleTypeImportVO> vehicleTypeImportVOs = null;
		try {
			vehicleTypeImportVOs = ExcelUtils.read(file, importVOClass);
		} catch (Exception e) {
			e.printStackTrace();

			throw new ParameterException("EXCEL转对象失败:" + e.getMessage());
		}

		ToolKits.isParamNull(vehicleTypeImportVOs, "EXCEL文件内容为空,请重新导入");
		log.info("车型导入详情:{}", JsonMapper.toJson(vehicleTypeImportVOs));

		// 获取当前账号的顶级部门
		RestMessage<List<Organization>> restMessage = userFeign.search("0", null, null, String.valueOf(user.getEnterpriseId()));
		if (!restMessage.isSuccess()) {
			throw new PrologException("获取部门信息API错误:" + restMessage.getMessage());
		}
		List<Organization> organizations = restMessage.getData();
		ToolKits.isParamNull(organizations, "顶级部门不存在,请先维护部门!");

		int i = 1;
		for (VehicleTypeImportVO importVO : vehicleTypeImportVOs) {
			if (ToolKits.isEmpty(importVO.getCode())) {
				throw new PrologException("第" + i + "行导入数据,车型编码不能为空");
			}
			if (ToolKits.isEmpty(importVO.getName())) {
				throw new PrologException("第" + i + "行导入数据,车型名称不能为空");
			}
			if (ToolKits.isEmpty(importVO.getType())) {
				throw new PrologException("第" + i + "行导入数据,类别为必选项");
			}
			i++;
		}
		// 验证导入文件中车型编号是否重复
		Map<String, Long> codeMap = vehicleTypeImportVOs.stream().collect(Collectors.groupingBy(VehicleTypeImportVO::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 = vehicleTypeImportVOs.stream().collect(Collectors.groupingBy(VehicleTypeImportVO::getName, Collectors.counting()));
		for (Map.Entry<String, Long> longEntry : nameMap.entrySet()) {
			if (longEntry.getValue() > 1) {
				throw new ParameterException(String.format("导入文件中，车型名称[%s]重复", longEntry.getKey()));
			}
		}

		i = 0;
		for (VehicleTypeImportVO vo : vehicleTypeImportVOs) {
			// 车型对象
			TmsBaseVehicleTypeModel model = new TmsBaseVehicleTypeModel();
			BeanUtils.copyProperties(vo, model);

			// 车型品牌数据字典
			List<Map<String, Object>> restMessage1 = sysRefdatadService.getDropDownById(DataDictionaryConstant.VEHICLE_TYPE_BRAND, null, null, null);
			if (ToolKits.isNotEmpty(vo.getBrand())) {
				// 车型品牌处理
				if (FileUtils.StringType(vo.getBrand())) {
					// 数据字典code处理
					Assert.notNull(PublicMethods.change(restMessage1, vo.getBrand()), "车型品牌【" + vo.getBrand() + "】不存在");
					model.setBrand(Integer.valueOf(vo.getBrand()));
				} else {
					// 数据字典name处理
					Assert.notNull(PublicMethods.reverseChange(restMessage1, vo.getBrand()), "车型品牌【" + vo.getBrand() + "】不存在");
					model.setBrand(Integer.valueOf(PublicMethods.reverseChange(restMessage1, vo.getBrand())));
				}
			}

			// 车型类别数据字典
			List<Map<String, Object>> restMessage2 = sysRefdatadService.getDropDownById(DataDictionaryConstant.VEHICLE_TYPE_CATEGORY, null, null, null);
			// 车型类别处理
			if (FileUtils.StringType(vo.getType())) {
				// 数据字典code处理
				Assert.notNull(PublicMethods.change(restMessage2, vo.getType()), "车型类别【" + vo.getType() + "】不存在");
				model.setType(Integer.valueOf(vo.getType()));
			} else {
				// 数据字典name处理
				Assert.notNull(PublicMethods.reverseChange(restMessage2, vo.getType()), "车型类别【" + vo.getType() + "】不存在");
				model.setType(Integer.valueOf(PublicMethods.reverseChange(restMessage2, vo.getType())));
			}

			// 判断车型编码是否已存在
			PublicMethods.isThereAnyinformation(TmsBaseVehicleTypeModel.class, "code", vo.getCode(), "enterpriseId", user.getEnterpriseId(), "status", StatusConstant.STATUS_ENABLE, tmsBaseVehicleMapper, "车型编码[" + vo.getCode() + "]已存在");
			PublicMethods.isThereAnyinformation(TmsBaseVehicleTypeModel.class, "code", vo.getCode(), "enterpriseId", user.getEnterpriseId(), "status", StatusConstant.STATUS_DISABLE, tmsBaseVehicleMapper, "车型编码[" + vo.getCode() + "]已停用,请直接启用!");

			// 判断车型名称是否已存在
			PublicMethods.isThereAnyinformation(TmsBaseVehicleTypeModel.class, "name", vo.getName(), "enterpriseId", user.getEnterpriseId(), "status", StatusConstant.STATUS_ENABLE, tmsBaseVehicleMapper, "车型名称[" + vo.getName() + "]已存在");
			PublicMethods.isThereAnyinformation(TmsBaseVehicleTypeModel.class, "name", vo.getName(), "enterpriseId", user.getEnterpriseId(), "status", StatusConstant.STATUS_DISABLE, tmsBaseVehicleMapper, "车型名称[" + vo.getName() + "]已停用,请直接启用!");

			String vechileTypeId = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_BASE_VEHICLE_TYPE_ID, "L");
			ToolKits.isParamNull(vechileTypeId, "车型ID生成失败");

			// 车型对象
			model.setId(Long.valueOf(vechileTypeId));
			model.setImportBatchNumber(importBatchNumber);
			model.setStatus(StatusConstant.STATUS_ENABLE);
			model.setSource(DataDictionaryConstant.SOURCE_EXCEL);
			model.setDepartmentId(organizations.get(0).getId());
			model.setDepartmentCode(organizations.get(0).getCode());
			model.setDepartmentName(organizations.get(0).getName());
			model.setEnterpriseId(user.getEnterpriseId());
			model.setEnterpriseName(user.getEnterpriseName());
			model.setCreatetime(date);
			model.setCreateperson(user.getNickname());
			model.setUpdateperson(user.getNickname());
			model.setUpdatetime(date);
			tmsBaseVehicleTypeMapper.save(model);
			i++;
		}
		return i;
	}

	/**
	 * 车型导入撤销
	 *
	 * @param batchno
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void rollbackData(String batchno) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");
		ToolKits.isParamNull(batchno, "导入批次号不能为空");

		Criteria criteria = Criteria.forClass(TmsBaseVehicleTypeModel.class);
		Restriction r1 = Restrictions.eq("importBatchNumber", batchno);
		criteria.setRestriction(r1);
		List<TmsBaseVehicleTypeModel> tmsBaseVehicleTypeModels = tmsBaseVehicleTypeMapper.findByCriteria(criteria);
		if (ToolKits.isEmpty(tmsBaseVehicleTypeModels)) {
			throw new RuntimeException("批次号[" + batchno + "]错误,查询为空!");
		}

		List<Long> ids = tmsBaseVehicleTypeModels.stream().filter(o -> ToolKits.isNotEmpty(o.getId())).distinct().map(TmsBaseVehicleTypeModel::getId).collect(Collectors.toList());

		// 车辆修改
		criteria = Criteria.forClass(TmsBaseVehicleModel.class);
		r1 = Restrictions.in("vehicleTypeId", ids.toArray());
		criteria.setRestriction(r1);

		Map<String, Object> map = Maps.newHashMap();
		map.put("vehicleTypeId", "");
		map.put("vehicleTypeCode", "");
		map.put("vehicleTypeName", "");
		tmsBaseVehicleMapper.updateMapByCriteria(map, criteria);

		// 车型删除
		tmsBaseVehicleTypeMapper.deleteByIds(ids.toArray(), TmsBaseVehicleTypeModel.class);
	}

	/**
	 * 车型导入分页查询
	 */
	@SuppressWarnings("resource")
	@Override
	public RestMessage<Object> pageVehicleTypeByImportBatchNumberData(ImportPageVO importPageVO) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		// 相应对象集合
		List<VehicleTypeImportPageDTO> vehicleTypeImportPageDTOs = new ArrayList<VehicleTypeImportPageDTO>();

		// 车型品牌
		List<Map<String, Object>> restMessage1 = sysRefdatadService.getDropDownById(DataDictionaryConstant.VEHICLE_TYPE_BRAND, null, null, null);

		// 车型类别
		List<Map<String, Object>> restMessage2 = sysRefdatadService.getDropDownById(DataDictionaryConstant.VEHICLE_TYPE_CATEGORY, null, null, null);

		// 车型状态
		List<Map<String, Object>> restMessage3 = sysRefdatadService.getDropDownById(DataDictionaryConstant.MAINDATA_STATUS, null, null, null);

		// 分页
		PageUtils.startPage(importPageVO.getPageNum(), importPageVO.getPageSize());

		Criteria criteria = Criteria.forClass(TmsBaseVehicleTypeModel.class);
		Restriction r1 = Restrictions.eq("importBatchNumber", importPageVO.getImportBatchNumber());
		Restriction r2 = Restrictions.eq("source", DataDictionaryConstant.SOURCE_EXCEL);
		Restriction r3 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		criteria.setRestriction(Restrictions.and(r1, r2, r3));
		criteria.setOrder(Order.newInstance().desc(new String[] { "updatetime" }));
		List<TmsBaseVehicleTypeModel> tmsBaseVehicleTypeModels = tmsBaseVehicleTypeMapper.findByCriteria(criteria);
		for (TmsBaseVehicleTypeModel item : tmsBaseVehicleTypeModels) {
			// 响应对象
			VehicleTypeImportPageDTO vehicleTypeImportPageDTO = new VehicleTypeImportPageDTO();
			BeanUtils.copyProperties(item, vehicleTypeImportPageDTO);
			vehicleTypeImportPageDTO.setBrandName(PublicMethods.change(restMessage1, String.valueOf(vehicleTypeImportPageDTO.getBrand())));
			vehicleTypeImportPageDTO.setTypeName(PublicMethods.change(restMessage2, String.valueOf(vehicleTypeImportPageDTO.getType())));
			vehicleTypeImportPageDTO.setStatusName(PublicMethods.change(restMessage3, String.valueOf(vehicleTypeImportPageDTO.getStatus())));
			vehicleTypeImportPageDTOs.add(vehicleTypeImportPageDTO);
		}

		Page<VehicleTypeImportPageDTO> page = PageUtils.getPage(vehicleTypeImportPageDTOs);
		if (tmsBaseVehicleTypeModels instanceof com.github.pagehelper.Page) {
			com.github.pagehelper.Page<TmsBaseVehicleTypeModel> p0 = (com.github.pagehelper.Page<TmsBaseVehicleTypeModel>) tmsBaseVehicleTypeModels;
			page.setPageCount(p0.getPages());
			page.setPageNum(p0.getPageNum());
			page.setPageSize(p0.getPageSize());
			page.setTotalCount(p0.getTotal());
			page.setStartRow(p0.getStartRow());
			page.setEndRow(p0.getEndRow());
		}

		return RestMessage.newInstance(true, "查询成功", page);
	}

	/**
	 * 根据车型名称查看车型资料
	 *
	 * @param vehicleTypeCheckVO
	 * @return
	 */
	public VehicleTypeCheckDTO getVehicleTypeByNameData(VehicleTypeCheckVO vehicleTypeCheckVO) {
		ToolKits.isParamNull(vehicleTypeCheckVO, "车型资料查看请求不为空");
		ToolKits.isParamNull(vehicleTypeCheckVO.getVehicleTypeName(), "车型名称不为空");

		Criteria criteria = Criteria.forClass(TmsBaseVehicleTypeModel.class);
		Restriction r1 = Restrictions.eq(TmsBaseVehicleTypeModel::getName, vehicleTypeCheckVO.getVehicleTypeName());
		criteria.setRestriction(Restrictions.and(r1));
		List<TmsBaseVehicleTypeModel> tmsBaseVehicleTypeModels = tmsBaseVehicleTypeMapper.findByCriteria(criteria);

		if (tmsBaseVehicleTypeModels.size() == 0) {
			throw new ParameterException("车型【" + vehicleTypeCheckVO.getVehicleTypeName() + "】数据不存在，查询失败");
		} else if (tmsBaseVehicleTypeModels.size() > 1) {
			throw new ParameterException("车型【" + vehicleTypeCheckVO.getVehicleTypeName() + "】存在重复数据，查询失败");
		}

		// 车型品牌
		List<Map<String, Object>> restMessage1 = sysRefdatadService.getDropDownById(DataDictionaryConstant.VEHICLE_TYPE_BRAND, null, null, null);

		// 车型类别
		List<Map<String, Object>> restMessage2 = sysRefdatadService.getDropDownById(DataDictionaryConstant.VEHICLE_TYPE_CATEGORY, null, null, null);

		// 车型资料对象
		TmsBaseVehicleTypeModel tmsBaseVehicleTypeModel = tmsBaseVehicleTypeModels.get(0);

		// 响应对象
		VehicleTypeCheckDTO vehicleTypeCheckDTO = new VehicleTypeCheckDTO();
		BeanUtils.copyProperties(tmsBaseVehicleTypeModel, vehicleTypeCheckDTO);
		vehicleTypeCheckDTO.setBrandName(PublicMethods.change(restMessage1, String.valueOf(vehicleTypeCheckDTO.getBrand())));
		vehicleTypeCheckDTO.setTypeName(PublicMethods.change(restMessage2, String.valueOf(vehicleTypeCheckDTO.getType())));

		return vehicleTypeCheckDTO;
	}

}
