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.BasedTask;
import com.platform.entities.DataInfoEntity;
import com.platform.entities.DataInfoEntityMoveTmp;
import com.platform.entities.GatherOracleInfo;
import com.platform.entities.OracleConnectorParams;
import com.platform.entities.OracleExtractExecuter;
import com.platform.form.PagerOptions;
import com.platform.form.oracleForm;
import com.platform.form.volumeMoveForm;
import com.platform.service.DataInfoService;
import com.platform.service.ICodeService;
import com.platform.service.IGatherOracleService;
import com.platform.service.ILogRead;
import com.platform.service.IMoveDataService;
import com.platform.service.IOracleExtractService;
import com.platform.service.IVolumeService;
import com.platform.service.OracleExtractTask;
import com.platform.service.OracleStatusService;
import com.platform.utils.Constant;
import com.platform.utils.UtilsHelper;

/**
 * 数据管理
 * 
 * @author chen
 * 
 */
@Controller
public class DataModelController extends BaseController {

	public static Logger log = Logger.getLogger(DataModelController.class);

	/**
	 * 数据管理--业务类
	 */
	@Resource(name = "dataInfoService")
	private DataInfoService dfs;

	/**
	 * gfs业务类
	 */
	@Resource(name = "volumeService")
	private IVolumeService volumeService;

	/**
	 * mysql相关业务
	 */
	@Resource(name = "mySqlService")
	private IGatherOracleService mySqlService;

	/**
	 * oracle汇总功能业务
	 */
	@Resource(name = "OracleExtract")
	private IOracleExtractService OracleExtract;

	/**
	 * 迁移数据业务类
	 */
	@Resource(name = "moveDataService")
	private IMoveDataService moveDataService;

	/**
	 * 地区、系统code业务类
	 */
	@Resource(name = "codeService")
	private ICodeService codeService;

	/**
	 * 日志业务管理类
	 */
	@Resource(name = "logReadService")
	private ILogRead logReadService;

	public void setDfsImp(DataInfoService dfs) {
		this.dfs = dfs;
	}

