/**
 * 
 */
package org.ccpit.front;

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

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONNull;
import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.ccpit.base.controller.BaseController;
import org.ccpit.base.controller.Page;
import org.ccpit.base.controller.PageRequest;
import org.ccpit.base.controller.ValidateCodeController;
import org.ccpit.base.user.User;
import org.ccpit.business.coApplication.CoApplicationInfo;
import org.ccpit.business.coApplication.CoApplicationInfoService;
import org.ccpit.business.noticeManage.Notice;
import org.ccpit.business.noticeManage.NoticeService;
import org.ccpit.business.questionsManage.Question;
import org.ccpit.business.questionsManage.QuestionService;
import org.ccpit.business.serviceNetWork.ServiceNetWork;
import org.ccpit.business.serviceNetWork.ServiceNetWorkService;
import org.ccpit.business.taxableGoods.TaxableGoods;
import org.ccpit.business.taxableGoods.TaxableGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * ClassName: IndexController <br/>
 * Function: TODO 原产地证申报系统官网前端控制controller. <br/>
 * Reason: TODO ADD REASON(可选). <br/>
 * date: 2017年4月24日 上午9:08:51 <br/>
 *
 * @author dingwei
 * @version
 * @since JDK 1.8.0
 */
@RestController
public class IndexController extends BaseController {

	@Autowired
	private IndexService indexService;
	@Autowired
	private NoticeService noticeService;
	@Autowired
	private QuestionService questionService;
	@Autowired
	private CoApplicationInfoService coApplicationInfoService;

	@Autowired
	private TaxableGoodsService taxableGoodsService;

	@Autowired
	private ServiceNetWorkService serviceNetWorkService;
	private final Integer NOTICETYPE = 1;
	private final Integer POLICYTYPE = 2;

	@Autowired
	private HttpServletRequest request;

	@RequestMapping(value = "/front/index")
	public ModelAndView index(ModelAndView mv) {
		initLoad(mv, null);
		mv.setViewName("/front/home-page");
		return mv;
	}

	@RequestMapping(value = "/front/hscodeinquery")
	public ModelAndView hscodeinquery(ModelAndView mv) {
		mv.setViewName("/front/hscodeinquery");
		return mv;
	}

	@RequestMapping(value = "/front/thirdPlatform")
	public ModelAndView thirdPlatform(ModelAndView mv) {
		mv.setViewName("/front/thirdPlatform");
		return mv;
	}

	@RequestMapping(value = "/front/queryTaxableGoods")
	public Object queryTaxableGoods(HttpServletRequest request) {
		PageRequest pageRequest = getPage(request);
		String taxNumber = request.getParameter("taxNumber");
		Page<TaxableGoods> pageInformation = taxableGoodsService
				.queryTaxableGoodsList(pageRequest, taxNumber);
		return pageInformation;
	}

	@RequestMapping(value = "/front/serviceNetWork")
	public ModelAndView serviceNetWork(ModelAndView mv) {
		mv.setViewName("/front/serviceNetWork");
		return mv;
	}

	@RequestMapping(value = "/front/aboutCO")
	public ModelAndView centerInfo(ModelAndView mv) {
		mv.setViewName("/front/certificateOfOrigin");
		return mv;
	}

	@RequestMapping(value = "/front/aboutNotice/{id}")
	public ModelAndView aboutNotice(ModelAndView mv, @PathVariable Integer id) {
		initLoad(mv, id);
		mv.addObject("noticeType", changeType(id));
		mv.setViewName("/front/noticeAnnouncement");
		return mv;
	}

	@RequestMapping(value = "/front/aboutNotice")
	public Object queryAllNotice(HttpServletRequest request, Notice Notice) {
		String queryParam = request.getParameter("queryParams");
		PageRequest pageRequest = getPage(request);
		String title = request.getParameter("noticeTitle");
		String newsType = queryParam.split(":")[1];
		Page<Notice> pageInformation = noticeService.queryNotices(pageRequest,
				title, newsType);
		// pageInformation.getRows().forEach(Notice -> {
		// noticeService.createNoticesIndex(Notice);
		// });
		return noticeService.convert(pageInformation);
	}

