package com.eactive.eai.rms.onl.manage.control.history;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.eactive.eai.rms.common.base.OnlBaseAnnotationController;
import com.eactive.eai.rms.common.vo.GridResponse;
import com.google.gson.Gson;

@Controller
public class ControlHistoryManController extends OnlBaseAnnotationController {

	@Autowired
	private ControlHistoryManService service;

	@RequestMapping(value = "/onl/admin/control/controlHistoryMan.view")
	public String viewList() {
		return "/onl/admin/control/controlHistoryMan";
	}

	@RequestMapping(value = "/onl/admin/control/controlHistoryMan.json", params = "cmd=LIST")
	public ResponseEntity<GridResponse<ControlHistoryManUI>> selectList(HttpServletRequest request, Pageable pageable,
			ControlHistoryManUISearch uiSearch) {
		Page<ControlHistoryManUI> pageUI = service.selectList(pageable, uiSearch);
		return ResponseEntity.ok(new GridResponse<ControlHistoryManUI>(pageUI));
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/onl/admin/control/controlHistoryMan.excel", params = "cmd=LIST_GRID_TO_EXCEL")
	public ModelAndView listGridToExcel(HttpServletRequest request, HttpServletResponse response,
			ControlHistoryManUISearch uiSearch, @RequestParam Map<String, Object> paramMap) throws Exception {

		HashMap<String, Object> resultMap = new HashMap<>();

		String headersStr = (String) paramMap.get("headersStr");
		headersStr = headersStr.substring(0, headersStr.length() - 1);
		paramMap.put("headersStr", headersStr);

		Gson gson = new Gson();
		Map<String, List<?>> list = service.selectListToExcel(uiSearch);

		String jsonStr = gson.toJson(list.get("list"));
		HashMap<String, Object>[] list2 = gson.fromJson(jsonStr, HashMap[].class);

		String[] headers = gson.fromJson((String) paramMap.get("header"), String[].class);
		String[] headerTitles = gson.fromJson((String) paramMap.get("headerTitle"), String[].class);

		resultMap.put("headers", headers);
		resultMap.put("headerTitles", headerTitles);
		resultMap.put("datas", list2);
		resultMap.put("fileName", paramMap.get("fileName"));
		return new ModelAndView("excelView", resultMap);
	}
}