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

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

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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.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.framework.entity.UserEntity;
import com.prolog.product.core.framework.util.PlgFxUsrUtils;
import com.prolog.rdc.tms.constant.BussinessConstant;
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.TmsTransferStationMapper;
import com.prolog.rdc.tms.model.dto.SysRefdatadDTO;
import com.prolog.rdc.tms.model.dto.basicData.TmsTransferStationByViewDTO;
import com.prolog.rdc.tms.model.dto.basicData.TmsTransferStationDTO;
import com.prolog.rdc.tms.model.dto.basicData.TmsTransferStationParsingDTO;
import com.prolog.rdc.tms.model.entity.line.TmsTransferStationModel;
import com.prolog.rdc.tms.model.vo.SysRefdatadQueryVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsTransferStationByQueryVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsTransferStationParsingVO;
import com.prolog.rdc.tms.model.vo.basicData.TmsTransferStationVO;
import com.prolog.rdc.tms.model.vo.basicData.TransferStationDeleteVO;
import com.prolog.rdc.tms.model.vo.basicData.TransferStationDisableVO;
import com.prolog.rdc.tms.model.vo.basicData.TransferStationEnableVO;
import com.prolog.rdc.tms.service.SysCodeengineService;
import com.prolog.rdc.tms.service.SysRefdatadService;
import com.prolog.rdc.tms.service.basicData.TransferStationService;
import com.prolog.rdc.tms.util.PublicMethods;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;

/**
 * 
 *
 * 基础数据-中转站管理实现层
 *
 * @className :TransferStationServiceImpl
 * @author :zhangsj
 * @creationTime :2022/03/31
 * @description :
 *
 * @modifier :zhangsj
 * @modifyTime :2022/03/31
 * @reviseRemarks:
 *
 * @version :1.0.0
 *
 */
@Service
public class TransferStationServiceImpl implements TransferStationService {

	@Autowired
	private TmsTransferStationMapper tmsTransferStationMapper;

	@Autowired
	private SysCodeengineService sysCodeengineService;

	@Autowired
	private SysRefdatadService sysRefdatadService;

