/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/

package com.cesgroup.cesmonitor.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cesgroup.cesmonitor.service.MediaService;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 媒体服务控制器
 *
 * @author zhang.erwei
 * @version 1.0.0 2017年5月24日
 */
@Controller
@RequestMapping(value = "/media")
public class MediaController {

    @Autowired
    MediaService mediaService;

    private String getRequestString(final HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            while ((line = in.readLine()) != null) {
                sb.append(line);

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 发送微信
     *
     * @param request
     *            http请求
     * @return 微信发送返回xml字符串
     */
    @RequestMapping(value = "sendByWeixin")
    @ResponseBody
    public String sendByWeixin(final HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            while ((line = in.readLine()) != null) {
                sb.append(line);

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String str = sb.toString();
        int index = str.indexOf(';');
        String sendTo = str.substring(0, index);
        String subject = str.substring(index + 1);
        return mediaService.sendByWeixin(sendTo, subject, null);
    }

    /**
     * 发送短信
     *
     * @param request
     *            http请求
     * @return 微信发送返回xml字符串
     */
    @RequestMapping(value = "sendByShortMessage")
    @ResponseBody
    public String sendByShortMessage(final HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            while ((line = in.readLine()) != null) {
                sb.append(line);

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String str = sb.toString();
        int index = str.indexOf(';');
        String mobile = str.substring(0, index);
        String content = str.substring(index + 1);
        return mediaService.sendByShortMessage(mobile, content);
    }

    /**
     * 通过输入数据库连接参数以及sql语句，获取数据库查询值
     *
     * @param request
     *            http请求
     * @return 返回sql查询值，如果返回0，表示出错
     */
    @ResponseBody
    @RequestMapping(value = "dbQuery")
    public String dbQuery(final HttpServletRequest request) {
        String json = getRequestString(request);
        ObjectMapper mapper = new ObjectMapper();
        Connection conn = null;
        Statement stmt = null;
        try {
            Map<String, Object> map = mapper.readValue(json, Map.class);
            String driver = (String) map.get("driver");
            String url = (String) map.get("url");
            String username = (String) map.get("username");
            String password = (String) map.get("password");
            String column = (String) map.get("column");
            if (column == null || column.trim().equals("")) {
                column = "1";
            }
            int c = Integer.parseInt(column);
            Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);
            stmt = conn.createStatement();
            String sql = (String) map.get("sql");
            ResultSet rs = stmt.executeQuery(sql);
            if (rs.next()) {
                return rs.getString(c);
            } else {
                return "0";
            }
        } catch (SQLException se) {
            se.printStackTrace();
            return "0";
        } catch (Throwable se) {
            return "0";
        } finally {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 检测数据库是否正常连接
     *
     * @param request
     *            http请求
     * @return 1：数据库正常；0：无法连接
     */
    @ResponseBody
    @RequestMapping(value = "dbCheck")
    public String dbCheck(final HttpServletRequest request) {
        String json = getRequestString(request);
        ObjectMapper mapper = new ObjectMapper();
        Connection conn = null;
        try {
            Map<String, Object> map = mapper.readValue(json, Map.class);

            String driver = (String) map.get("driver");
            String url = (String) map.get("url");
            String username = (String) map.get("username");
            String password = (String) map.get("password");
            Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);

        } catch (SQLException se) {
            return "0";
        } catch (Throwable se) {
            return "0";
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return "1";

    }
}