	@RequestMapping(value = "/front/aboutNoticeContent/{id}")
	public ModelAndView aboutNoticeContent(ModelAndView mv,
			@PathVariable Integer id) {
		Notice notice = noticeService.queryNoticeById(id);
		if (notice.getNoticeType() == 2) {
			mv.addObject("contentName", "政策法规");
		} else if(notice.getNoticeType() == 1){
			mv.addObject("contentName", "通知公告");
		}else if(notice.getNoticeType() == 3){
			mv.addObject("contentName", "链博会专栏");
		}
		mv.addObject("content", notice);
		mv.addObject("noticeType", notice.getNoticeType());
		mv.setViewName("/front/noticeContent");
		notice.setClickVolume(notice.getClickVolume() +1);
		noticeService.update(notice);
		return mv;
	}

	/*
	 * @RequestMapping(value = "/aboutPolicyContent/{id}") public ModelAndView
	 * aboutPolicyContent(ModelAndView mv,
	 * 
	 * @PathVariable Integer id) { Notice notice =
	 * noticeService.queryNoticeById(id); mv.addObject("contentName", "政策法规");
	 * mv.addObject("content", notice); mv.setViewName("/front/noticeContent");
	 * return mv; }
	 */

	@RequestMapping(value = "/front/aboutQuestion")
	public ModelAndView aboutQuestion(ModelAndView mv) {
		initLoad(mv, null);
		mv.setViewName("/front/commonQuestion");
		return mv;
	}

	@RequestMapping(value = "/front/aboutQuestions")
	public Object queryAllQuestion(HttpServletRequest request, Question question) {
		PageRequest pageRequest = getPage(request);
		String title = request.getParameter("title");
		Page<Question> pageInformation = questionService.queryQuestions(
				pageRequest, title);
		// pageInformation.getRows().forEach(Question -> {
		// QuestionService.createQuestionsIndex(Question);
		// });
		return questionService.convert(pageInformation);
	}

	@RequestMapping(value = "/front/aboutQuestionContent/{id}")
	public ModelAndView aboutQuestionContent(ModelAndView mv,
			@PathVariable Integer id) {
		Question question = questionService.queryQuestionById(id);
		mv.addObject("contentName", "常见问题");
		mv.addObject("content", question);
		mv.setViewName("/front/questionContent");
		question.setClickVolume(question.getClickVolume() + 1);
		questionService.update(question);
		return mv;
	}

	@RequestMapping(value = "/front/coApplicationForm")
	public ModelAndView coApplicationForm(ModelAndView mv) {
		mv.addObject("contentName", "CO网上申请");
		mv.setViewName("/front/coApplicationForm");
		return mv;
	}

	@RequestMapping(value = "/front/aboutUS")
	public ModelAndView aboutUs(ModelAndView mv) {
		mv.setViewName("/front/aboutUS");
		return mv;
	}

	@RequestMapping(value = "/front/applyFlow")
	public ModelAndView applyFlow(ModelAndView mv) {
		mv.setViewName("/front/applyFlow");
		return mv;
	}

	// 查询网点
	@RequestMapping(value = "/front/serviceNetWork/{id}")
	public ModelAndView getserviceNetWorks(ModelAndView mv,
			@PathVariable String id) {
		List<ServiceNetWork> serviceNetWorks = serviceNetWorkService
				.queryServiceNetWorksByPId(id);
		mv.addObject("netWorks", serviceNetWorks);
		mv.setViewName("/front/netWorks");
		return mv;
	}

	/**
	 * 
	 * initLoad:(网站首页初始化加载方法). <br/>
	 * 
	 * @author dingwei
	 * @return Date:2017年4月24日上午9:11:39
	 * @since JDK 1.8.0
	 */
	private ModelAndView initLoad(ModelAndView mv, Integer id) {
		List<Notice> noticeList = null;
		List<Notice> policyList = null;
		if (null == id && !"".equals(id)) {
			noticeList = noticeService.queryNoticeList(NOTICETYPE);
			policyList = noticeService.queryNoticeList(POLICYTYPE);
		} else if (NOTICETYPE == id) {
			noticeList = noticeService.queryNoticeList(id);
		} else if (POLICYTYPE == id) {
			policyList = noticeService.queryNoticeList(id);
		}
		List<Question> questionList = questionService.queryQuestionList();
		// 通知公告列表
		mv.addObject("noticeList", noticeList);
		// 政策法规列表
		mv.addObject("policyList", policyList);
		// 常见问题列表
		mv.addObject("questionList", questionList);
		return mv;
	}