	/**
	 * 中转站分页查询
	 * 
	 * @param vo
	 * @return
	 */
	@SuppressWarnings("resource")
	@Override
	public Page<TmsTransferStationDTO> query(TmsTransferStationByQueryVO vo) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "没有操作权限！");

		ToolKits.isParamNull(vo, "参数不能为空！");
		ToolKits.isParamNull(vo.getPageNum(), "当前页码不能为空");
		ToolKits.isParamNull(vo.getPageSize(), "每页条数不能为空");

		// 状态
		List<Map<String, Object>> restMessage = sysRefdatadService.getDropDownById(DataDictionaryConstant.MAINDATA_STATUS, null, null, null);
		// 类型
		List<Map<String, Object>> restMessage1 = sysRefdatadService.getDropDownById(DataDictionaryConstant.TRANSFER_STATION_TYPE, null, null, null);

		Criteria criteria = Criteria.forClass(TmsTransferStationModel.class);
		Restriction r1 = ToolKits.isEmpty(vo.getName()) ? null : Restrictions.like("name", "%" + vo.getName() + "%");
		Restriction r2 = ToolKits.isEmpty(vo.getCode()) ? null : Restrictions.like("code", "%" + vo.getCode() + "%");
		Restriction r3 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		Restriction r4 = null;
		Restriction r5 = null;
		// 自有账号 权限控制
		if (ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_ZY)) {
			r4 = Restrictions.in("departmentId", user.getDepts().stream().toArray(String[]::new));
		} else {
			r4 = Restrictions.in("departmentId", user.getDepts().stream().toArray(String[]::new));
			// 仓库
			r5 = Restrictions.in(TmsTransferStationModel::getBranchId, user.getWarehouses().toArray());
		}

		criteria.setRestriction(Restrictions.and(r1, r2, r3, r4, r5));
		criteria.setOrder(Order.newInstance().desc(new String[] { "updatetime" }));
		PageUtils.startPage(vo.getPageNum(), vo.getPageSize());
		List<TmsTransferStationModel> tmsTransferStationModels = tmsTransferStationMapper.findByCriteria(criteria);

		List<TmsTransferStationDTO> dtoList = Lists.newArrayList();
		for (TmsTransferStationModel tmsTransferStationModel : tmsTransferStationModels) {
			TmsTransferStationDTO dto = new TmsTransferStationDTO();
			BeanUtils.copyProperties(tmsTransferStationModel, dto);
			dto.setStatusName(PublicMethods.change(restMessage, String.valueOf(dto.getStatus())));
			dto.setTypeName(PublicMethods.change(restMessage1, String.valueOf(dto.getType())));
			dtoList.add(dto);
		}

		Page<TmsTransferStationDTO> page = PageUtils.getPage(dtoList);
		if (tmsTransferStationModels instanceof com.github.pagehelper.Page) {
			com.github.pagehelper.Page<TmsTransferStationModel> p0 = (com.github.pagehelper.Page<TmsTransferStationModel>) tmsTransferStationModels;
			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 vo
	 * @return
	 */
	@Override
	public TmsTransferStationByViewDTO view(TmsTransferStationVO vo) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "没有操作权限！");
		ToolKits.isParamNull(vo.getId(), "参数不能为空！");

		TmsTransferStationModel model = tmsTransferStationMapper.findById(vo.getId(), TmsTransferStationModel.class);
		ToolKits.isParamNull(model, "中转站ID[" + vo.getId() + "]错误,查询为空！");

		TmsTransferStationByViewDTO dto = new TmsTransferStationByViewDTO();
		BeanUtils.copyProperties(model, dto);

		SysRefdatadQueryVO sysrefdatadqueryvo = new SysRefdatadQueryVO();
		// 需要查询的参数
		String[] objectcodes = { DataDictionaryConstant.TRANSFER_STATION_TYPE, DataDictionaryConstant.MAINDATA_STATUS };
		sysrefdatadqueryvo.setObjectcodes(objectcodes);
		// 执行查询
		List<SysRefdatadDTO> sysrefdataddtos = new ArrayList<SysRefdatadDTO>();
		try {
			sysrefdataddtos = sysRefdatadService.getSysRefdatadData(sysrefdatadqueryvo);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ParameterException("获取数据字典失败");
		}
		if (ToolKits.isNotEmpty(sysrefdataddtos)) {
			for (SysRefdatadDTO sysrefdataddto : sysrefdataddtos) {
				// 运单类型翻译
				if (DataDictionaryConstant.MAINDATA_STATUS.equals(sysrefdataddto.getObjectcode()) && sysrefdataddto.getCode().equals(dto.getStatus().toString())) {
					dto.setStatusName(sysrefdataddto.getName());
				}
				if (DataDictionaryConstant.TRANSFER_STATION_TYPE.equals(sysrefdataddto.getObjectcode()) && sysrefdataddto.getCode().equals(dto.getType().toString())) {
					dto.setTypeName(sysrefdataddto.getName());
				}
			}
		}

		return dto;
	}

	/**
	 * 中转站修改
	 * 
	 * @param vo
	 */
	@Override
	public void update(TmsTransferStationVO vo) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "没有操作权限！");
		ToolKits.isParamNull(vo, "参数不能为空！");
		ToolKits.isParamNull(vo.getId(), "中转站ID不能为空！");
		ToolKits.isParamNull(vo.getStatus(), "状态不能为空");
		ToolKits.isParamNull(vo.getType(), "类型不能为空");

		TmsTransferStationModel model = tmsTransferStationMapper.findById(vo.getId(), TmsTransferStationModel.class);
		ToolKits.isParamNull(model, "中转站ID[" + vo.getId() + "]错误,查询为空！");

		BeanUtils.copyProperties(vo, model);
		model.setUpdateperson(user.getNickname());
		model.setUpdatetime(DateUtils.nowDate());
		tmsTransferStationMapper.update(model);
	}

	/**
	 * 中转站新增
	 * 
	 * @param vo
	 */
	@Override
	public void save(TmsTransferStationVO vo) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "没有操作权限！");

		ToolKits.isParamNull(vo, "参数不能为空！");
		ToolKits.isParamNull(vo.getCode(), "中转站编码不能为空");
		ToolKits.isParamNull(vo.getName(), "中转站名称不能为空");
		ToolKits.isParamNull(vo.getStatus(), "状态不能为空");
		ToolKits.isParamNull(vo.getType(), "类型不能为空");

		// 权限控制
		if (!ObjectUtil.equal(user.getUserType(), BussinessConstant.USER_TYPE_ZY)) {// 自有账号
			throw new PrologException("当前人员没有操作权限！");
		}

		Map<String, Object> map = Maps.newHashMap();
		map.put("code", vo.getCode());
		map.put("enterpriseId", user.getEnterpriseId());
		map.put("status", StatusConstant.STATUS_ENABLE);

		Map<String, Object> map2 = Maps.newHashMap();
		map2.put("name", vo.getName());
		map2.put("enterpriseId", user.getEnterpriseId());
		map2.put("status", StatusConstant.STATUS_ENABLE);

		// 判断中转站编码/名称 是否已存在
		PublicMethods.doesItExistByMap(tmsTransferStationMapper, map, TmsTransferStationModel.class, "编码【" + vo.getCode() + "】已存在");
		PublicMethods.doesItExistByMap(tmsTransferStationMapper, map2, TmsTransferStationModel.class, "名称【" + vo.getName() + "】已存在");

		// 判断中转站编码/名称 是否已停用
		map.put("status", StatusConstant.STATUS_DISABLE);
		map2.put("status", StatusConstant.STATUS_DISABLE);
		PublicMethods.doesItExistByMap(tmsTransferStationMapper, map, TmsTransferStationModel.class, "编码【" + vo.getCode() + "】已停用,请直接启用");
		PublicMethods.doesItExistByMap(tmsTransferStationMapper, map2, TmsTransferStationModel.class, "名称【" + vo.getName() + "】已停用,请直接启用");

		// 获取中转站ID
		String id = sysCodeengineService.getCodeNumberByCode(SeriaNnumberConstant.TMS_TRANSFER_STATION_ID, "L");
		ToolKits.isParamNull(id, "获取中转站ID失败！");

		TmsTransferStationModel model = new TmsTransferStationModel();
		BeanUtils.copyProperties(vo, model);

		model.setId(Long.valueOf(id));
		model.setCreateperson(user.getNickname());
		model.setCreatetime(DateUtils.nowDate());
		model.setUpdateperson(user.getNickname());
		model.setUpdatetime(DateUtils.nowDate());

		model.setDepartmentCode(vo.getDepartmentCode());
		model.setDepartmentName(vo.getDepartmentName());
		model.setEnterpriseId(user.getEnterpriseId());
		model.setEnterpriseName(user.getEnterpriseName());

		tmsTransferStationMapper.save(model);

	}

	/**
	 * 中转站资料停用
	 * 
	 * @param list
	 */
	@Override
	public void disableData(List<TransferStationDisableVO> transferStationDisableVOs) {
		ToolKits.isParamNull(transferStationDisableVOs, "中转站停用请求不为空");

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

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

		Criteria criteria = Criteria.forClass(TmsTransferStationModel.class);
		Restriction r1 = Restrictions.in("id", ids.toArray());
		criteria.setRestriction(r1);

		Map<String, Object> map = Maps.newHashMap();
		map.put("status", StatusConstant.STATUS_DISABLE);
		map.put("updatetime", DateUtil.date());
		map.put("updateperson", user.getNickname());

		tmsTransferStationMapper.updateMapByCriteria(map, criteria);
	}

	/**
	 * 中转站资料启用
	 * 
	 * @param transferStationEnableVOs
	 */
	@Override
	public void enableData(List<TransferStationEnableVO> transferStationEnableVOs) {
		ToolKits.isParamNull(transferStationEnableVOs, "中转站启用请求不为空");

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

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

		Criteria criteria = Criteria.forClass(TmsTransferStationModel.class);
		Restriction r1 = Restrictions.in("id", ids.toArray());
		criteria.setRestriction(r1);

		Map<String, Object> map = Maps.newHashMap();
		map.put("status", StatusConstant.STATUS_ENABLE);
		map.put("updatetime", DateUtil.date());
		map.put("updateperson", user.getNickname());

		tmsTransferStationMapper.updateMapByCriteria(map, criteria);
	}

	/**
	 * 中转站资料删除
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteData(List<TransferStationDeleteVO> transferStationDeleteVOs) {
		ToolKits.isParamNull(transferStationDeleteVOs, "中转站删除请求不为空");

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

		ToolKits.isParamNull(ids, "中转站ID不能为空");

		tmsTransferStationMapper.deleteByIds(ids.toArray(), TmsTransferStationModel.class);
	}

	/**
	 * 地图解析
	 * 
	 * @param vo
	 */
	@Override
	public void parsing(TmsTransferStationParsingVO vo) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "没有操作权限！");
		ToolKits.isParamNull(vo.getId(), "中转站ID不能为空");
		TmsTransferStationModel model = tmsTransferStationMapper.findById(vo.getId(), TmsTransferStationModel.class);
		ToolKits.isParamNull(model, "中转站ID[" + vo.getId() + "]有误");

		// 重新设置经纬度和地址详情
		model.setLatitude(vo.getLatitude());
		model.setLongitude(vo.getLongitude());
		model.setAddress(vo.getAddress());

		tmsTransferStationMapper.update(model);

	}

	/**
	 * 地图解析查询
	 * 
	 * @param vo
	 * @return
	 */
	@Override
	public Page<TmsTransferStationParsingDTO> parsingPage(TmsTransferStationParsingVO vo) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "没有操作权限！");
		ToolKits.isParamNull(vo.getPageNum(), "当前页码不能为空");
		ToolKits.isParamNull(vo.getPageSize(), "每页条数不能为空");
		ToolKits.isParamNull(vo, "参数不能为空！");

		Criteria criteria = Criteria.forClass(TmsTransferStationModel.class);
		Restriction r1 = ToolKits.isEmpty(vo.getIds()) ? null : Restrictions.in("id", vo.getIds().toArray());
		Restriction r2 = ToolKits.isEmpty(vo.getSearch()) ? null : Restrictions.like("name", "%" + vo.getSearch() + "%");
		criteria.setRestriction(Restrictions.and(r1, r2));

		PageUtils.startPage(vo.getPageNum(), vo.getPageSize());
		List<TmsTransferStationModel> tmsTransferStationModels = tmsTransferStationMapper.findByCriteria(criteria);

		List<TmsTransferStationParsingDTO> dtoList = Lists.newArrayList();
		for (TmsTransferStationModel model : tmsTransferStationModels) {
			TmsTransferStationParsingDTO dto = new TmsTransferStationParsingDTO();
			BeanUtils.copyProperties(model, dto);
			dtoList.add(dto);
		}
		Page<TmsTransferStationParsingDTO> page = PageUtils.getPage(dtoList);

		return page;
	}
}
