package cn.tsy.idsse.dsds.service.sample;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.hme.framework.helper.date.LocalDateHelper;
import cn.hme.framework.helper.lang.StringHelper;
import cn.hme.framework.helper.log.LogHelper;
import cn.hme.framework.jdbc.provider.builder.SqlBuilder;
import cn.hme.framework.jdbc.provider.builder.SqlCondition;
import cn.hme.framework.web.exception.BusinessException;
import cn.hme.framework.web.helper.FrameAssertHelper;
import cn.tsy.data.idsse.dsds.mapper.sample.SampleDatasetMapper;
import cn.tsy.data.idsse.dsds.mapper.sample.SampleLineMapper;
import cn.tsy.data.idsse.dsds.mapper.sample.SampleLineTrackMapper;
import cn.tsy.data.idsse.dsds.mapper.voyage.VoyageRegMapper;
import cn.tsy.data.idsse.dsds.model.sample.SampleDataset;
import cn.tsy.data.idsse.dsds.model.sample.SampleLine;
import cn.tsy.data.idsse.dsds.model.sample.SampleLineTrack;
import cn.tsy.data.idsse.dsds.model.voyage.VoyageReg;

@Service
public class SampleLineTrackService {
	@Autowired
	private SampleLineTrackMapper mTrack;
	@Autowired
	private SampleLineMapper mLine;
	@Autowired
	private VoyageRegMapper mVoyage;
	@Autowired
	private SampleDatasetMapper mDataset;

	public List<SampleLineTrack> uploadTrack(int dataset_id, List<String> array, String file_name) {
		FrameAssertHelper.hasValue(array, "测线轨迹文件为空，请检查！");
		if (file_name.toLowerCase().endsWith("m.txt")) {
			SampleDataset ds = this.mDataset.find(dataset_id);
			if (ds == null) {
				throw new BusinessException("未找到对应的数据集信息！");
			}
			VoyageReg voyage = this.mVoyage.find(ds.getVoyage_id());
			String heigth = file_name.replace(".txt", "").replaceAll("m", "").split("_")[1];
			// 判断是否已经输入了
			this.mLine.deleteByColumn("dataset_id", dataset_id);
			int index = 1;
			SampleLine line = new SampleLine();
			for (int i = 0; i < array.size(); i++) {
				if (array.get(i).trim().length() == 0) {
					break;
				}
				String[] values = StringHelper.splitWithSpace(array.get(i));
				if (values[0].equals(">>")) {
					this.createLine(voyage,ds, line, heigth, index);
					line = new SampleLine();
					LogHelper.info("dataset_index:"+index);
					index++;
					continue;
				}
				String lon = values[0];
				String lat = values[1];
				String time = values[2];
				// 经纬度的范围包括经度范围0°-180°和纬度范围0°-90°
				try {
					double d = Double.parseDouble(lon);
					if (d > 180)
						throwError(i, "经度[" + lon + "]不能大于 180°");
					if (d < 0)
						throwError(i, "经度[" + lon + "]不能小于 0°");
				} catch (Exception e) {
					throwError(i, "经度[" + lon + "]格式错误");
				}

				try {
					double d = Double.parseDouble(lat);
					if (d > 90)
						throwError(i, "纬度[" + lat + "]不能大于 90°");
					if (d < 0)
						throwError(i, "纬度[" + lat + "]不能小于 0°");
				} catch (Exception e) {
					throwError(i, "纬度[" + lat + "]格式错误");
				}
				// 109.49100 18.23400 2023-09-18-21:58:35
				String[] vs = time.split("-");
				if (vs.length != 4)
					throwError(i, "时间[" + time + "]格式错误，样例 2023-09-18-21:58:35");
				LocalDateTime curTime = LocalDateHelper.parseDateTime(vs[0] + "-" + vs[1] + "-" + vs[2] + " " + vs[3]);
				if (curTime == null)
					throwError(i, "时间[" + time + "]格式错误，样例 2023-09-18-21:58:35");
				// 判断通过
				if (values.length < 3) {
					throwError(i, "列不足，至少需要3列");
				}
				if (line.getStart_lat() == null)
					line.setStart_lat(lat);
				if (line.getStart_lon() == null)
					line.setStart_lon(lon);
				if (line.getStart_time() == null)
					line.setStart_time(curTime);
				line.setEnd_lat(lat);
				line.setEnd_lon(lon);
				line.setEnd_time(curTime);				
			}
			this.createLine(voyage,ds, line, heigth, index);
		} else {
			// 找出所有航线
			String dv_sn = file_name.replace(".txt", "").replace("_Clean", "");
			List<SampleDataset> sdArray = this.mDataset.selectListByColumn("diving_sn", dv_sn);
			if (sdArray.size() == 0) {
				throw new BusinessException("未找到潜次[" + dv_sn + "]对应的数据集！");

			} else {
				for (SampleDataset ds : sdArray) {
					int index = 1;
					List<SampleLineTrack> navArray = new ArrayList<>();
					for (int i = 0; i < array.size(); i++) {
						if (array.get(i).trim().length() == 0) {
							this.update(file_name, ds, index, navArray);
							break;
						}
						String[] values = StringHelper.splitWithSpace(array.get(i));
						if (values[0].equals(">>")) {
							this.update(file_name, ds, index, navArray);
							navArray = new ArrayList<>();
							index++;
							continue;
						}
						if (values.length < 3) {
							throwError(i, "列不足，至少需要3列");
						}

						// 110.565232 17.370000 2023-05-20-13:55:27
						String lon = values[0];
						String lat = values[1];
						String time = values[2];
						// 经纬度的范围包括经度范围0°-180°和纬度范围0°-90°
						try {
							double d = Double.parseDouble(lon);
							if (d > 180)
								throwError(i, "经度[" + lon + "]不能大于 180°");
							if (d < 0)
								throwError(i, "经度[" + lon + "]不能小于 0°");
						} catch (Exception e) {
							throwError(i, "经度[" + lon + "]格式错误");
						}

						try {
							double d = Double.parseDouble(lat);
							if (d > 90)
								throwError(i, "纬度[" + lat + "]不能大于 90°");
							if (d < 0)
								throwError(i, "纬度[" + lat + "]不能小于 0°");
						} catch (Exception e) {
							throwError(i, "纬度[" + lat + "]格式错误");
						}
						// 109.49100 18.23400 2023-09-18-21:58:35
						String[] vs = time.split("-");
						if (vs.length != 4)
							throwError(i, "时间[" + time + "]格式错误，样例 2023-09-18-21:58:35");
						LocalDateTime curTime = LocalDateHelper.parseDateTime(vs[0] + "-" + vs[1] + "-" + vs[2] + " " + vs[3]);
						if (curTime == null)
							throwError(i, "时间[" + time + "]格式错误，样例 2023-09-18-21:58:35");
						// 判断通过

						SampleLineTrack nav = new SampleLineTrack();
						nav.setTrack_lat(lat);
						nav.setTrack_lon(lon);
						nav.setTrack_time(curTime);
						navArray.add(nav);
					}
				}
			}
		}

		return new ArrayList<>();
	}