	// 全文索引查询
	@RequestMapping(value = "/front/searchIndex")
	public ModelAndView searchIndex(ModelAndView mv) {
		mv.setViewName("front/result");
		String queryString = request.getParameter("keys");
		if ("".equals(queryString)) {
			return mv;
		}
		String[] searchFields = { "title" };
		return mv;
	}

	/**
	 * CO网上申请
	 */
	@RequestMapping(value = "/front/addCoApplicationInfo", produces = "application/json;charset=UTF-8")
	public Object addCoApplicationInfo(HttpServletRequest request,
			CoApplicationInfo coApplicationInfo) {
		String result = "";
		boolean flag = coApplicationInfoService.addCoApplicationInfo(
				coApplicationInfo, request, (User) getUserSession(request));
		if (flag) {
			result = "{ \"flag\": " + flag + ", \"info\": \"申请提交成功！\" }";
		} else {
			result = "{ \"flag\": " + flag + ", \"info\": \"申请提交失败！\" }";
		}
		return result;
	}

	/**
	 * certificate验证页面
	 */

	@RequestMapping(value = "/verify")
	public ModelAndView checkCertificate(ModelAndView mv) {
		mv.setViewName("/front/checkCertificate");
		return mv;
	}

	@RequestMapping(value = "/front/findCertificate")
	@ResponseBody
	public Object findCertificate(@RequestParam String tbApplyNumber,
			@RequestParam String tbPrintNumber,
			@RequestParam String validateCode) {
		Map<String, Object> result = new HashMap<String, Object>();
		if (!ValidateCodeController.validate(request, validateCode)) {
			result.put("status", "error");
			result.put("message", "verification code wrong");
			return result;
		}
		String url = "https://admin-co.ccpit.org/checkCertificate?certificateNo="
				+ tbApplyNumber + "&coSerialNo=" + tbPrintNumber;
//		String url = "http://localhost:8221/checkCertificate?certificateNo="
//				+ tbApplyNumber + "&coSerialNo=" + tbPrintNumber;
		String charset = "utf-8";
		// HttpClientUtil httpClientUtil = new HttpClientUtil();
		// 进行httpclient请求
		DefaultHttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet(url);// 这里发送get请求
		HttpResponse httpResponse;
		try {
			httpResponse = client.execute(request);
			// 第四步：检查相应的状态是否正常：检查状态码的值是200表示正常
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				// 第五步：从相应对象当中取出数据，放到entity当中
				HttpEntity entity = httpResponse.getEntity();
				String response = EntityUtils.toString(entity, "utf-8");
				JSONObject jsonObject = JSONObject.fromObject(response);
				result.putAll(replaceNullValue((Map)jsonObject));
				if (result.size() == 1){
					result.put("status", "error");
					result.put("message", "the cerificate not found");
				}
				client.close();
				// 将entity当中的数据转换为字符串
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// Map<String, String> createMap = new HashMap<String, String>();
		// createMap.put("certificateNo", tbApplyNumber);
		// createMap.put("coSerialNo", tbPrintNumber);
		// String httpOrgCreateTestRtn = httpClientUtil.doPost(url, createMap,
		// charset);
		// System.out.println("result:" + httpOrgCreateTestRtn);

		// HttpMethod method = new PostMethod("https://admin-co.ccpit.org");
		return result;
	}
	
	private Map<String,Object> replaceNullValue(Map<String,Object> map) {
		for(Map.Entry<String, Object> entry: map.entrySet()){
			if (entry.getValue()== JSONNull.getInstance()) {
				map.put(entry.getKey(), "未填写");
			}
			if ("exporter".equals(entry.getKey())) {
				Map<String,Object> temp1 = (Map<String, Object>) entry.getValue();
				map.put("exporter", temp1.get("value"));
			}
			if ("issuer".equals(entry.getKey())) {
				Map<String,Object> temp2 = (Map<String, Object>) entry.getValue();
				map.put("issuer", temp2.get("value"));
			}
		}
		return map;
	}

	private String changeType(Integer id){
		String title = "";
		if(1 == id){
			title = "通知公告";
		}else if(2 == id){
			title = "政策法规";
		}else if(3 == id){
			title = "链博会专栏";
		}
		return title;
	}
}
