package com.platform.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.platform.controller.CheckoutController;
import com.platform.dao.DataInfoDao;
import com.platform.dao.DataInfoMoveTmpDao;
import com.platform.dao.VolumeDao;
import com.platform.entities.DataInfoEntity;
import com.platform.entities.DataInfoEntityMoveTmp;
import com.platform.entities.FolderNode;
import com.platform.entities.VolumeInitEntity;
import com.platform.glusterfs.CheckoutMD5;
import com.platform.http.gfs.RemoveData;
import com.platform.glusterfs.ShowData;
import com.platform.service.IMoveDataService;
import com.platform.utils.DateForm;

@Component
@Service(value = "moveDataService")
public class MoveDataServiceImpl implements IMoveDataService {
	
	/**
	 * 日志
	 */
	public final static Logger log = Logger.getLogger(CheckoutController.class);

	@Resource(name = "dataInfoDao")
	private DataInfoDao dataInfoDao;
	
	@Resource(name = "volumeDao")
	private VolumeDao volumeDao;

	private RemoveData removeservice = new RemoveData();

	/**
	 * MD5校验
	 */
//	CheckoutMD5 check = new CheckoutMD5();

	@Resource(name = "dataInfoMoveTmpDao")
	private DataInfoMoveTmpDao dataInfoMoveTmpDao;

	/**
	 * 查看数据
	 */
	ShowData show = new ShowData();

	@Override
	public boolean moveData(List<DataInfoEntity> data, FolderNode node)
			throws Exception {
		boolean isSuccess = false;
		if (null ==node.getName() ||"".equals(node.getName())) {
			return false;
		}
		if (null ==node.getPath() ||"".equals(node.getPath())) {
			return false;
		}
		List<VolumeInitEntity> listVolume = volumeDao.findAll();
		if (null == listVolume || listVolume.size() == 0) {
			return false;
		}
		String tailPath = "";
		if (null != data) {
			// XXX/320198_16/1,or XXX/320122KFQ_15/1 ---> /320198_16/1, or
			// /320122KFQ_15/1
			List<DataInfoEntityMoveTmp> exist = dataInfoMoveTmpDao.findAll();
			List<String> existIds = new ArrayList<String>();
			List<Integer> fkIds = new ArrayList<Integer>();
			if (null != exist) {
				for (DataInfoEntityMoveTmp dataInfoEntityMoveTmp : exist) {
					if ("0".equals(dataInfoEntityMoveTmp.getCompleteStatus())
							|| "1".equals(dataInfoEntityMoveTmp
									.getCompleteStatus())) {
						if (null != dataInfoEntityMoveTmp.getDataPath()) {
							existIds.add(dataInfoEntityMoveTmp.getDataPath());
						}
						fkIds.add(dataInfoEntityMoveTmp.getFkid());
					}
				}
			}
			Pattern pattern = Pattern
					.compile("\\/\\d+[a-z]*[A-Z]*_\\d+\\/\\d*\\/*$");
			// 末尾 含有 /
			Pattern pattern2 = Pattern.compile("\\/$");
			String dstPath = node.getPath();
			Matcher matcher2 = pattern2.matcher(dstPath);
			// 去掉 最后 的 / 符合
			if (matcher2.find()) {
				dstPath = dstPath.substring(0, dstPath.length() - 1);
			}
			List<DataInfoEntityMoveTmp> moveList = new ArrayList<DataInfoEntityMoveTmp>();
			for (DataInfoEntity dataInfoEntity : data) {
				//（根据迁移路径判断）存在迁移过的数据，不允许迁移，先必须删除记录
				if (existIds.contains(dataInfoEntity.getDataPath())) {
					continue;
				}
				// 数据的id不存在的数据不允许迁移
				if (dataInfoEntity.getId() == 0) {
					continue;
				}
				// （根据数据的id判断）存在迁移过的数据，不允许迁移，先必须删除记录
				if (fkIds.contains(dataInfoEntity.getId())) {
					continue;
				}
				// 迁移数据的位置在原数据路径或者原数据父目录及其上，不允许迁移
				if (dataInfoEntity.getDataPath().contains(node.getPath())) {
					continue;
				}
				// TODO 正则：取出 data 的后面 的 路径，eg: XXX/320198_16/1,or
				// XXX/320122KFQ_15/1）
				Matcher matcher = pattern.matcher(dataInfoEntity.getDataPath());
				// tailPath 第一个字符是 / 符号取尾："\\/\\d+[a-z]*[A-Z]*_\\d+\\/\\d*\\/*$"
				if (matcher.find()) {
					tailPath = matcher.group();
				}
				String finalDestPath = dstPath + tailPath;
				Matcher matchertmp2 = pattern2.matcher(finalDestPath);
				// 去掉 最后 的 / 符合
				if (!matchertmp2.find()) {
					finalDestPath = finalDestPath + "/";
				}
				DataInfoEntityMoveTmp dataMove = new DataInfoEntityMoveTmp();
				dataMove.setSystemCode(dataInfoEntity.getSystemCode());
				dataMove.setRegionalismCode(dataInfoEntity.getRegionalismCode());
				dataMove.setDstPath(finalDestPath);
				dataMove.setLastTime(DateForm.date2StringBysecond(new Date()));
				dataMove.setFkid(dataInfoEntity.getId());
				// 末尾 含有 /
				Matcher matcher3 = pattern2.matcher(node.getPath());
				// 去掉 最后 的 / 符合
				String volumePath = ""; 
				if (!matcher3.find()) {
					volumePath = node.getPath()+"/";
				}
				else {
					volumePath = node.getPath();
				}
				String path = "";
				String ip = "";
				for ( VolumeInitEntity ve : listVolume) {
					String tmpPath = ve.getPath();
					if (volumePath.contains(tmpPath)) {
						if (tmpPath.length() > path.length()) {
							path = tmpPath;
							ip = ve.getIp();
						}
					}
				}
				if (path.length() == 0) {
					dataMove.setDstVolumePath("nopath");
					dataMove.setDstVolumePath("noIP");
				}else {
					dataMove.setDstVolumePath(path);
					dataMove.setDstVolumeIp(ip);
				}
				moveList.add(dataMove);
			}
			if (moveList.size() > 0) {
				dataInfoMoveTmpDao.insertBatch(moveList);
				isSuccess = true;
			}
		}
		return isSuccess;
	}