	/**
	 * 数据管理--分页查询数据
	 * 
	 * @param res
	 * @param req
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/data.json")
	@ResponseBody
	public ModelMap getAllDataToJson(HttpServletRequest res,
			HttpServletResponse req) throws UnsupportedEncodingException {
		log.info("-----------/data.json-----------");
		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(",");
			}
		}
		log.info(sb.deleteCharAt(sb.length() - 1).append("}").toString());
		PagerOptions pagerOptions = (PagerOptions) UtilsHelper
				.newObjAndSetAttrsByClass(PagerOptions.class, params);
		pagerOptions.setCurrentPageNum(Integer.valueOf(params
				.get("currentPageNum")));
		// 冷热区查询字段mark
		pagerOptions.setMark(pagerOptions.getVolumeType().trim());
		return dfs.getPagerTableData(pagerOptions);
	}

	/**
	 * 数据管理--删除数据
	 * 
	 * @param res
	 * @param req
	 * @throws Exception
	 */
	@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);
	}

	/**
	 * 连接oracle
	 * 
	 * @param res
	 * @param req
	 * @throws UnsupportedEncodingException
	 */
	@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) {
				log.info("执行连接\t" + rcName);
				String cmd = "kubectl label --overwrite rc " + rcName
						+ " status=0";
				List<String> rList = Constant.ganymedSSH
						.execCmdWaitAcquiescent(cmd);
				StringBuffer sb = new StringBuffer();
				for (String string : rList)
					sb.append(string).append("\n");
				log.info(sb.toString());
				new OracleStatusService().connectToOracle(rcName);
			}
		req.setStatus(200);
	}

	/**
	 * 断开oracle连接
	 * 
	 * @param res
	 * @param req
	 * @throws UnsupportedEncodingException
	 */
	@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) {
				log.info("取消连接:\t" + rcName);
				new OracleStatusService().cancelToOracle(rcName, operate);
			}
		}
		req.setStatus(200);
	}

	/**
	 * gfs的 volume节点的查询
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/volume/list", method = RequestMethod.POST)
	@ResponseBody
	public String volumeList() throws Exception {
		log.debug("-----/volume/list------");
		String rest = volumeService.getAllvolume();
		return rest;
	}

	/**
	 * 数据迁移功能
	 * 
	 * @param res
	 * @param req
	 * @param form
	 * @throws Exception
	 */
	@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);

		log.debug("------/volume/{name}/move--------");
		if (datas.size() > 0) {
			moveDataService.moveData(datas, form.getSelectNode());
		}
		req.setStatus(200);
	}

	/**
	 * oracle的 汇总功能
	 * 
	 * @param res
	 * @param req
	 * @param form
	 * @throws Exception
	 */
	@RequestMapping(value = "/oracle/{name}/extract", method = RequestMethod.POST)
	public void oracleExtract(HttpServletRequest res, HttpServletResponse req,
			@RequestBody oracleForm form) throws Exception {
		log.error("/oracle/{name}/extract");
		if (null != form.getTarget()) { // 检查请求参数中是否包含汇总库信息
			boolean isConnect = OracleExtract.isConnectTotalOracle(form
					.getTarget()); // 检查汇总库是否可以连接成功，连接成功返回200状态吗，连接失败返回500状态吗
			if (isConnect) {
				req.setStatus(200);
				if (null != form.getInneed() && form.getInneed().size() > 0) {
					for (OracleConnectorParams oracleParams : form.getInneed()) {						
						BasedTask task = new OracleExtractTask(
								oracleParams.getName(), form.getTarget(),
								oracleParams, OracleExtract);
						OracleExtractExecuter oee = new OracleExtractExecuter(
								task);
						new Thread(oee, oracleParams.getName()).start();
					}
				}
			} else
				req.setStatus(500);
		}

	}

	/**
	 * oracle汇总、抽取库的 查询
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/oracle/list", method = RequestMethod.POST)
	@ResponseBody
	public List<GatherOracleInfo> oracleList() throws Exception {
		log.debug("----------getOracleInfo-----------------------");
		List<GatherOracleInfo> result = mySqlService.findAllOracle();
		return result;
	}

	/**
	 * oracle汇总、抽取库的 删除
	 * 
	 * @param req
	 * @param res
	 * @param id
	 * @throws Exception
	 */
	@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.deleteOracle(num);
		log.info("oracleDelete : " + result);
		res.setStatus(200);
	}

	/**
	 * oracle汇总、抽取库的 新增
	 * 
	 * @param res
	 * @param req
	 * @param id
	 * @param oracle
	 * @throws Exception
	 */
	@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);
	}

	/**
	 * oracle汇总、抽取库的 更新
	 * 
	 * @param res
	 * @param req
	 * @param id
	 * @param oracle
	 * @throws Exception
	 */
	@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);
	}

	/**
	 * 迁移 数据 的查询
	 * 
	 * @return
	 * @throws Exception
	 */
	@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;
	}

	/**
	 * 迁移完成后的 删除记录功能
	 * 
	 * @param res
	 * @param req
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@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;
	}

	/**
	 * 迁移数据完成后新增一条数据（暂时去掉，新增功能不在此）
	 * 
	 * @param res
	 * @param req
	 * @param move
	 * @return
	 * @throws Exception
	 */
	@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 1;
	}

	/**
	 * 地区和系统的 code 对应的名称 的 获取
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/code/list", method = RequestMethod.POST)
	@ResponseBody
	public Object findCodeList() throws Exception {
		log.debug("---------/findSystemCode-----------------------");
		Map<String, Object> result = codeService.findAll();
		return result;
	}

	/**
	 * oracle 汇总的 日志 读取
	 * 
	 * @param name
	 * @param res
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/oracle/extract/log", method = RequestMethod.POST)
	@ResponseBody
	public Object getExtractLog(@RequestParam("rcName") String name,
			HttpServletRequest res, HttpServletResponse req) throws Exception {
		log.info("---------/oracle/extract/log-------------------");
		String result = logReadService.readLog(name);		
		// "查看相应日志"
		Map<String, String> log = new HashMap<String, String>();
		log.put(name, result);
		return log;
	}
}
