package com.zzsn.api;

import com.zzsn.common.ReturnUtil;
import com.zzsn.entity.PaserErroreMsg;
import com.zzsn.entity.Site;
import com.zzsn.service.PaserErroreMsgService;
import com.zzsn.util.JSONSerializer;
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 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.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 需要配置模板的站点
 *
 */

@Controller
@RequestMapping("/needsite")
@Slf4j
public class PaserErroreMsgController {
    @Autowired
    PaserErroreMsgService paserErroreMsgService;

    /**
     * 访问site页面
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ModelAndView index() throws Exception {
        log.info("==========进入needTempsite页面==");
        ModelAndView mav = new ModelAndView("needTempsite");
        return mav;
    }

    /**
     * 根据id获取信息
     * @return
     */
    @RequestMapping(value = "/getSiteById", method = RequestMethod.GET)
    @ResponseBody
    public String  getSiteById(String id) throws Exception {
        PaserErroreMsg site = paserErroreMsgService.getById(id);

        return MsgUtil.outSiteJSON(site);
    }

    /**
     * 根据id删除站点信息
     * @return
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.GET)
    @ResponseBody
    public String  deleteById(String id) throws Exception {
        boolean b = paserErroreMsgService.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 = "/getPageDetail", method = RequestMethod.POST)
    public String getPageDetail(HttpServletRequest request,HttpServletResponse response) throws Exception{
        ReturnUtil view=new ReturnUtil();
        Map<String,Object> parameter = getRequestParams(request);
        Page pageParams = getPageParams(request);
        List<Metadata> metaList=BookViewSupport.getColumnTempSite();
        QueryWrapper<PaserErroreMsg> queryWrapper =  new QueryWrapper<>();
        Page<PaserErroreMsg> page = new Page<PaserErroreMsg>(pageParams.getCurrent(), pageParams.getSize());
        if(null!=parameter.get("keywords")) {
            queryWrapper.like("keywords", parameter.get("keywords"));
        }
        if(null!=parameter.get("domain_url")) {
            queryWrapper.like("domain_url", parameter.get("domain_url"));
        }
        queryWrapper.orderByDesc("id");
        try{
            Page<PaserErroreMsg> pageList = paserErroreMsgService.page(page, queryWrapper);
            List<PaserErroreMsg> siteList = pageList.getRecords();
            long count = pageList.getTotal();
            if( siteList != null && count > 0 ){
                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("没有找到符合条件的记录！");
            }
        } catch(Exception e){
            view.setSuccess(false);
            view.setMsg("没有找到符合条件的记录！");
        }

        return ReturnUtil.returnMsg(view).toLowerCase();
    }
    /**
     * 信息列表-表头
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getColumnSite", method =  RequestMethod.POST)
    public String getColumnSite(HttpServletResponse response, HttpServletRequest request) throws Exception{
        StringBuffer result = new StringBuffer();
        try{
            List<Metadata> columns = BookViewSupport.getColumnTempSite();
            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.getSize();
        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("}");
        }

        return result;
    }
}
