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

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

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.GpsDataHtyMapper;
import com.prolog.rdc.tms.dao.mapper.GpsDataMapper;
import com.prolog.rdc.tms.model.dto.IntfErrorLogDTO;
import com.prolog.rdc.tms.model.entity.ErrorLogModel;
import com.prolog.rdc.tms.model.entity.GpsDataHtyModel;
import com.prolog.rdc.tms.model.entity.GpsDataModel;
import com.prolog.rdc.tms.model.vo.GpsDataStrVO;
import com.prolog.rdc.tms.model.vo.GpsDataVO;
import com.prolog.rdc.tms.rmi.feign.BusinessComingRecordFeign;
import com.prolog.rdc.tms.service.GpsDataWritingService;

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

/**
 * 
 *
 * GPS数据接口实现层
 *
 * @className :GpsDataWritingServiceImpl
 * @author :fanzw
 * @creationTime :2023/02/03
 * @description :
 *
 * @modifier :fanzw
 * @modifyTime :2023/02/03
 * @reviseRemarks:
 *
 * @version :1.0.0
 *
 */
@Slf4j
@Service
public class GpsDataWritingServiceImpl implements GpsDataWritingService {

	@Autowired
	private GpsDataMapper gpsDataMapper;

	@Autowired
	private GpsDataHtyMapper gpsDataHtyMapper;

	@Autowired
	private BusinessComingRecordFeign businessComingRecordFeign;

	@Autowired
	private ErrorLogMapper errorLogMapper;

	/**
	 * GPS数据保存
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveGpsDataWritingData(GpsDataStrVO gpsDataStrVO) {
		ToolKits.isParamNull(gpsDataStrVO, "请求参数不为空");
		ToolKits.isParamNull(gpsDataStrVO.getData(), "GPS参数不为空");

		String datas = gpsDataStrVO.getData();
		log.info("GPS数据参数：" + datas);

		Date date = DateUtil.date();

		String[] parameters = datas.split(",");
		Assert.isTrue(parameters.length == 15, "GPS数据【" + datas + "】校验失败");

		// 保存
		GpsDataModel gpsDataModel = new GpsDataModel();
		gpsDataModel.setId(ToolKits.getUUID());
		gpsDataModel.setType(Integer.valueOf(parameters[0]));
		gpsDataModel.setDeviceCode(parameters[1]);
		gpsDataModel.setLongitude(new BigDecimal(parameters[4]));
		gpsDataModel.setLatitude(new BigDecimal(parameters[5]));
		gpsDataModel.setGpsDate(DateUtil.parseDateTime(parameters[3]));
		gpsDataModel.setLocationHeight(new BigDecimal(parameters[6]));
		gpsDataModel.setSpatialReference(parameters[7]);
		gpsDataModel.setHorizontalVelocity(new BigDecimal(parameters[8]));
		gpsDataModel.setVerticalVelocity(new BigDecimal(parameters[9]));
		gpsDataModel.setCurrentVelocity(new BigDecimal(parameters[10]));
		gpsDataModel.setVehicleDirection(new BigDecimal(parameters[11]));
		gpsDataModel.setPositioningQuality(parameters[12]);
		gpsDataModel.setPositioningStatus(parameters[13]);
		gpsDataModel.setDataProvider(parameters[14]);
		gpsDataModel.setCreateperson(InterfaceConstant.INTERFACE_SYSTEM);
		gpsDataModel.setCreatetime(date);
		gpsDataModel.setUpdateperson(InterfaceConstant.INTERFACE_SYSTEM);
		gpsDataModel.setUpdatetime(date);
		gpsDataModel.setIntfStatus(InterfaceConstant.INTERFACE_DATA_N);
		gpsDataModel.setEnterpriseId(null);
		gpsDataModel.setEnterpriseName(null);
		// 保存
		gpsDataMapper.save(gpsDataModel);
	}

	/**
	 * 数据处理定时任务
	 */
	@Override
	public void timerTaskData() {
		// 查询未处理GPS接口数据
		List<GpsDataModel> gpsDataModels = gpsDataMapper.listGpsDataSql();

		List<GpsDataVO> gpsDataVOs = Lists.newArrayList();
		for (GpsDataModel gpsDataModel : gpsDataModels) {
			GpsDataVO gpsDataVO = new GpsDataVO();
			BeanUtils.copyProperties(gpsDataModel, gpsDataVO);
			gpsDataVOs.add(gpsDataVO);
		}

		if (ToolKits.isNotEmpty(gpsDataVOs)) {
			log.info("GPS数据接口定时任务请求报文:{}", JSONObject.toJSONString(gpsDataVOs));

			Date date = DateUtil.date();

			// 转业务处理
			RestMessage<List<IntfErrorLogDTO>> restMessage = businessComingRecordFeign.saveGpsExecute(gpsDataVOs);
			if (restMessage.isSuccess()) {
				List<IntfErrorLogDTO> intfErrorLogs = restMessage.getData();
				Assert.isTrue(ToolKits.isNotEmpty(intfErrorLogs), "处理结果异常：响应为空");
				for (IntfErrorLogDTO intfErrorLog : intfErrorLogs) {
					// 根据ID查询
					GpsDataModel gpsDataModel = gpsDataModels.stream().filter(item -> item.getId().equals(intfErrorLog.getDataId())).findAny().orElse(null);
					if (intfErrorLog.isStatus()) {
						// 转历史
						GpsDataHtyModel gpsDataHtyModel = new GpsDataHtyModel();
						BeanUtils.copyProperties(gpsDataModel, gpsDataHtyModel);
						gpsDataHtyModel.setId(ToolKits.getUUID());
						gpsDataHtyModel.setIntfStatus(InterfaceConstant.INTERFACE_DATA_Y);
						gpsDataHtyModel.setUpdatetime(date);
						gpsDataHtyMapper.save(gpsDataHtyModel);

						// 删除当前数据
						gpsDataMapper.deleteById(intfErrorLog.getDataId(), GpsDataModel.class);
					} else {
						// 状态修改为E
						gpsDataModel.setIntfStatus(InterfaceConstant.INTERFACE_DATA_E);
						gpsDataModel.setUpdatetime(date);
						gpsDataMapper.update(gpsDataModel);

						ErrorLogModel errorLogModel = new ErrorLogModel();
						errorLogModel.setId(ToolKits.getUUID());
						errorLogModel.setIntfName("GPS接口");
						errorLogModel.setErrorInfo(intfErrorLog.getErrorInfo());
						errorLogModel.setTableName("intf_gps_data");
						errorLogModel.setDataId(intfErrorLog.getDataId());
						errorLogModel.setCreatetime(date);
						errorLogMapper.save(errorLogModel);
					}
				}
			} else {
				throw new ParameterException(restMessage.getMessage());
			}
		} else {
			log.info("======GPS数据接口定时任务没有可执行数据======");
		}
	}

}
