package com.platform.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.base.BaseController;
import com.platform.entities.DataInfoEntity;
import com.platform.entities.DataInfoEntityMoveTmp;
import com.platform.entities.GatherOracleInfo;
import com.platform.entities.PagerOptions;
import com.platform.entities.VolumeEntity;
import com.platform.entities.oracleForm;
import com.platform.entities.volumeMoveForm;
import com.platform.service.DataInfoService;
import com.platform.service.ICodeService;
import com.platform.service.IGfsService;
import com.platform.service.IMoveDataService;
import com.platform.service.IMySqlService;
import com.platform.service.IOracleExtractService;
import com.platform.service.OracleStatusService;
import com.platform.utils.Configs;
import com.platform.utils.UtilsHelper;

@Controller
public class DataModelController extends BaseController{
	
	public static Logger log = Logger.getLogger(DataModelController.class);
	
	@Resource(name = "dataInfoService")
	private DataInfoService dfs;
	
	@Resource(name = "gfsService")
	private IGfsService gfsService;
	
	@Resource(name = "mySqlService")
	private IMySqlService mySqlService;
	
	@Resource(name = "OracleExtract")
	private IOracleExtractService OracleExtract;
	
	@Resource(name = "moveDataService")
	private IMoveDataService moveDataService;
	
	@Resource(name = "codeService")
	private ICodeService codeService;
	
	public void setDfsImp(DataInfoService dfs) {
		this.dfs = dfs;
	}

	@RequestMapping("/data.json")
	@ResponseBody
	public ModelMap getAllDataToJson(HttpServletRequest res,
			HttpServletResponse req) throws UnsupportedEncodingException {
		res.setCharacterEncoding("UTF-8");
		Map<String, String[]> paramMap = res.getParameterMap();
		Set<String> keySet = paramMap.keySet();
		Map<String, String> params = new HashMap<String, String>();
		StringBuffer sb = new StringBuffer().append("当前的请求参数:{");
		for (String str : keySet) {
			String value = paramMap.get(str)[0];
			if (StringUtils.isNotEmpty(value)) {
				params.put(str, value);
				sb.append(str).append(":").append(value).append(",");
			} else {
				sb.append(str).append(":").append("null").append(",");
			}
		}
		Configs.CONSOLE_LOGGER.info(sb.deleteCharAt(sb.length() - 1)
				.append("}").toString());
		PagerOptions pagerOptions = (PagerOptions) UtilsHelper
				.newObjAndSetAttrsByClass(PagerOptions.class, params);
		
		return dfs.getPagerTableData(pagerOptions);
	}

	@RequestMapping(value="/delete/data", method= RequestMethod.POST)
	public void deleteData(HttpServletRequest res, HttpServletResponse req) throws Exception {
		res.setCharacterEncoding("UTF-8");
		Map<String, String[]> paramMap = res.getParameterMap();
		String[] data = paramMap.get("data");
		dfs.deleteData(data);
		req.setStatus(200);
	}

	@RequestMapping("/connectOracle")
	public void connectOracle(HttpServletRequest res, HttpServletResponse req) throws UnsupportedEncodingException {
		res.setCharacterEncoding("UTF-8");
		Map<String, String[]> paramMap = res.getParameterMap();
		String[] oraclesName = paramMap.get("oracleName");
		if (oraclesName != null)
			for (String rcName : oraclesName) {
				Configs.CONSOLE_LOGGER.info("连接成功\t" + rcName);
				new OracleStatusService().connectToOracle(rcName);
			}
		req.setStatus(200);
	}

	@RequestMapping("/cancelOracleConection")
	public void cancelOracleConnection(HttpServletRequest res,
			HttpServletResponse req) throws UnsupportedEncodingException {
		res.setCharacterEncoding("UTF-8");
		Map<String, String[]> paramMap = res.getParameterMap();
		String[] oraclesName = paramMap.get("oracleName");
		String operate = paramMap.get("operation")[0];
		if (null != oraclesName) {
			for (String rcName : oraclesName) {
				Configs.CONSOLE_LOGGER.info("取消连接:\t" + rcName);
				new OracleStatusService().cancelToOracle(rcName, operate);
			}
		}
		req.setStatus(200);
	}

	@RequestMapping(value="/oracle/{name}/extract", method= RequestMethod.POST)
	public void oracleExtract(HttpServletRequest res,
			HttpServletResponse req,@RequestBody oracleForm form) throws Exception {
		Configs.CONSOLE_LOGGER.error("/oracle/{name}/extract");
		res.setCharacterEncoding("UTF-8");
		if (null != form.getInneed() && form.getInneed().size() > 0) {
			OracleExtract.extractOracle(form.getName(), form.getInneed(), form.getTarget());
		}
		req.setStatus(200);
	}
//	public void oracleExtract(HttpServletRequest res,
//			HttpServletResponse req, String name, @RequestBody GatherOracleInfo gather, @RequestBody List<OracleConnectorParams> collectOracles)
//					throws Exception {
////		res.setCharacterEncoding("UTF-8");
//		log.debug("------extract-------");
////		Map<String, String[]> paramMap = res.getParameterMap();
////		log.debug(paramMap);
////		//汇总库 对象信息--带有tableName-
////		String[] nodes = paramMap.get("target");
////		Map map = null;
////		for (String string : nodes) {
////			JSONObject jsonobject = JSONObject.fromObject(string);
////			map = jsonobject;
////			System.out.println(map);
////		}
////		
////		// 采集库对象--(多个采集库抽取到1个汇总库的1个tableName下)
////		String[] inneed = paramMap.get("inneed");
////		List<Map<String, String>> colleclist = new ArrayList<Map<String,String>>();
////		for (String string : nodes) {
////			JSONObject jsonobject = JSONObject.fromObject(string);
////			 Map inneedMap = jsonobject;
////			colleclist.add(inneedMap);
////		}
//		OracleExtract.extractOracle(name, collectOracles, gather);
//	}