	@Override
	public List<DataInfoEntityMoveTmp> findAll() throws Exception {
		List<DataInfoEntityMoveTmp> result = new ArrayList<DataInfoEntityMoveTmp>();
		try {
			List<DataInfoEntityMoveTmp> tmp = dataInfoMoveTmpDao.findAll();
			for (DataInfoEntityMoveTmp tmpentity : tmp) {
				if (null != tmpentity.getSubmittedBatch() || null != tmpentity.getSystemName()) {
					result.add(tmpentity);
				}else {
					this.delete(tmpentity);
				}
			}
			
		} catch (Exception e) {
			log.error(e);
		}
		return result;
	}

	@Override
	public int delete(DataInfoEntityMoveTmp dataMove) throws Exception {
		List<DataInfoEntityMoveTmp> list = dataInfoMoveTmpDao.findAll();
		if (null != list) {
			for (DataInfoEntityMoveTmp dataInfoEntityMoveTmp : list) {
				if (dataMove.getId() == dataInfoEntityMoveTmp.getId()) {
					dataMove = dataInfoEntityMoveTmp;
					break;
				}
			}
			
		}
		//迁移失败
		if ("3".equals(dataMove.getCompleteStatus())) {
			removeservice.deleteFolder(dataMove.getDstPath());
		}
		int result = 0;
		//是正则迁移时：
		if ("1".equals(dataMove.getCompleteStatus())) {
			if(1 != removeservice.abortcopyFolder(dataMove.getDataPath(), makeDstPath(dataMove.getDstPath()))){
				removeservice.deleteFolder(dataMove.getDstPath());
			}
		}
		result = dataInfoMoveTmpDao.remove(dataMove.getId());
		return result;
	}

	@Override
	public int save(DataInfoEntityMoveTmp data) throws Exception {
		dataInfoMoveTmpDao.save(data);
		return 0;
	}

	@Override
	public int insertBatch(List<DataInfoEntityMoveTmp> list) throws Exception {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int update(DataInfoEntityMoveTmp data) throws Exception {
		int result = dataInfoMoveTmpDao.update(data);
		return result;
	}

	/** 去掉 最后 的     数字 +/
	 * @param dstPath
	 * @return
	 */
	private String makeDstPath(String dstPath) {
		// 末尾 含有    数字 + /
		Pattern pattern2 = Pattern.compile("\\d+\\/$");
		Matcher matcher2 = pattern2.matcher(dstPath);
		//去掉 最后 的     数字 +/ 符合
		if (matcher2.find()) {
			String removeStr = matcher2.group();
			dstPath = dstPath.replace(removeStr, "");
		}
		return dstPath;
	}
}
