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

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.CollectionUtil;
import com.prolog.rdc.tms.model.vo.ImportLogUpdateVO;
import com.prolog.rdc.tms.service.fleetManagement.ContainerService;
import com.prolog.rdc.tms.service.fleetManagement.DeviceService;
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.prolog.common.util.ToolKits;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.exception.ParameterException;
import com.prolog.framework.core.pojo.Page;
import com.prolog.framework.core.restriction.Criteria;
import com.prolog.framework.core.restriction.FieldSelector;
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.DataDictionaryConstant;
import com.prolog.rdc.tms.dao.mapper.SysImportLogMapper;
import com.prolog.rdc.tms.model.dto.basicConfigure.ImportLogPageDTO;
import com.prolog.rdc.tms.model.dto.basicConfigure.SysImportTemplethQueryHdDTO;
import com.prolog.rdc.tms.model.entity.SysImportLogModel;
import com.prolog.rdc.tms.model.vo.basicConfigure.ImportDataCheckPageVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.ImportLogAddVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.ImportLogPageVO;
import com.prolog.rdc.tms.model.vo.basicConfigure.ImportPageVO;
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.basicData.BranchService;
import com.prolog.rdc.tms.service.basicData.CarriersService;
import com.prolog.rdc.tms.service.basicData.CustomerService;
import com.prolog.rdc.tms.service.basicData.ItemCategoryService;
import com.prolog.rdc.tms.service.basicData.ItemService;
import com.prolog.rdc.tms.service.basicData.ProviderService;
import com.prolog.rdc.tms.service.basicData.TranslineService;
import com.prolog.rdc.tms.service.fleetManagement.DeliverymanService;
import com.prolog.rdc.tms.service.fleetManagement.DriverService;
import com.prolog.rdc.tms.service.fleetManagement.VehicleService;
import com.prolog.rdc.tms.service.fleetManagement.VehicleTypeService;
import com.prolog.rdc.tms.util.PublicMethods;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;

/**
 *
 *
 * 日志管理-导入日志实现层
 *
 * @className :ImportLogServiceImpl
 * @author :kh
 * @creationTime :2022/04/24
 * @description :
 *
 * @modifier :kh
 * @modifyTime :2022/04/24
 * @reviseRemarks:
 *
 * @version :1.0.0
 *
 */
@Service
public class ImportLogServiceImpl implements ImportLogService {

	@Autowired
	private SysImportLogMapper sysImportLogMapper;

	@Autowired
	private SysImportTemplethService sysImportTemplethService;

	@Autowired
	private SysRefdatadService sysRefdatadService;

	@Autowired
	private ItemService baseItemService;

	@Autowired
	private ItemCategoryService baseItemCategoryService;

	@Autowired
	private ProviderService providerService;

	@Autowired
	private BranchService tmsBaseBranchService;

	@Autowired
	private TranslineService tmsBaseTranslineService;

	@Autowired
	private CustomerService customerService;

	@Autowired
	private CarriersService carriersService;

	@Autowired
	private DriverService driverService;

	@Autowired
	private DeliverymanService deliverymanService;

	@Autowired
	private VehicleTypeService vehicleTypeService;

	@Autowired
	private VehicleService vehicleService;

	@Autowired
	private DeviceService deviceService;

	@Autowired
	private ContainerService containerService;

