package com.zzsn.api;

import com.zzsn.common.BaseController;
import com.zzsn.common.ReturnUtil;
import com.zzsn.entity.*;
import com.zzsn.service.ProcessitemService;
import com.zzsn.util.Metadata;
import com.zzsn.util.MsgUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzsn.entity.DocInfo;
import com.zzsn.entity.Processitem;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;


@Controller
@RequestMapping("/search")
@Slf4j
public class BaiduSearchController extends BaseController {
	@Autowired
	ProcessitemService processitemService;

	@RequestMapping(value = "/baiduword", method = RequestMethod.GET)
	public ModelAndView baiduword() {
		ModelAndView mav = new ModelAndView("baiduword");
		return mav;
	}

	@ResponseBody
	@RequestMapping(value = "/keywordsearch" , method = RequestMethod.POST)
	public String keysearch(String keywords,HttpServletRequest request,HttpServletResponse response) {
		ReturnUtil view=new ReturnUtil();
		if(keywords.length()>0) {
			List<DocInfo> docInfoList = processitemService.searchKeyword(keywords);
			Page<DocInfo> pageList=new Page<>();
			pageList.setRecords(docInfoList);
			pageList.setTotal(docInfoList.size());
			List<Metadata> metaList=BookViewSupport.getColumnBaidu();
//			result = setPageJson(pageList, metaList);

			view.setCurrpage(pageList.getCurrent()+"");
			view.setTotalrecords(pageList.getTotal()+"");
			view.setTotalpages((int)(Math.ceil((double)pageList.getTotal()/(double)pageList.getSize()))+"");
			view.setRows(pageList.getRecords());
			view.setSuccess(true);
			view.setMsg("请求成功！");
		}else {
			view.setSuccess(false);
			view.setMsg("请输入参数");
		}

		return ReturnUtil.returnMsg(view).replaceAll("publishDate","publishdate")
				.replaceAll("contentNoTag","contentnotag");
	}
	/**
	 * 根据id获取信息
	 * @return
	 */
	@RequestMapping(value = "/getdetailById", method = RequestMethod.GET)
	@ResponseBody
	public String  getSiteById(String id) throws Exception {
		Processitem site = processitemService.getById(id);

		return MsgUtil.outSiteJSON(site);
	}
	/**
	 * 根据id删除站点信息
	 * @return
	 */
	@RequestMapping(value = "/deleteById", method = RequestMethod.GET)
	@ResponseBody
	public String  deleteById(String id) throws Exception {
		boolean b = processitemService.removeById(id);
		String result="";
		if(b){
			result="\"success\": true,\"desc\":\"删除成功\"";
		}else{
			result="\"success\": false,\"desc\":\"删除失败\"";
		}

		return MsgUtil.outSiteJSON(result);
	}
	/**
	 * 查询分页数据获取
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/getPageBaiduDetail", method = RequestMethod.POST)
	public String getPageDetail(HttpServletRequest request,HttpServletResponse response) throws Exception{
		Map<String,Object> parameter = getRequestParams(request);
//		Page pageParams = getPageParams(request);
		List<Metadata> metaList=BookViewSupport.getColumnBaidu();
		StringBuilder result = new StringBuilder("{");

		String pageNo = request.getParameter("page")==null?"1": request.getParameter("page");
		String pageSize = request.getParameter("rows")==null?"10":request.getParameter("rows");


		QueryWrapper<Processitem> queryWrapper =  new QueryWrapper<>();
		Page<Processitem> page = new Page<Processitem>(Long.parseLong(pageNo), Long.parseLong(pageSize));
		if(null!=parameter.get("keywords")) {
			queryWrapper.like("keywords", parameter.get("keywords"));
		}

		queryWrapper.orderByDesc("id");
		try{
			Page<Processitem> pageList = processitemService.page(page, queryWrapper);
			List<Processitem> siteList = pageList.getRecords();
			Collections.sort(siteList, new Comparator<Processitem>() {
				@Override
				public int compare(Processitem o1, Processitem o2) {
					//降序
					return o1.getId().compareTo(o2.getId());
				}
			});
			pageList.setRecords(siteList);
//			List<Processitem> sites = processitemService.list(queryWrapper);
			long count = pageList.getTotal();
			if( siteList != null && count > 0 ){
				result = setPageJson(pageList, metaList);
			}else {
				result.append("\"success\": true,\"desc\": \"没有找到符合条件的记录\",\"currpage\": \"1\", \"totalpages\":\"0\", \"totalrecords\":\"0\",\"rows\": []}");
			}
		} catch(Exception e){
			result.append("\"success\": true,\"desc\": \"没有找到符合条件的记录\",\"currpage\": \"1\", \"totalpages\":\"0\", \"totalrecords\":\"0\",\"rows\": []}");
			e.printStackTrace();
		}

		return writerMessageToClient(response, result.toString());
	}

	/**
	 * 信息列表-表头
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/getColumnBaidu", method =  RequestMethod.POST)
	public String getColumnSite(HttpServletResponse response, HttpServletRequest request) throws Exception{
		StringBuffer result = new StringBuffer();
		try{
			List<Metadata> columns = BookViewSupport.getColumnBaidu();
			if( columns!=null && columns.size()>0 ){
				result.append("{\"success\":true, \"desc\":\"请求成功\", \"colNames\":[\"id\"");
				for(Metadata meta:columns){
					result.append(",\""+meta.getDescribe()+"\"");
				}
				result.append("],\"colModel\":[");
				result.append(" {\"name\": \"id\", \"index\": \"id\", \"width\": \"10\", \"align\": \"center\", \"sortable\": false, \"hidden\":true} ");

				for(Metadata meta:columns){
					String length = "";
					if(StringUtils.isNotBlank(meta.getWidth()))
						length = meta.getWidth();
					else
						length = meta.getDescribe().getBytes("UTF-8").length*6+20+"";
					result.append(", {\"name\": \""+meta.getName().toLowerCase()+"\", \"index\": \""+meta.getName().toLowerCase()+"\", \"width\": \""+length+"\", \"align\": \""+meta.getAlign()+"\", \"sortable\": true, \"hidden\":false} ");
				}

				result.append(" ]}");
			} else {
				result.append("{\"success\": false,\"msg\":\"请求失败\"}");
			}
		} catch(Exception e){
			result.append("{\"success\": false,\"msg\":\"请求失败\"}");
			e.printStackTrace();
		}
		return writerMessageToClient(response,result.toString());
	}

	/**
	 * 像浏览器返回JSON格式相应信息
	 * @param response
	 * @param message
	 * @return
	 */
	public String writerMessageToClient(HttpServletResponse response, String message) throws IOException {
		response.reset();
		response.setContentType("text/plain;charset=UTF-8");
		PrintWriter writer = response.getWriter();
		writer.append(message.replaceAll("null", "").replaceAll("\r\n", "  "));
		writer.flush();
		return null;
	}

