package com.zzsn.api;

import com.zzsn.common.cache.MemcachedUtils;
import com.zzsn.entity.DocInfo;
import com.zzsn.entity.Site;
import com.zzsn.entity.SiteTemplate;
import com.zzsn.service.SiteService;
import com.zzsn.util.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzsn.util.JSONSerializer;
import com.zzsn.util.Metadata;
import com.zzsn.util.MsgUtil;
import com.zzsn.util.VerifySiteUtil;
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("/site")
@Slf4j
public class SiteCollectionController {
    @Autowired
    SiteService siteService;

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

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

        return MsgUtil.outSiteJSON(site);
    }
    /**
     * 对配置的站点信息进行验证
     * @return
     */
    @RequestMapping(value = "/verifyById", method = RequestMethod.GET)
    @ResponseBody
    public String  verifyById(String id) throws Exception {
        Site site = siteService.getById(id);

        return MsgUtil.outSiteJSON(site);
    }
    /**
     * 根据id删除站点信息
     * @return
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.GET)
    @ResponseBody
    public String  deleteById(String id) throws Exception {
        Site site = siteService.getById(id);
        MemcachedUtils.del("domainUri_"+site.getDomainUri());
        boolean b = siteService.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{
        Map<String,Object> parameter = getRequestParams(request);
        Page pageParams = getPageParams(request);
        List<Metadata> metaList=BookViewSupport.getColumnSite();
        StringBuilder result = new StringBuilder("{");

        QueryWrapper<Site> queryWrapper =  new QueryWrapper<>();
        Page<Site> page = new Page<Site>(pageParams.getCurrent(), pageParams.getSize());
        if(null!=parameter.get("name")) {
            queryWrapper.like("name", parameter.get("name"));
        }
        if(null!=parameter.get("domainUri")) {
            queryWrapper.like("domain_uri", parameter.get("domainUri"));
        }
        queryWrapper.orderByDesc("id");
        try{
            Page<Site> pageList = siteService.page(page, queryWrapper);
            List<Site> siteList = pageList.getRecords();
            List<Site> sites = siteService.list(queryWrapper);
            long count = sites.size();
            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();
        }
        String s = result.toString();
        s=s.replaceAll("domainUri","domainuri")
                .replaceAll("matchTitle","matchtitle")
                .replaceAll("matchContent","matchcontent")
                .replaceAll("createDate","createdate");
        return writerMessageToClient(response,s);
    }
    /**
     * 信息列表-表头
     * @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.getColumnSite();
            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());
    }

    /**
     * 保存配置的信息模板
     * @param siteEntity
     * @return
     */
    @PostMapping(value = "/save")
    @ResponseBody
    public String save(@RequestBody  Site siteEntity) {
        StringBuffer result = new StringBuffer();
        String id = siteEntity.getId();
        if(null==id) {
            QueryWrapper<Site> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("DOMAIN_URI", siteEntity.getDomainUri());
            List<Site> siteList = siteService.list(queryWrapper);
            if (siteList.size() < 1) {
                boolean flag = siteService.save(siteEntity);
                if (flag) {
                    result.append("{\"success\": true,\"msg\":\"保存成功\"}");
                } else {
                    result.append("{\"success\": false,\"msg\":\"保存失败\"}");
                }
            } else {
                boolean flag = siteService.updateById(siteEntity);
                result.append("{\"success\": true,\"msg\":\"站点配置更新成功\"}");
            }
        }else {
            boolean flag = siteService.updateById(siteEntity);
            result.append("{\"success\": true,\"msg\":\"站点配置更新成功\"}");
        }
        return result.toString();
    }

    /**
     * 对配置的模板进行测试验证 并进行状态修改
     * @param id
     * @return
     */
    @RequestMapping(value = "/verifySite", method = RequestMethod.GET)
    @ResponseBody
    public String verifySite(String id) {
        Site site = siteService.getById(id);
        SiteTemplate siteTemplate=new SiteTemplate();
        siteTemplate.setMatchTitle(site.getMatchTitle());
        siteTemplate.setMatchSummary(site.getMatchSummary());
        siteTemplate.setMatchContent(site.getMatchContent());
        siteTemplate.setMatchAuthor(site.getMatchAuthor());
        siteTemplate.setMatchOrigin(site.getMatchOrigin());
        siteTemplate.setMatchPublishDate(site.getMatchPublishDate());
        VerifySiteUtil verifySiteUtil=new VerifySiteUtil();

        DocInfo docInfo = verifySiteUtil.catchWebNews(siteTemplate, site.getUri());
        System.out.println(docInfo.getTitle());
        return MsgUtil.outSiteJSON(docInfo);
    }

    /**
     * 对配置的模板进行测试验证 并进行状态修改
     * @param id
     * @return verifystatus
     */
    @RequestMapping(value = "/verifystatus", method = RequestMethod.GET)
    @ResponseBody
    public String verifystatus(String id) {
        QueryWrapper<Site> queryWrapper =  new QueryWrapper<>();
        queryWrapper.eq("","1");
        siteService.update(queryWrapper);
        Site site = siteService.getById(id);
        SiteTemplate siteTemplate=new SiteTemplate();
        siteTemplate.setMatchTitle(site.getMatchTitle());
        siteTemplate.setMatchSummary(site.getMatchSummary());
        siteTemplate.setMatchContent(site.getMatchContent());
        siteTemplate.setMatchAuthor(site.getMatchAuthor());
        siteTemplate.setMatchOrigin(site.getMatchOrigin());
        siteTemplate.setMatchPublishDate(site.getMatchPublishDate());
        VerifySiteUtil verifySiteUtil=new VerifySiteUtil();

        DocInfo docInfo = verifySiteUtil.catchWebNews(siteTemplate, site.getUri());
        System.out.println(docInfo.getTitle());
        return MsgUtil.outSiteJSON(docInfo);
    }
    /**
     * 像浏览器返回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;
    }
}
