package com.platform.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
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.Service;
import org.springframework.ui.ModelMap;

import com.base.Custom4exception;
import com.base.CustomException;
import com.platform.dao.DataInfoDao;
import com.platform.entities.DataInfoEntity;
import com.platform.form.PagerOptions;
import com.platform.http.gfs.RemoveData;
import com.platform.service.DataInfoService;
import com.platform.utils.Configs;

@Service(value = "dataInfoService")
public class DataInfoServiceImp implements DataInfoService {
	
	/** log4j  */
	public static Logger log = Configs.DAILY_ROLLING_LOGGER;
	
	@Resource(name = "dataInfoDao")
	private DataInfoDao dfdDao;
	
	private RemoveData removedata = new RemoveData();

	public void setDfdDao(DataInfoDao dfdDao) {
		this.dfdDao = dfdDao;
	}

	@Override
	public ModelMap getPagerTableData(PagerOptions pagerOptions) {
		ModelMap modelMap = new ModelMap();
		String querystr = pagerOptions.getKeyQuery();
		String[] querys = null;
		try {
			List<String> removelist = new ArrayList<String>();
			List<String> alllist = new ArrayList<String>();
			List<String> list = new ArrayList<String>();
			//如果有查询数据库类型的
			//去掉版本字段
			Pattern pattern = Pattern.compile("^版本\\d+");
			if (null != querystr && !"".equals(querystr)) {
				if (querystr.toLowerCase().contains("oracle")) {
					pagerOptions.setDataBaseType("ORACLE");
					querystr = querystr.toUpperCase().replaceAll("ORACLE", "");
				}else if(querystr.toLowerCase().contains("sql server")){
					pagerOptions.setDataBaseType("SQL SERVER");
					querystr = querystr.toUpperCase().replaceAll("SQL SERVER", "");
				}
				querys = querystr.trim().split(" ");
				list = Arrays.asList(querys);
			}
			//遍历 list
			for (String ss : list) {
				ss = ss.trim();
				if (!"".equals(ss)) {
					alllist.add(ss);
				}
			}
			for (String ss : alllist) {
				Matcher matcher2 = pattern.matcher(ss);
				// 去掉 最后 的 / 符合
				if (matcher2.find()) {
					String s2 = matcher2.group();
					removelist.add(ss);
				}
			}
			alllist.removeAll(removelist);
			Object[] strs = alllist.toArray();
			int length = strs.length;
			List<String> arrays = new ArrayList<String>();
			for (int i = 0; i < length; i++) {
				arrays.add(strs[i].toString().trim());
			}
			for (String version : removelist) {
				pagerOptions.setDataVersion(Integer.valueOf(version.replace("版本", "")));
			}
			if (arrays.size() > 0) {
				pagerOptions.setArray(arrays);
			}
			if (null !=pagerOptions.getSubmittedBatch() && !"".equals(pagerOptions.getSubmittedBatch()) ) {
				pagerOptions.setSubmittedBatch("批次"+pagerOptions.getSubmittedBatch());
			}
			List<DataInfoEntity> result = null;
			try{
				result = dfdDao.getLimitedDataInfoByPage(pagerOptions);
			}catch(Exception e){
				log.error(e.getMessage());
			}
//			int count = dfdDao.getLimitedDataCount(pagerOptions); //获取总记录条数	
//			log.info("total colume " + count);
//			int offset = 0;		
//			if (pagerOptions.getCurrentPageNum() > 1) {
//				pagerOptions.setTotalLimit((pagerOptions.getCurrentPageNum() - 1)
//						* pagerOptions.getPriorTableSize());
//				offset = dfdDao.getLimitedBeginId(pagerOptions); //获取起始查询id
//				log.info(offset);
//			}
//			pagerOptions.setOffset(offset + 1);
//			List<DataInfoEntity> result = dfdDao
//					.getLimitedDataInfoEntities(pagerOptions);
//			if (null != result) {
//				for (DataInfoEntity dataInfoEntity : result) {
//					dataInfoEntity.setVolumeType(dataInfoEntity.getMark());
//				}
//			}
			modelMap.addAttribute("page", pagerOptions);
			modelMap.addAttribute("data", result);
			modelMap.addAttribute("length", pagerOptions.getTotleSize());
		} catch (Exception e) {
			new CustomException();
		}
		return modelMap;
	}
	
	@Override
	public void deleteData(String[] id) throws Exception {
		// TODO Auto-generated method stub
		List<Integer> ids = new ArrayList<Integer>();
		for(String idx: id){
			ids.add(Integer.parseInt(idx));
		}
		deleteData(ids);
	}

	@Override
	public void deleteData(List<Integer> ids) throws Exception {
		if (ids.size() > 0) {
			//数据在不在？
			List<String> paths = dfdDao.getIdIsExist(ids);
			if(paths.size()>0){
				//TODO 删除文件操作
				Pattern pattern = Pattern
						.compile("\\/$");
				for (int i = 0; i < paths.size(); i++) {
					String folderPath = paths.get(i);
					Matcher matcher = pattern.matcher(folderPath);
					String tailPath = "";
					if (matcher.find()) {
						tailPath = matcher.group();
					}
					folderPath = folderPath.substring(0, folderPath.length()-tailPath.length());
					int res = removedata.deleteFolder(folderPath);
					if (res != 1) {
						log.error( folderPath+ "  删除失败！\n");
					}
					else {
						log.info( folderPath+ "  删除成功！\n");
					}
				}
				//删除数据库记录
				dfdDao.removes(ids);			
			}
		}
		
	}

	@Override
	public int save(DataInfoEntity data) throws Exception {
		int result = 0;
		try {
			result = dfdDao.save(data);
		} catch (Exception e) {
			result = -1;
			new CustomException(Custom4exception.MySQL_Except, e, data);
		}
		return result;
	}
}