	@SuppressWarnings("unchecked")
	public Page getPageParams(HttpServletRequest request){
		Page page = new Page();
		String pageNo = request.getParameter("page");
		String pageSize = request.getParameter("rows");
		String orderBy = request.getParameter("sidx");
		String order = request.getParameter("sord");

		if( StringUtils.isNotBlank(pageNo)){
			page.setCurrent(Integer.valueOf(pageNo));
		}
		if( StringUtils.isNotBlank(pageSize)){
			page.setSize(Integer.valueOf(pageSize));
		}
		return page;
	}

	/**
	 * 自动封装所有请求参数
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map<String,Object> getRequestParams(HttpServletRequest request){
		Map<String,Object> rqParams = new HashMap<String,Object>();
		Enumeration enums = request.getParameterNames();
		while (enums.hasMoreElements()) {
			String paramName = (String) enums.nextElement();
			String paramValue = request.getParameter(paramName);
			if(StringUtils.isNotBlank(paramValue)){
				if(!StringUtils.equals("measure", paramName)){
					paramValue = paramValue.replaceAll(",", "','");
				}
				rqParams.put(paramName, paramValue);
			}
		}
		return rqParams;
	}

	/**
	 * 组装数据为json格式
	 * @param pageList
	 * @param metaList
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static StringBuilder setPageJson(Page pageList, List<Metadata> metaList){
		StringBuilder result = new StringBuilder("{");
//		List<Site> dataList = pageList.getRecords();
//		long count = pageList.getTotal();
//		if( dataList != null && count > 0 ){
//			result.append("\"success\": true,\"desc\": \"操作成功\",");
//			result.append("\"currpage\": \""+pageList.getCurrent()+"\",");//当前页
//			int totalPages = (int)(Math.ceil((double)pageList.getTotal()/(double)pageList.getSize()));
//			result.append("\"totalpages\":\""+totalPages+"\",");//总页数
//			result.append("\"totalrecords\":\"").append(count).append("\",");//总记录数
//			result.append("\"rows\": ");
//			String serialize = JSONSerializer.serialize(dataList);
//			result.append(serialize);
//			result.append("}");
//		}
		List<DocInfo> dataList = pageList.getRecords();
		long count = pageList.getTotal();
		if( dataList != null && count > 0 ){
			result.append("\"success\": true,\"desc\": \"操作成功\",");
			result.append("\"currpage\": \""+pageList.getCurrent()+"\",");//当前页
			int totalPages = (int)(Math.ceil((double)pageList.getTotal()/(double)pageList.getSize()));
			result.append("\"totalpages\":\""+totalPages+"\",");//总页数
			result.append("\"totalrecords\":\"").append(count).append("\",");//总记录数
			//	result.append("\"userdata\":{\"record_day\":\""+dataList.get(0).get("record_day")+"\"},");
			result.append("\"rows\": [");
			String sep1 = "";
			String sep2 = "";
			for (DocInfo docInfo : dataList) {
				Map<String,String> map=new HashMap<>();
				map.put("id",docInfo.id);
				map.put("title",docInfo.getTitle());
				map.put("keywords",docInfo.getKeywords());
				map.put("origin",docInfo.getOrigin());
				map.put("sourceaddress",docInfo.getSourceaddress());
				map.put("publishDate",docInfo.getPublishDate());
				map.put("summary",docInfo.getSummary());
				map.put("contentNoTag",docInfo.getContentWithTag());
				result.append(sep1).append("{");
				sep2 = "";
				for(Metadata meta : metaList){
					String key = meta.getName();
					String value=map.get(key)==null?"":map.get(key).toString();
					value = value.replace("\"", "\\\"");

					result.append(sep2).append("\"").append(key.toLowerCase()).append("\":\"");

					result.append(value).append("\"");

					sep2 = ",";
				}
				result.append("}");
				sep1 = ",";
			}
			result.append("]}");
//				result = BookViewUtils.SetPageJson(pageList, metaList);
		}else {
			result.append("\"success\": true,\"desc\": \"没有找到符合条件的记录\",\"currpage\": \"1\", \"totalpages\":\"0\", \"totalrecords\":\"0\",\"rows\": []}");
		}
		return result;
	}
}
