package com.controller.log;

import com.config.BaseController;
import com.config.ControllerInterface;
import com.enums.SortEnum;
import com.exception.NitifyException;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.model.Log;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName LogController
 * @Description 日志管理控制器
 * @Author zhangyanwei
 * @Date 2020/11/24 15:36
 * @Version 1.0
 **/
@ControllerInterface(path="/log")
public class LogController extends BaseController {
    Log log = new Log().dao();
    public void index(){
        render("/log/list.html");
    }
    public void  list() throws NitifyException {
        try {
            int type = getParaToInt("type", 0);
            String oper = getPara("oper");
            String create_name = getPara("create_name");
            String lever = getPara("lever");
            String startTime = getPara("startTime");
            String sort = getPara("sort");
            int limit = getParaToInt("limit");
            int pageNum = getParaToInt("page");

            List values = new ArrayList();
            String select = "select t1.ip,t1.log_no,t1.description,t1.oper,t1.start_time,t1.req_status, t1.id,t2.lever,t1.create_name ,t1.type ";
            StringBuilder sb = new StringBuilder(" from log t1 left join t_log_dict t2  on t1.req_path  = t2.method_path where 1=1");
            if (type > 0) {
                sb.append(" and t1.type=?");
                values.add(type);
            } else {
                sb.append(" and t1.type=?");
                values.add(1);
            }

            if (startTime != null && !startTime.equals("")) {
                String[] times = startTime.split(" - ");
                sb.append(" and t1.start_time >= ?  and  t1.start_time <= ?");
                values.add(times[0] + " 00:00");
                values.add(times[1] + " 23:59");
            }
            if (oper != null && !oper.equals("")) {
                if(oper.length()>10){
                    fail(1,"请求参数不合法！");
                    return;
                }
                sb.append(" and t1.oper=?");
                values.add(oper);
            }
            if (lever != null && !lever.equals("")) {
                sb.append(" and t2.lever=?");
                values.add(lever);
            }


            if (StringUtils.isNotBlank(create_name) && !create_name.equals("")) {
                sb.append(" and t1.create_name like ? ");
                values.add("%" + create_name + "%");
            }

            if (sort != null && !create_name.equals("")) {
                sb.append(" order by " + SortEnum.getCodeByName(sort));
            } else {
                sb.append(" order by  t1.id desc ");
            }
            System.out.println("日志审计SQL" + select + sb.toString());
            Page<Record> page = Db.paginate(pageNum, limit,
                    select, sb.toString(), listToArray(values));

            success(page);
        }catch (Exception e){
            e.printStackTrace();
            throw new NitifyException(500,"参数错误");
        }
    }

    /**
     * 日志统计
     */
    public void  sindex(){
        render("/log/log_statistics.html");
    }
    public void statistics() throws Exception{
        Page<Record> page = new Page<>();
        try {


            String create_name = getPara("create_name");
            String oper = getPara("oper");
            String startTime = getPara("startTime");

            String toTime="";
            String condition ="";
            List<Object> args=new ArrayList<>();
            if (startTime != null && !"".equals(startTime)) {

                String[] times = startTime.split(" - ");
                if(Integer.valueOf(times[0].split("-")[0]) > 2021 && Integer.valueOf(times[0].split("-")[0]) < 1970 && Integer.valueOf(times[1].split("-")[0]) > 2021&&Integer.valueOf(times[1].split("-")[0]) < 1970){
                    throw new NitifyException(500,"参数错误");
                }

                if(Integer.valueOf(times[0].split("-")[1]) > 12 && Integer.valueOf(times[0].split("-")[1]) <1 && Integer.valueOf(times[1].split("-")[1]) > 12&&Integer.valueOf(times[1].split("-")[1]) < 1){
                    throw new NitifyException(500,"参数错误");
                }
                condition += " between ?  and ?";
                args.add(times[0]+ " 00:00");
                args.add(times[1] + " 23:59");
                args.add(times[0] + " 00:00");
                args.add(times[1] + " 23:59");
                toTime = "CONCAT('" + times[0] + "',' -- ','" + times[1] + "')";

            } else {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                condition += " between ?  and ?";
                args.add(sdf.format(new Date()) + " 00:00");
                args.add(sdf.format(new Date()) + " 23:59");
                args.add(sdf.format(new Date()) + " 00:00");
                args.add(sdf.format(new Date()) + " 23:59");
                toTime = "CONCAT('" + sdf.format(new Date()) + "',' -- ','" + sdf.format(new Date()) + "')";
            }

            //操作


            if (oper != null && !"".equals(oper)) {
                if(oper.length()>10){
                    fail(1,"请求参数不合法！");
                    return;
                }
                oper = " and oper ='" +oper+ "'";
            }else{
                oper = "";
            }

            if (create_name != null && !"".equals(create_name)) {
                create_name = " and create_name like '%" + create_name + "%'";

            }else{
                create_name ="";
            }
            String sql = " from (select " + toTime + " as toTime, tb3.oper,tb3.successCount,0 as failCount  from (select oper,ifnull(count(1),0) successCount from 	(select * from log where 1=1 and  start_time " + condition + oper + create_name + " and req_status=200  ) tb2 GROUP BY tb2.oper) tb3 " +

                         " union all " +

                         " select " + toTime + " as toTime, tb4.oper,0 as successCount,ifnull(tb4.failCount,0)failCount  from (select oper,ifnull(count(1),0) failCount from 	(select * from log where 1=1 and  start_time  " + condition + oper + create_name + " and req_status=500  ) tb2 GROUP BY tb2.oper) tb4 )temp ";

            //日志统计
            System.out.println("日志统计 --> 时间查询" + sql);
            page = Db.paginate(1,10,
                    "select  * ",sql,listToArray(args));
            success(page);
        }catch (Exception e){
            throw new NitifyException(500,"参数错误");
        }

    }


    /**
     * 日志备份
     */
    public void logBak() {
        Db.update("truncate log_bak");
        int status = 0;
        status = Db.update("replace into log_bak(select * from log)");
        success();
    }

    // 日志恢复

    public void restoreLog() {
        int status = 0;
        status = Db.update( "replace into log(select * from log_bak where date(start_time)<date(date_sub(now(),INTERVAL 6 MONTH)))");
        success();
    }

    /**
     * 日志配置
     */

    public void  cindex(){
        render("/log/log_config.html");
    }
    public void config() {
        int file_size =  getParaToInt("file_size");
        int count = Db.update( "update message_config set file_size = "+file_size);
        success();
    }

    /**
     * 日志配置查看详情
     */

    public void detail() {
         Record record = Db.findFirst("select file_size from message_config limit 1");
         success(record);
    }
}