	public void createLine(VoyageReg voyage,SampleDataset ds, SampleLine line, String heigth, int index) {
		line.setCreate_time(LocalDateTime.now());
		line.setDataset_id(ds.getTsy_id());
		line.setFunding_org(voyage.getFunding_org());
		line.setDataset_name(ds.getDataset_name());
		line.setLine_deep(heigth);
		line.setPublish_rule("不公开");
		line.setSample_status("原始数据");
		line.setSample_seq(StringHelper.leftPadding(index + "", 2, '0'));
		line.setLine_sn(line.getSample_seq());
		line.setSample_name(ds.getDataset_name() + "_" + line.getSample_seq());
		this.mLine.insert(line);
	}

	public void update(String file_name, SampleDataset ds, int index, List<SampleLineTrack> navArray) {
		if (navArray.size() == 0)
			return;
		// 查找是否有对应的测线
		String sn = StringHelper.leftPadding(index + "", 2, '0');
		List<SampleLine> lineArray = this.mLine.selectList(SqlBuilder.create().addSqlCondition(SqlCondition.of("dataset_id", ds.getTsy_id())).addSqlCondition(SqlCondition.of("sample_seq", sn)));
		if (lineArray.size() > 0) {
			for (SampleLineTrack nav : navArray) {
				nav.setDataset_id(ds.getTsy_id());
				nav.setTrack_index(sn);
				nav.setLine_id(lineArray.get(0).getTsy_id());
				this.mTrack.insert(nav);
			}
			SampleLine line = new SampleLine();
			line.setTsy_id(lineArray.get(0).getTsy_id());
			line.setTrack_file_name(file_name);
			this.mLine.update(line);

		}
		navArray = new ArrayList<>();
	}

	public void throwError(int row, String msg) {
		throw new BusinessException("测线轨迹文件导入失败->第[" + (row + 1) + "]行:" + msg);

	}

}