	@RequestMapping(value="/volume/list", method= RequestMethod.POST)
	@ResponseBody
	public List<VolumeEntity> volumeList() throws Exception {
		log.debug("-----/volume/list------");
		List<VolumeEntity> result = gfsService.getAllVolumes();
		return result;
	}
	
	@RequestMapping(value = "/volume/{name}/move", method= RequestMethod.POST)
	@ResponseBody
	public void volumeMove(HttpServletRequest res, HttpServletResponse req,@RequestBody volumeMoveForm form) throws Exception {
		List<DataInfoEntity> datas = new ArrayList<DataInfoEntity>();
		List<DataInfoEntity> selectItems = form.getSelectItems();
		if (null == selectItems) {
			req.setStatus(200);
			return;
		}
		datas.addAll(selectItems);
		
		System.out.println("------/volume/{name}/move--------");
		if (datas.size() >0) {
			moveDataService.moveData(datas, form.getSelectNode());
		}
		req.setStatus(200);
	}
	
	@RequestMapping(value="/oracle/list", method= RequestMethod.POST)
	@ResponseBody
	public List<GatherOracleInfo> oracleList() throws Exception {
		log.debug("----------getOracleInfo-----------------------");
		List<GatherOracleInfo> result = mySqlService.findAllMySql(); 
		return result;
	}
	
	@RequestMapping(value="/oracle/{id}/delete", method= RequestMethod.POST)
	public void oracleDelete(HttpServletRequest req, HttpServletResponse res, @PathVariable String id) throws Exception {
		log.debug("----------deleteOracleInfo----------------");
		Integer num = Integer.valueOf(id);
		Integer result = mySqlService.deleteMySql(num); 
		log.info("oracleDelete : " + result);
		res.setStatus(200);
	}
	
	@RequestMapping(value="/oracle/{id}/insert", method= RequestMethod.POST)
	@ResponseBody
	public void oracleInsert(HttpServletRequest res, HttpServletResponse req, @PathVariable String id, @RequestBody GatherOracleInfo oracle) throws Exception {
		log.debug("----------insertOracleInfo----------------");
		oracle.setId(Integer.valueOf(id));
		mySqlService.insertOracle(oracle);
		req.setStatus(200);
	}
	
	@RequestMapping(value="/oracle/{id}/update", method= RequestMethod.POST)
	@ResponseBody
	public void oracleUpdate(HttpServletRequest res, HttpServletResponse req, @PathVariable("id") String id, @RequestBody GatherOracleInfo oracle) throws Exception {
		log.debug("----------updateOracleInfo-----------------------");
		log.debug(oracle);
		mySqlService.updateOracle(oracle); 
		req.setStatus(200);
	}
	
	@RequestMapping(value="/task/transfer/list", method= RequestMethod.POST)
	@ResponseBody
	public Object taskTransferList() throws Exception {
		log.debug("----------/task/transfer/list-----------------------");
		List<DataInfoEntityMoveTmp> result = moveDataService.findAll();
		return result;
	}
	
	@RequestMapping(value="/task/transfer/{id}/delete", method= RequestMethod.POST)
	@ResponseBody
	public Object taskTransferDelete(HttpServletRequest res, HttpServletResponse req, @PathVariable String id) throws Exception {
		log.debug("----------/task/transfer/{id}/delete-----------------------");
		DataInfoEntityMoveTmp move = new DataInfoEntityMoveTmp();
		move.setId(Integer.valueOf(id));
		int result = moveDataService.delete(move );
		req.setStatus(200);
		return result;
	}
	
	@RequestMapping(value="/task/transfer/save", method= RequestMethod.POST)
	@ResponseBody
	public Object taskTransferSave(HttpServletRequest res, HttpServletResponse req, @RequestBody DataInfoEntity move) throws Exception {
		log.debug("---------/task/transfer/save-----------------------");
		int result = dfs.save(move);
		req.setStatus(200);
		return result;
	}
	
	@RequestMapping(value="/code/list", method= RequestMethod.POST)
	@ResponseBody
	public Object findCodeList() throws Exception {
		log.debug("---------/findSystemCode-----------------------");
		Map<String, Object> result = codeService.findAll();
		return result;
	}
	
	@RequestMapping(value = "/oracle/extract/log", method= RequestMethod.POST )
	@ResponseBody
	public Object getExtractLog(@RequestParam("rcName") String name, HttpServletRequest res, HttpServletResponse req){
		log.info("---------/oracle/extract/log-------------------");
		StringBuilder sb = new StringBuilder();
		sb.append("查看相应日志").append("\n").append("看到了");
		Map<String, String> log = new HashMap<>();
		log.put(name, sb.toString());
		return log;
	}
}
