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

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
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 org.springframework.util.Assert;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.prolog.common.util.ToolKits;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.exception.ParameterException;
import com.prolog.rdc.tms.constant.InterfaceConstant;
import com.prolog.rdc.tms.dao.mapper.ErrorLogMapper;
import com.prolog.rdc.tms.dao.mapper.ShipbillPackageHtyMapper;
import com.prolog.rdc.tms.dao.mapper.ShipbillPackageMapper;
import com.prolog.rdc.tms.dao.mapper.ShipbillPkgDetailHtyMapper;
import com.prolog.rdc.tms.dao.mapper.ShipbillPkgDetailMapper;
import com.prolog.rdc.tms.model.dto.IntfErrorLogDTO;
import com.prolog.rdc.tms.model.entity.ErrorLogModel;
import com.prolog.rdc.tms.model.entity.ShipbillPackageHtyModel;
import com.prolog.rdc.tms.model.entity.ShipbillPackageModel;
import com.prolog.rdc.tms.model.entity.ShipbillPkgDetailHtyModel;
import com.prolog.rdc.tms.model.entity.ShipbillPkgDetailModel;
import com.prolog.rdc.tms.model.vo.IntfShipbillPackageHeaderVO;
import com.prolog.rdc.tms.model.vo.IntfShipbillPackageVO;
import com.prolog.rdc.tms.model.vo.IntfShipbillPkgDetailVO;
import com.prolog.rdc.tms.rmi.feign.BusinessComingRecordFeign;
import com.prolog.rdc.tms.service.ShipbillPackageService;
import com.prolog.rdc.tms.util.HttpUtils;

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

/**
 * 
 *
 * 运单包裹接口实现层
 *
 * @className :ShipbillPackageServiceImpl
 * @author :fanzw
 * @creationTime :2022/11/17
 * @description :
 *
 * @modifier :fanzw
 * @modifyTime :2022/11/17
 * @reviseRemarks:
 *
 * @version :1.0.0
 *
 */
@Slf4j
@Service
public class ShipbillPackageServiceImpl implements ShipbillPackageService {

	@Autowired
	private BusinessComingRecordFeign businessComingRecordFeign;

	@Autowired
	private ShipbillPackageMapper shipbillPackageMapper;

	@Autowired
	private ShipbillPackageHtyMapper shipbillPackageHtyMapper;

	@Autowired
	private ShipbillPkgDetailMapper shipbillPkgDetailMapper;

	@Autowired
	private ShipbillPkgDetailHtyMapper shipbillPkgDetailHtyMapper;

	@Autowired
	private ErrorLogMapper errorLogMapper;

