package com.ag.web.edi;

import com.ag.edi.IEdiService;
import com.ag.secp.platform.common.CommonUtil;
import com.ag.secp.platform.spring.SpringContextHolder;
import com.wb.util.WebUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * edi日志查询
 * Created by shaoqiang on 2017/6/23.
 */
public class EdiLogInfoController {

    /**
     * 启动edi
     * @param request
     * @param response
     */
    public static void startedi(HttpServletRequest request, HttpServletResponse response) {
        IEdiService ediService=(IEdiService) SpringContextHolder.getBean("ediService");
        Map dataMap=new HashMap();
        ediService.startEdi("id",dataMap);
    }

    /**
     * 停止edi
     * @param request
     * @param response
     */
    public static void stopedi(HttpServletRequest request, HttpServletResponse response) {
        IEdiService ediService=(IEdiService) SpringContextHolder.getBean("ediService");
        Map dataMap=new HashMap();
        ediService.stopedi("id");
    }


    /**
     * 获取错误日志
     *
     * @param request
     * @param response
     */
    public static void queryMessageErrorlog(HttpServletRequest request, HttpServletResponse response) {

        String id = request.getParameter("cId");
        Criteria criteria = new Criteria();
        criteria.and("mrlLogId").is(id);


        Query query = new Query(criteria);
        MongoTemplate mongoTemplate = (MongoTemplate) SpringContextHolder.getBean("mongoTemplate");
        List<ELogError> infoStateList = mongoTemplate.find(query, ELogError.class);
        StringBuffer buffer = new StringBuffer("");
        int h = 0;
        for (int i = 0; infoStateList != null && i < infoStateList.size(); i++) {
            if (i > 0) buffer.append(",");
            buffer.append("{");
            try {
                ELogError log = infoStateList.get(i);


                java.lang.reflect.Field[] fields = log.getClass().getDeclaredFields();
                for (int ia = 0; ia < fields.length; ia++) {
                    String name = fields[ia].getName();
                    if (PropertyUtils.isReadable(log, name) && PropertyUtils.isWriteable(log, name)) {

                        if (name.equals("description")) {
                            buffer.append("\"" + name + "\":\"" + BeanUtils.getProperty(log, name).replace("\n","") + "\"");
                        } else
                            buffer.append("\"" + name + "\":\"" + BeanUtils.getProperty(log, name) + "\"");
                        buffer.append(",");
                    }

                }


            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }

            buffer.append("}");
            h = i;
        }

        StringBuffer str = new StringBuffer();
        str.append("{\"success\":true");
        str.append(",\"metaData\":{\"fields\":[");

        String fieldName = "mrLogId";
        String type = "string";


        java.lang.reflect.Field[] fields = new ELogError().getClass().getDeclaredFields();
        processfieldType(str, fields);


        str.append("]},\"rows\":[");
        str.append(buffer).append("],\"total\":" + h + "}");
        try {
            WebUtil.send(response, str);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * ???????????
     *
     * @param request
     * @param response
     */
    public static void queryMessageInfolog(HttpServletRequest request, HttpServletResponse response) {

        String id = request.getParameter("cId");
        Criteria criteria = new Criteria();
        criteria.and("mrlLogId").is(id);
        //criteria.and("mrltime").gte("2017-06-20 22:00");
        Query query = new Query(criteria);
        MongoTemplate mongoTemplate = (MongoTemplate) SpringContextHolder.getBean("mongoTemplate");
        List<MessageInfoState> infoStateList = mongoTemplate.find(query, MessageInfoState.class);
        StringBuffer buffer = new StringBuffer("");
        int h = 0;
        for (int i = 0; infoStateList != null && i < infoStateList.size(); i++) {
            if (i > 0) buffer.append(",");
            buffer.append("{");
            try {
                MessageInfoState log = infoStateList.get(i);


                java.lang.reflect.Field[] fields = log.getClass().getDeclaredFields();
                for (int ia = 0; ia < fields.length; ia++) {
                    String name = fields[ia].getName();
                    if (PropertyUtils.isReadable(log, name) && PropertyUtils.isWriteable(log, name)) {
                        buffer.append("\"" + name + "\":\"" + BeanUtils.getProperty(log, name) + "\"");
                        buffer.append(",");
                    }

                }


            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }

            buffer.append("}");
            h = i;
        }

        StringBuffer str = new StringBuffer();
        str.append("{\"success\":true");
        str.append(",\"metaData\":{\"fields\":[");

        String fieldName = "mrLogId";
        String type = "string";


        java.lang.reflect.Field[] fields = new MessageInfoState().getClass().getDeclaredFields();
        processfieldType(str, fields);


        str.append("]},\"rows\":[");
        str.append(buffer).append("],\"total\":" + h + "}");
        try {
            WebUtil.send(response, str);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 查询路由信息
     *
     * @param request
     * @param response
     */

    public static void findMessageroutelog(HttpServletRequest request, HttpServletResponse response) {
        MongoTemplate mongoTemplate = (MongoTemplate) SpringContextHolder.getBean("mongoTemplate");


        Criteria criteria = new Criteria();
        criteria.and("insTimestamp").gt(CommonUtil.getDate(request.getParameter("startdatetime"), "yyyy-MM-dd HH:mm:ss"))
                .lt(CommonUtil.getDate(request.getParameter("enddatetime"), "yyyy-MM-dd HH:mm:ss"));


        Query query = new Query(criteria);
        query.with(new Sort(Sort.Direction.DESC, "create_time "));
        List<MessageRouteLog> routeLogs = mongoTemplate.find(query, MessageRouteLog.class);


        // DBCursor scr = mongoTemplate.getCollection("messageRouteLog").find();
        StringBuffer buffer = new StringBuffer("");

        int h = 0;

        for (int i = 0; i < routeLogs.size(); i++) {
            if (i > 0) buffer.append(",");
            buffer.append("{");
            MessageRouteLog log = routeLogs.get(i);

            try {
                // MessageRouteLog log = Beanutil.dbObject2Bean(da, new MessageRouteLog());
                java.lang.reflect.Field[] fields = log.getClass().getDeclaredFields();
                for (int ia = 0; ia < fields.length; ia++) {
                    String name = fields[ia].getName();
                    if (PropertyUtils.isReadable(log, name) && PropertyUtils.isWriteable(log, name)) {
                        buffer.append("\"" + name + "\":\"" + BeanUtils.getProperty(log, name) + "\"");
                        buffer.append(",");
                    }

                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }

            buffer.append("}");
            h = i;
        }

        StringBuffer str = new StringBuffer();
        str.append("{\"success\":true");
        str.append(",\"metaData\":{\"fields\":[");

        String fieldName = "mrLogId";
        String type = "string";


        java.lang.reflect.Field[] fields = new MessageRouteLog().getClass().getDeclaredFields();
        processfieldType(str, fields);


        str.append("]},\"rows\":[");
        str.append(buffer).append("],\"total\":" + h + "}");
        try {
            WebUtil.send(response, str);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * json??????
     *
     * @param str
     * @param fields
     */
    public static void processfieldType(StringBuffer str, Field[] fields) {
        for (int ia = 0; ia < fields.length; ia++) {
            String name = fields[ia].getName();
            String types = fields[ia].getType().getName();
            if (ia > 0) str.append(",");
            if (types.equals("long")) {
                types = "long";
            }
            if (types.equals("java.lang.String")) {
                types = "string";
            }
            if (types.equals("java.lang.Long")) {
                types = "long";
            }
            if (types.equals("java.util.Date")) {
                types = "date";
            }

            str.append("{\"name\":\"" + name + "\",\"type\":\"" + types + "\"}");

        }
    }


    public static void main(String args[]) throws IOException {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("mongodb\\spring-mongo.xml");
        MongoTemplate mongoTemplate = (MongoTemplate) ctx.getBean("mongoTemplate");


    }
}
