package com.platform.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import com.base.CustomException;
import com.platform.dao.DataInfoDao;
import com.platform.entities.DataInfoEntity;
import com.platform.entities.PagerOptions;
import com.platform.utils.Bean2MapUtils;

@Service(value = "dataInfoService")
public class DataInfoServiceImp implements DataInfoService {
	@Resource(name = "dataInfoDao")
	private DataInfoDao dfdDao;

	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 {
			if (null != querystr && !"".equals(querystr)) {
				querys = querystr.split(" ");
			}
			pagerOptions.setArray(querys);
			int count = dfdDao.getLimitedDataCount(pagerOptions); //获取总记录条数	
			System.out.println("total colume " + count);
			int offset = 0;		
			if (pagerOptions.getCurrentPageNum() > 1) {
				pagerOptions.setTotalLimit((pagerOptions.getCurrentPageNum() - 1)
						* pagerOptions.getPriorTableSize());
				offset = dfdDao.getLimitedBeginId(pagerOptions); //获取起始查询id
				System.out.println(offset);
			}
			pagerOptions.setOffset(offset + 1);
			List<DataInfoEntity> result = dfdDao
					.getLimitedDataInfoEntities(pagerOptions);
			if (null != result) {
				for (DataInfoEntity dataInfoEntity : result) {
					dataInfoEntity.setVolumeType(dataInfoEntity.getMark());
				}
			}
			modelMap.addAttribute("data", result);
			modelMap.addAttribute("length", count);
		} 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));
		}
		if (ids.size() > 0) {
			//数据在不在？
			List<String> paths = dfdDao.getIdIsExist(ids);
			if(paths.size()>0){
				//删除文件操作
				for (int i = 0; i < paths.size(); i++) {
					System.out.println(paths.get(i));
				}
				//删除数据库记录
				dfdDao.removes(ids);			
			}
		}
	}

	@Override
	public int save(DataInfoEntity data) throws Exception {
		int result = 0;
		try {
			result = dfdDao.save(data);
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("");
		}
		return result;
	}
}