	/**
	 * 运单包裹接口保存
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public String saveShipbillPackageData(IntfShipbillPackageVO intfShipbillPackageVO) {
		ToolKits.isParamNull(intfShipbillPackageVO, "请求参数不为空");

		Date date = DateUtil.date();

		ToolKits.isParamNull(intfShipbillPackageVO.getOrderId(), "订单ID不为空");
		ToolKits.isParamNull(intfShipbillPackageVO.getOrderNo(), "订单编号不为空");
		ToolKits.isParamNull(intfShipbillPackageVO.getEnterpriseId(), "订单【" + intfShipbillPackageVO.getOrderNo() + "】企业ID不为空");
		ToolKits.isParamNull(intfShipbillPackageVO.getEnterpriseName(), "订单【" + intfShipbillPackageVO.getOrderNo() + "】企业名称不为空");

		// 包裹对象集合
		List<IntfShipbillPackageHeaderVO> intfShipbillPackageHeaderVOs = intfShipbillPackageVO.getHeaders();
		Assert.isTrue(intfShipbillPackageHeaderVOs.size() >= 1, "包裹信息不为空");

		// 取包裹编码集合
		List<String> packageCodes = intfShipbillPackageHeaderVOs.stream().map(IntfShipbillPackageHeaderVO::getPackageCode).distinct().collect(Collectors.toList());
		Assert.isTrue(packageCodes.size() == intfShipbillPackageHeaderVOs.size(), "订单【" + intfShipbillPackageVO.getOrderNo() + "】包裹编号重复");

		// 判断是否存在最后一个包裹
		List<IntfShipbillPackageHeaderVO> list = intfShipbillPackageHeaderVOs.stream().filter(s -> s.getLastPackage().equals(InterfaceConstant.LAST_PACKAGE_YES)).collect(Collectors.toList());
		if (list.size() > 0) {
			Assert.isTrue(list.size() == 1, "订单【" + intfShipbillPackageVO.getOrderNo() + "】存在多个最后包裹");
		}

		int count = 1;
		List<IntfShipbillPackageHeaderVO> shipbillPackageHeaderVOs = Lists.newArrayList();
		List<ShipbillPackageModel> shipbillPackageModels = Lists.newArrayList();
		List<ShipbillPkgDetailModel> shipbillPkgDetailModels = Lists.newArrayList();
		// 校验非空项
		for (IntfShipbillPackageHeaderVO intfShipbillPackageHeaderVO : intfShipbillPackageHeaderVOs) {
			ToolKits.isParamNull(intfShipbillPackageHeaderVO.getOrderId(), "订单ID不为空");
			ToolKits.isParamNull(intfShipbillPackageHeaderVO.getOrderNo(), "订单编号不为空");
			ToolKits.isParamNull(intfShipbillPackageHeaderVO.getPackageCode(), "订单【" + intfShipbillPackageHeaderVO.getOrderNo() + "】包裹编码不为空");
			ToolKits.isParamNull(intfShipbillPackageHeaderVO.getPackageType(), "订单【" + intfShipbillPackageHeaderVO.getOrderNo() + "】包裹类型不为空");
			if (intfShipbillPackageHeaderVO.getPackageType().intValue() != InterfaceConstant.PACKAGE_TYPE_ZJ.intValue() && intfShipbillPackageHeaderVO.getPackageType().intValue() != InterfaceConstant.PACKAGE_TYPE_PX.intValue()) {
				throw new ParameterException("包裹类型错误(1整件 2拼箱)");
			}

			ToolKits.isParamNull(intfShipbillPackageHeaderVO.getPcs(), "订单【" + intfShipbillPackageHeaderVO.getOrderNo() + "】包裹件数不为空");
			ToolKits.isParamNull(intfShipbillPackageHeaderVO.getWeight(), "订单【" + intfShipbillPackageHeaderVO.getOrderNo() + "】包裹重量不为空");
			ToolKits.isParamNull(intfShipbillPackageHeaderVO.getVolume(), "订单【" + intfShipbillPackageHeaderVO.getOrderNo() + "】包裹体积不为空");
			ToolKits.isParamNull(intfShipbillPackageHeaderVO.getChildParentType(), "订单【" + intfShipbillPackageHeaderVO.getOrderNo() + "】包裹字母单类型不为空");
			ToolKits.isParamNull(intfShipbillPackageHeaderVO.getLastPackage(), "订单【" + intfShipbillPackageHeaderVO.getOrderNo() + "】包裹是否最后一个包裹不为空");

			intfShipbillPackageHeaderVO.setEnterpriseId(intfShipbillPackageVO.getEnterpriseId());
			intfShipbillPackageHeaderVO.setEnterpriseName(intfShipbillPackageVO.getEnterpriseName());

			// 运单包裹对象
			ShipbillPackageModel shipbillPackageModel = new ShipbillPackageModel();
			BeanUtils.copyProperties(intfShipbillPackageHeaderVO, shipbillPackageModel);
			shipbillPackageModel.setId(ToolKits.getUUID());
			shipbillPackageModel.setSeqno(count++);
			shipbillPackageModel.setWholePiece(ToolKits.isEmpty(intfShipbillPackageHeaderVO.getWholePiece()) ? BigDecimal.ZERO : intfShipbillPackageHeaderVO.getWholePiece());
			shipbillPackageModel.setLclPiece(ToolKits.isEmpty(intfShipbillPackageHeaderVO.getLclPiece()) ? BigDecimal.ZERO : intfShipbillPackageHeaderVO.getLclPiece());
			shipbillPackageModel.setLength(ToolKits.isEmpty(intfShipbillPackageHeaderVO.getLength()) ? BigDecimal.ZERO : intfShipbillPackageHeaderVO.getLength());
			shipbillPackageModel.setWidth(ToolKits.isEmpty(intfShipbillPackageHeaderVO.getWidth()) ? BigDecimal.ZERO : intfShipbillPackageHeaderVO.getWidth());
			shipbillPackageModel.setHeigth(ToolKits.isEmpty(intfShipbillPackageHeaderVO.getHeigth()) ? BigDecimal.ZERO : intfShipbillPackageHeaderVO.getHeigth());
			shipbillPackageModel.setCreatetime(date);
			shipbillPackageModel.setUpdatetime(date);
			shipbillPackageModels.add(shipbillPackageModel);

			List<IntfShipbillPkgDetailVO> shipbillPkgDetailVOs = Lists.newArrayList();

			// 运单包裹明细处理，可为空
			List<IntfShipbillPkgDetailVO> intfShipbillPkgDetailVOs = intfShipbillPackageHeaderVO.getDetails();
			if (ToolKits.isNotEmpty(intfShipbillPkgDetailVOs)) {
				for (IntfShipbillPkgDetailVO intfShipbillPkgDetailVO : intfShipbillPkgDetailVOs) {
					ToolKits.isParamNull(intfShipbillPkgDetailVO.getItemCode(), "订单【" + intfShipbillPackageHeaderVO.getOrderNo() + "】包裹商品编码不为空");
					ToolKits.isParamNull(intfShipbillPkgDetailVO.getItemName(), "订单【" + intfShipbillPackageHeaderVO.getOrderNo() + "】包裹商品名称不为空");
					ToolKits.isParamNull(intfShipbillPkgDetailVO.getPcs(), "订单【" + intfShipbillPackageHeaderVO.getOrderNo() + "】包裹商品件数不为空");

					// 运单包裹明细对象
					ShipbillPkgDetailModel shipbillPkgDetailModel = new ShipbillPkgDetailModel();
					BeanUtils.copyProperties(intfShipbillPkgDetailVO, shipbillPkgDetailModel);
					shipbillPkgDetailModel.setId(ToolKits.getUUID());
					shipbillPkgDetailModel.setOrderId(shipbillPackageModel.getOrderId());
					shipbillPkgDetailModel.setOrderNo(shipbillPackageModel.getOrderNo());
					shipbillPkgDetailModel.setPackageId(shipbillPackageModel.getPackageId());
					shipbillPkgDetailModel.setPackageCode(shipbillPackageModel.getPackageCode());
					shipbillPkgDetailModel.setPackageType(shipbillPackageModel.getPackageType());
					shipbillPkgDetailModel.setItemCode(intfShipbillPkgDetailVO.getItemCode());
					shipbillPkgDetailModel.setItemName(intfShipbillPkgDetailVO.getItemName());
					shipbillPkgDetailModel.setPcs(intfShipbillPkgDetailVO.getPcs());
					shipbillPkgDetailModel.setVolume(ToolKits.isEmpty(intfShipbillPkgDetailVO.getVolume()) ? BigDecimal.ZERO : intfShipbillPkgDetailVO.getVolume());
					shipbillPkgDetailModel.setWeight(ToolKits.isEmpty(intfShipbillPkgDetailVO.getWeight()) ? BigDecimal.ZERO : intfShipbillPkgDetailVO.getWeight());
					shipbillPkgDetailModel.setEnterpriseId(shipbillPackageModel.getEnterpriseId());
					shipbillPkgDetailModel.setEnterpriseName(shipbillPackageModel.getEnterpriseName());
					shipbillPkgDetailModel.setCreatetime(shipbillPackageModel.getCreatetime());
					shipbillPkgDetailModel.setCreateperson(shipbillPackageModel.getCreateperson());
					shipbillPkgDetailModel.setUpdatetime(shipbillPackageModel.getUpdatetime());
					shipbillPkgDetailModel.setUpdateperson(shipbillPackageModel.getUpdateperson());
					shipbillPkgDetailModels.add(shipbillPkgDetailModel);

					// 转业务包裹数据处理
					IntfShipbillPkgDetailVO shipbillPkgDetailVO = new IntfShipbillPkgDetailVO();
					BeanUtils.copyProperties(shipbillPkgDetailModel, shipbillPkgDetailVO);
					shipbillPkgDetailVOs.add(shipbillPkgDetailVO);
				}
			}

			// 转业务包裹数据处理
			IntfShipbillPackageHeaderVO shipbillPackageHeaderVO = new IntfShipbillPackageHeaderVO();
			BeanUtils.copyProperties(shipbillPackageModel, shipbillPackageHeaderVO);
			shipbillPackageHeaderVO.setDetails(shipbillPkgDetailVOs);

			shipbillPackageHeaderVOs.add(shipbillPackageHeaderVO);
		}

		// 转业务请求集合
		List<IntfShipbillPackageVO> shipbillPackageVOs = Lists.newArrayList();

		IntfShipbillPackageVO shipbillPackageVO = new IntfShipbillPackageVO();
		shipbillPackageVO.setOrderId(intfShipbillPackageVO.getOrderId());
		shipbillPackageVO.setOrderNo(intfShipbillPackageVO.getOrderNo());
		shipbillPackageVO.setEnterpriseId(intfShipbillPackageVO.getEnterpriseId());
		shipbillPackageVO.setEnterpriseName(intfShipbillPackageVO.getEnterpriseName());
		shipbillPackageVO.setHeaders(shipbillPackageHeaderVOs);
		shipbillPackageVOs.add(shipbillPackageVO);

		log.info("运单包裹接口转业务请求报文:{}", JSONObject.toJSONString(shipbillPackageVOs));

		// 接口用户登录
		HttpUtils.HttpRestClient();

		// 转业务处理
		RestMessage<List<IntfErrorLogDTO>> restMessage = businessComingRecordFeign.saveShipbillPackageInterfaceExecute(shipbillPackageVOs);
		if (restMessage.isSuccess()) {
			List<IntfErrorLogDTO> intfErrorLogs = restMessage.getData();
			Assert.isTrue(ToolKits.isNotEmpty(intfErrorLogs), "处理结果异常：响应为空");

			IntfErrorLogDTO intfErrorLog = intfErrorLogs.get(0);
			if (intfErrorLog.isStatus()) {
				// 包裹转历史
				for (ShipbillPackageModel shipbillPackageModel : shipbillPackageModels) {
					// 运单包裹接口转历史
					ShipbillPackageHtyModel shipbillPackageHtyModel = new ShipbillPackageHtyModel();
					BeanUtils.copyProperties(shipbillPackageModel, shipbillPackageHtyModel);
					shipbillPackageHtyModel.setId(ToolKits.getUUID());
					shipbillPackageHtyModel.setIntfStatus(InterfaceConstant.INTERFACE_DATA_Y);
					shipbillPackageHtyModel.setUpdatetime(DateUtil.date());
					shipbillPackageHtyMapper.save(shipbillPackageHtyModel);
				}

				// 包裹明细转历史
				for (ShipbillPkgDetailModel shipbillPkgDetailModel : shipbillPkgDetailModels) {
					// 运单包裹明细接口转历史
					ShipbillPkgDetailHtyModel shipbillPkgDetailHtyModel = new ShipbillPkgDetailHtyModel();
					BeanUtils.copyProperties(shipbillPkgDetailModel, shipbillPkgDetailHtyModel);
					shipbillPkgDetailHtyModel.setId(ToolKits.getUUID());
					shipbillPkgDetailHtyModel.setUpdatetime(DateUtil.date());
					shipbillPkgDetailHtyMapper.save(shipbillPkgDetailHtyModel);
				}

				return null;
			} else {
				for (ShipbillPackageModel shipbillPackageModel : shipbillPackageModels) {
					// 状态修改为E
					shipbillPackageModel.setIntfStatus(InterfaceConstant.INTERFACE_DATA_E);
					shipbillPackageModel.setUpdatetime(DateUtil.date());
					shipbillPackageMapper.save(shipbillPackageModel);
				}

				if (shipbillPkgDetailModels.size() > 0) {
					shipbillPkgDetailMapper.saveBatch(shipbillPkgDetailModels);
				}

				ErrorLogModel errorLogModel = new ErrorLogModel();
				errorLogModel.setId(ToolKits.getUUID());
				errorLogModel.setIntfName("运单包裹接口");
				errorLogModel.setErrorInfo(intfErrorLog.getErrorInfo());
				errorLogModel.setTableName("intf_shipbill_package");
				errorLogModel.setDataId(intfErrorLog.getDataId());
				errorLogModel.setCreatetime(date);
				errorLogMapper.save(errorLogModel);

				return intfErrorLog.getErrorInfo();
			}
		} else {
			throw new ParameterException(restMessage.getMessage());
		}
	}

}