	/**
	 * 导入日志分页查询
	 */
	@SuppressWarnings("resource")
	@Override
	public Page<ImportLogPageDTO> pageImportLogData(ImportLogPageVO importLogPageVO) {
		ToolKits.isParamNull(importLogPageVO, "导入日志分页查询请求不为空");
		ToolKits.isParamNull(importLogPageVO.getPageNum(), "页码不为空");
		ToolKits.isParamNull(importLogPageVO.getPageSize(), "页码数量不为空");

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

		// 响应集合
		List<ImportLogPageDTO> importLogPageDTOs = new ArrayList<ImportLogPageDTO>();

		// 导入状态
		List<Map<String, Object>> restMessage1 = sysRefdatadService.getDropDownById(DataDictionaryConstant.IMPORT_STATUS, null, null, null);
		// 操作状态
		List<Map<String, Object>> restMessage2 = sysRefdatadService.getDropDownById(DataDictionaryConstant.OPERATE_STATUS, null, null, null);

		Criteria criteria = Criteria.forClass(SysImportLogModel.class);
		Restriction r1 = ToolKits.isEmpty(importLogPageVO.getImportObjName()) ? null : Restrictions.like("importObjName", "%" + importLogPageVO.getImportObjName() + "%");
		Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		criteria.setRestriction(Restrictions.and(r1, r2));
		criteria.setOrder(Order.newInstance().desc(new String[] { "importTime" }));
		PageUtils.startPage(importLogPageVO.getPageNum(), importLogPageVO.getPageSize());
		List<SysImportLogModel> sysImportLogModels = sysImportLogMapper.findByCriteria(criteria);
		for (SysImportLogModel sysImportLogModel : sysImportLogModels) {
			ImportLogPageDTO importLogPageDTO = new ImportLogPageDTO();
			BeanUtils.copyProperties(sysImportLogModel, importLogPageDTO);
			importLogPageDTO.setStatusName(PublicMethods.change(restMessage1, String.valueOf(importLogPageDTO.getStatus())));
			importLogPageDTO.setOperateStatusName(PublicMethods.change(restMessage2, String.valueOf(importLogPageDTO.getOperateStatus())));

			importLogPageDTOs.add(importLogPageDTO);
		}

		Page<ImportLogPageDTO> page = PageUtils.getPage(importLogPageDTOs);
		if (sysImportLogModels instanceof com.github.pagehelper.Page) {
			com.github.pagehelper.Page<SysImportLogModel> p0 = (com.github.pagehelper.Page<SysImportLogModel>) sysImportLogModels;
			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 void addImportLogData(ImportLogAddVO importLogAddVO) {
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		// 查询对象信息
		SysImportTemplethQueryHdDTO templeteh = sysImportTemplethService.queryTempleteh(importLogAddVO.getImportObjNo(), user.getEnterpriseId());

		// 当前时间
		Date date = DateUtil.date();

		SysImportLogModel sysImportLogModel = new SysImportLogModel();
		BeanUtil.copyProperties(importLogAddVO, sysImportLogModel);
		sysImportLogModel.setId(ToolKits.getUUID());
		sysImportLogModel.setImportUserId(user.getUserid());
		sysImportLogModel.setImportUserName(user.getNickname());
		sysImportLogModel.setImportTime(date);
		sysImportLogModel.setTempleteName(templeteh.getTempleteName());
		sysImportLogModel.setPhoneNumber(sysImportLogModel.getPhoneNumber());
		sysImportLogModel.setImportObjName(templeteh.getImportObjName());
		sysImportLogModel.setOperateStatus(DataDictionaryConstant.OPERATE_STATUS_IMPORT);
		sysImportLogModel.setEnterpriseId(user.getEnterpriseId());
		sysImportLogModel.setEnterpriseName(user.getEnterpriseName());
		sysImportLogModel.setCreateperson(user.getNickname());
		sysImportLogModel.setCreatetime(date);
		sysImportLogModel.setUpdateperson(user.getNickname());
		sysImportLogModel.setUpdatetime(date);
		sysImportLogMapper.save(sysImportLogModel);
	}

	/**
	 * 导入日志更新
	 * @param updateVO
	 */
	@Override
	public void updateImportLogData(ImportLogUpdateVO updateVO) {
		Criteria criteria = Criteria.forClass(SysImportLogModel.class);
		Restriction r1 = Restrictions.eq("importBatchNumber", updateVO.getImportBatchNumber());
		criteria.setRestriction(Restrictions.and(r1));
		List<SysImportLogModel> importLogModels = sysImportLogMapper.findByCriteria(criteria);
		if (CollectionUtil.isNotEmpty(importLogModels)) {
			SysImportLogModel sysImportLogModel = importLogModels.get(0);
			sysImportLogModel.setStatus(updateVO.getStatus());
			sysImportLogModel.setSuccessNum(updateVO.getSuccessNum());
			sysImportLogModel.setFailNum(updateVO.getFailNum());
			sysImportLogModel.setUpdatetime(new Date());
			sysImportLogModel.setFailReason(updateVO.getFailReason());
			sysImportLogMapper.update(sysImportLogModel);
		}
	}

	/**
	 * 撤销导入数据
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 * @throws @date     2022/1/13 11:54
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void revokeData(String id) throws Exception {
		// 人员权限
		UserEntity user = PlgFxUsrUtils.getUserEntity();
		ToolKits.isParamNull(user, "当前人员没有操作权限");

		// 查询导入对象
		Criteria criteria = Criteria.forClass(SysImportLogModel.class);
		Restriction r1 = Restrictions.eq("id", id);
		Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
		Restriction r3 = Restrictions.eq("status", DataDictionaryConstant.IMPORT_STATUS_YES);
		Restriction r4 = Restrictions.eq("operateStatus", DataDictionaryConstant.OPERATE_STATUS_IMPORT);
		criteria.setRestriction(Restrictions.and(r1, r2, r3, r4));
		List<SysImportLogModel> importLogModels = sysImportLogMapper.findByCriteria(criteria);
		ToolKits.isParamNull(importLogModels, "导入日志不存在或已经撤销");

		// 导入对象
		SysImportLogModel importLogModel = importLogModels.get(0);

		switch (String.valueOf(importLogModel.getImportObjNo())) {
		case DataDictionaryConstant.ITEM_IMPORT:
			baseItemService.rollbackData(importLogModel.getImportBatchNumber());
			break;
		case DataDictionaryConstant.ITEM_CATEGORY_IMPORT:
			baseItemCategoryService.rollbackData(importLogModel.getImportBatchNumber());
			break;
		case DataDictionaryConstant.PROVIDER_IMPORT:
			providerService.rollbackData(importLogModel.getImportBatchNumber());
			break;
		case DataDictionaryConstant.PROVIDER_SHIPPER_IMPORT:
			providerService.rollbackShipperData(importLogModel.getImportBatchNumber());
			break;
		case DataDictionaryConstant.CUSTOMER_IMPORT:
			customerService.rollbackData(importLogModel.getImportBatchNumber());
			break;
		case DataDictionaryConstant.CUSTOMER_CONSIGNEE_IMPORT:
			customerService.rollbackByCustomerReceiverData(importLogModel.getImportBatchNumber());
			break;
		case DataDictionaryConstant.BRANCH_IMPORT:
			tmsBaseBranchService.rollbackData(importLogModel.getImportBatchNumber());
			break;
		case DataDictionaryConstant.BRANCH_PARKING_SPACE_IMPORT:
			tmsBaseBranchService.rollbackCarportData(importLogModel.getImportBatchNumber());
			break;
		case DataDictionaryConstant.CARRIER_IMPORT:
			carriersService.rollbackData(importLogModel.getImportBatchNumber());
			break;
		case DataDictionaryConstant.LINE_IMPORT:
			tmsBaseTranslineService.rollbackData(importLogModel.getImportBatchNumber());
			break;
		case DataDictionaryConstant.LINE_CARRIER_IMPORT:
			tmsBaseTranslineService.rollbackCarrierData(importLogModel.getImportBatchNumber());
			break;
		case DataDictionaryConstant.LINE_CONSIGNEE_IMPORT:
			tmsBaseTranslineService.rollbackConsigneeData(importLogModel.getImportBatchNumber());
			break;
		case DataDictionaryConstant.DRIVER_IMPORT:
			driverService.rollbackData(importLogModel.getImportBatchNumber());
			break;
		case DataDictionaryConstant.DELIVERYMAN_IMPORT:
			deliverymanService.rollbackData(importLogModel.getImportBatchNumber());
			break;
		case DataDictionaryConstant.VEHICLE_TYPE_IMPORT:
			vehicleTypeService.rollbackData(importLogModel.getImportBatchNumber());
			break;
		case DataDictionaryConstant.VEHICLE_IMPORT:
			vehicleService.rollbackData(importLogModel.getImportBatchNumber());
			break;
		case DataDictionaryConstant.DEVICE_IMPORT:
			deviceService.rollbackData(importLogModel.getImportBatchNumber());
			break;
		case DataDictionaryConstant.CONTAINER_IMPORT:
			containerService.rollbackData(importLogModel.getImportBatchNumber());
			break;
		default:
			throw new ParameterException("导入对象标识错误");
		}

		SysImportLogModel updateModel = new SysImportLogModel();
		updateModel.setOperateStatus(DataDictionaryConstant.OPERATE_STATUS_REVOKE);
		updateModel.setUpdateperson(user.getNickname());
		updateModel.setUpdatetime(new Date());

		// 指定更新字段
		FieldSelector field = FieldSelector.newInstance().include(new String[] { "operateStatus", "updatetime", "updateperson" });

		Criteria updateCriteria = Criteria.forClass(SysImportLogModel.class);
		updateCriteria.setRestriction(Restrictions.eq("id", id));
		sysImportLogMapper.updateFieldsByCriteria(updateModel, field, updateCriteria);
	}

	/**
	 * 导入数据查看
	 */
	@Override
	public RestMessage<Object> pageImportdCheckData(ImportDataCheckPageVO ImportDataCheckPageVO) {
		ToolKits.isParamNull(ImportDataCheckPageVO, "导入数据查看请求不为空");
		ToolKits.isParamNull(ImportDataCheckPageVO.getImportBatchNumber(), "导入批次号不为空");
		ToolKits.isParamNull(ImportDataCheckPageVO, "导入对象编码不为空");
		ToolKits.isParamNull(ImportDataCheckPageVO, "页码不为空");
		ToolKits.isParamNull(ImportDataCheckPageVO, "页数不为空");

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

		// 查询VO
		ImportPageVO importPageVO = new ImportPageVO();
		importPageVO.setImportBatchNumber(ImportDataCheckPageVO.getImportBatchNumber());
		importPageVO.setPageNum(ImportDataCheckPageVO.getPageNum());
		importPageVO.setPageSize(ImportDataCheckPageVO.getPageSize());

		// 响应对象
		RestMessage<Object> restMessage = null;
		switch (String.valueOf(ImportDataCheckPageVO.getImportObjNo())) {
		case DataDictionaryConstant.ITEM_IMPORT:
			restMessage = baseItemService.pageItemByImportBatchNumberData(importPageVO);
			break;

		case DataDictionaryConstant.ITEM_CATEGORY_IMPORT:
			restMessage = baseItemCategoryService.pageItemCategoryByImportBatchNumberData(importPageVO);
			break;

		case DataDictionaryConstant.PROVIDER_IMPORT:
			restMessage = providerService.pageProviderByImportBatchNumberData(importPageVO);
			break;

		case DataDictionaryConstant.PROVIDER_SHIPPER_IMPORT:
			restMessage = providerService.pageProviderShipperByImportBatchNumberData(importPageVO);
			break;

		case DataDictionaryConstant.CUSTOMER_IMPORT:
			restMessage = customerService.pageCustomerByImportBatchNumberData(importPageVO);
			break;

		case DataDictionaryConstant.CUSTOMER_CONSIGNEE_IMPORT:
			restMessage = customerService.pageCustomerConsigneeByImportBatchNumberData(importPageVO);
			break;

		case DataDictionaryConstant.BRANCH_IMPORT:
			restMessage = tmsBaseBranchService.pageBranchByImportBatchNumberData(importPageVO);
			break;

		case DataDictionaryConstant.BRANCH_PARKING_SPACE_IMPORT:
			restMessage = tmsBaseBranchService.pageBranchParkingSpaceByImportBatchNumberData(importPageVO);
			break;

		case DataDictionaryConstant.CARRIER_IMPORT:
			restMessage = carriersService.pageCarrierByImportBatchNumberData(importPageVO);
			break;

		case DataDictionaryConstant.LINE_IMPORT:
			restMessage = tmsBaseTranslineService.pageLineByImportBatchNumberData(importPageVO);
			break;

		case DataDictionaryConstant.LINE_CARRIER_IMPORT:
			restMessage = tmsBaseTranslineService.pageLineCarrierByImportBatchNumberData(importPageVO);
			break;

		case DataDictionaryConstant.LINE_CONSIGNEE_IMPORT:
			restMessage = tmsBaseTranslineService.pageLineConsigneeByImportBatchNumberData(importPageVO);
			break;

		case DataDictionaryConstant.DRIVER_IMPORT:
			restMessage = driverService.pageDriverByImportBatchNumberData(importPageVO);
			break;

		case DataDictionaryConstant.DELIVERYMAN_IMPORT:
			restMessage = deliverymanService.pageDeliverymanByImportBatchNumberData(importPageVO);
			break;

		case DataDictionaryConstant.VEHICLE_TYPE_IMPORT:
			restMessage = vehicleTypeService.pageVehicleTypeByImportBatchNumberData(importPageVO);
			break;

		case DataDictionaryConstant.VEHICLE_IMPORT:
			restMessage = vehicleService.pageVehicleByImportBatchNumberData(importPageVO);
			break;

		default:
			throw new ParameterException("导入对象标识错误");
		}

		return restMessage;
	}
}
