package com.manage.controller;

import com.manage.annotation.OptionalLog;
import com.manage.annotation.RequiresPermissions;
import com.manage.dao.Power_LogMapper;
import com.manage.service.cache.CacheManager;
import com.manage.service.LogService;
import com.manage.util.ExportExcelUtil;
import com.manage.util.Msg;
import com.manage.util.PageHelper;
import com.manage.vo.Power_LogVo;
import com.manage.vo.Power_UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @ProjectName:
 * @Description:
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/7/10 14:35
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/7/10 14:35
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Controller
@RequestMapping("otherManage/")
public class Power_LogController {
    @Autowired
    private Power_LogMapper logMapper;
    @Autowired
    private LogService logService;

    /**
     * @MethodName backupDatabase
     * @Description: 跳转到备份数据库页面
     * @Param 无
     * @Returnt otherManage/backupDatabase
     * @Author: 曾文和
     * @CreateDate: 2019-07-10
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-10
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @OptionalLog(module = "查看",methods = "日志管理页面")
    @RequiresPermissions("/otherManage/backupDatabase")
    @RequestMapping("backupDatabase")
    public String backupDatabase(Model model){
        CacheManager.addExcCount("noExc");
        return "otherManage/backupDatabase";
    }

    /**
     * @MethodName getLogList
     * @Description: 获取日志数据表
     * @Param 无
     * @Returnt
     * @Author: 曾文和
     * @CreateDate: 2019-07-10
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-10
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value="getLogList")
    @ResponseBody
    public PageHelper<Power_LogVo> getLogList(Power_LogVo log, String startTime, String endTime, HttpServletRequest request){
        PageHelper<Power_LogVo> pageHelper = new PageHelper<Power_LogVo>();
        try{
            List<Power_LogVo> logs = logMapper.selectAll(log, startTime, endTime);
            int total  = logMapper.getTotal(log, startTime, endTime);
            pageHelper.setTotal(total);
            //匹配权限
            Power_UserVo user = (Power_UserVo) request.getSession().getAttribute("CURRENT_USER");
            if(null != logs && !logs.isEmpty()){
                Set<String> menus = user.getMenus();
                if(null != menus && !menus.isEmpty()){
                    Integer deleteOper = 0;
                    for(String menu : menus){
                        if(StringUtils.isNotBlank(menu)){
                            if("/otherManage/deleteLogById".equals(menu)){
                                deleteOper = 1;
                            }
                        }
                    }
                    for (Power_LogVo obj : logs){
                        obj.setDeleteOper(deleteOper);
                    }
                }
            }
            pageHelper.setRows(logs);
            CacheManager.addExcCount("noExc");
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return null;
        }
        return pageHelper;
    }

    /**
     * @MethodName deleteLogById
     * @Description: 根据id删除日志
     * @Param 无
     * @Returnt
     * @Author: 曾文和
     * @CreateDate: 2019-07-10
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-10
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @OptionalLog(module = "删除",methods = "日志管理",fieldName = "logContent",fieldName1="noticeTypeName",tableName = "Power_Log")
    @RequiresPermissions("/otherManage/deleteLogById")
    @RequestMapping("deleteLogById/{logId}")
    @ResponseBody
    public Msg deleteLogById(@PathVariable("logId")Integer logId){
        try{
            logService.deleteLogById(logId);
            CacheManager.addExcCount("noExc");
            return Msg.success();
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return Msg.fail("删除失败，请联系超管!");
        }
    }

    /**
     * @MethodName deleteLogByIds
     * @Description: 根据id集合批量删除日志
     * @Param 无
     * @Returnt
     * @Author: 曾文和
     * @CreateDate: 2019-07-10
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-10
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @OptionalLog(module = "批量删除",methods = "日志管理")
    @RequestMapping("deleteLogByIds/{ids}")
    @RequiresPermissions("/otherManage/deleteLogByIds")
    @ResponseBody
    public Msg deleteLogByIds(@PathVariable("ids")String ids){
        try{
            String[] idList = ids.split(",");
            String str = "";
            for (int i = 0; i < idList.length; i++) {
                if(StringUtils.isNoneBlank(idList[i])){
                    if(i != idList.length - 1){
                        str += idList[i] + ",";
                    }else{
                        str += idList[i];
                    }
                }
            }
            logService.deleteLogByIds(str);
            CacheManager.addExcCount("noExc");
            return Msg.success();
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return Msg.fail("删除失败，请联系超管!");
        }
    }

    /**
     * @MethodName: exportExcel
     * @Description: 根据搜索条件导出excel
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-27
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-27
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @OptionalLog(module = "导出excel",methods = "日志管理")
    @RequiresPermissions("/otherManage/exportExcel")
    @RequestMapping(value="exportExcel",produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public void exportExcel(HttpServletResponse response, Power_LogVo log, String startTime, String endTime,String checks){
        String tableThNames = "操作人,日志主题,日志内容,备注,操作时间,ip地址";
        String fieldCns = "creater,logTitle,logContent,remark,createDate,ip";
        List<Power_LogVo> logs = new ArrayList<>();
        try {
            if(StringUtils.isNotBlank(checks)){
                logs = logMapper.selectAllByIds(checks);
            }else{
                //构造excel的数据
                logs = logMapper.selectAll(log, startTime, endTime);
            }
            //文件名
            String fileName = "操作日志导出数据(" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ").xls";
            //ExportExcelUtil
            ExportExcelUtil exportExcelUtil = new ExportExcelUtil();
            //导出excel的操作
            exportExcelUtil.expordExcel(tableThNames,fieldCns,logs,fileName,response);
            CacheManager.addExcCount("noExc");
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
        }
    }
}
