package com.mvc.admin.dao.impl;

import com.mvc.admin.bean.LoggIng;
import com.mvc.admin.bean.Permission;
import com.mvc.admin.dao.ILoggIngDao;
import com.mvc.admin.utils.jdbcUtils;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.RowProcessor;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 日志记录 Dao层 实现类
 * Created by JEEP-711 on 2017/7/7.
 */

public class LoggIngDaoImpl implements ILoggIngDao{
    private QueryRunner queryRunner = jdbcUtils.getQueryRuner();
    RowProcessor processor = null;
    public LoggIngDaoImpl(){
        Map<String, String> map = new HashMap<String, String>();
        map.put("pti", "pti");
        // 用构建好的HashMap建立一个BeanProcessor对象
        BeanProcessor bean = new BeanProcessor(map);
        processor = new BasicRowProcessor(bean);
    }

    public List<Permission> getUrl(int id){
        String sql = "select permission.url from jsqx left join permission on jsqx.pid=permission.id left join yhjs on jsqx.rid=yhjs.rid where yhjs.uid=?";
        try {
          return   queryRunner.query(sql,new BeanListHandler<Permission>(Permission.class),id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<LoggIng> getAllLog() {
        List<LoggIng> list = new ArrayList<LoggIng>();
        try {
            String sql = "SELECT * FROM logging";
            return queryRunner.query(sql, new BeanListHandler<LoggIng>(LoggIng.class, processor));
        } catch (SQLException e) {
            System.out.println("查询日志失败");
            throw new RuntimeException(e);
        }
    }

    @Override
    public void addLog(String hostuser, String pti, String met, String ip, String url, String pah, String pms) {
        String sql = "INSERT INTO logging(`hostuser`,`pti`,`met`,`ip`,`url`,`pah`,`pms`) VALUES (?,?,?,?,?,?,?)";
        try {
            queryRunner.update(sql, hostuser,pti,met, ip,url,pah,pms);
            System.out.println("日志新增成功");
        } catch (SQLException e) {
            System.out.println("日志新增失败");
            throw new RuntimeException(e);
        }
    }

    @Override
    public void addJSQX(int rid, int pid){
        try {
            String sql = "INSERT INTO jsqx(`rid`,`pid`) VALUES(?,?)";
            queryRunner.update(sql,rid,pid);
            System.out.println("角色权限新增成功");
        } catch (SQLException e) {
            System.out.println("角色权限新增失败");
            throw new RuntimeException(e);
        }
    }
}
