package com.emr.controller.otherManage;

import com.alibaba.fastjson.JSON;
import com.emr.dao.emrLog.Emr_LogMapper;
import com.emr.entity.Power_User;
import com.emr.entity.ResultUtil;
import com.emr.entity.emrLog.Emr_Log;
import com.emr.service.emrLog.LogService;
import com.emr.util.ExceptionPrintUtil;
import com.emr.util.ExportExcelUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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 BackDatabaseController {
    @Autowired
    private Emr_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
     */
    @RequiresPermissions("/otherManage/backupDatabase")
    @RequestMapping("backupDatabase")
    public String backupDatabase(){
        return "otherManage/backupDatabase";
    }

    /**
     * 接口借阅日志
     * @return
     */
    @RequiresPermissions("/otherManage/interfaceDatabase")
    @RequestMapping("interfaceDatabase")
    public String interfaceDatabase(){
        return "otherManage/interfaceDatabase";
    }


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

    /**
     * 接口借阅日志查询
     * @param page
     * @param limit
     * @param log
     * @param startTime
     * @param endTime
     * @param request
     * @return
     */
    @RequestMapping("getLogListIf")
    @ResponseBody
    public String getLogListIf(Integer page, Integer limit, Emr_Log log, String startTime, String endTime, HttpServletRequest request){
        if(null != page && null != limit){
            PageHelper.startPage(page, limit);
        }
        try{
            List<Emr_Log> logs = logMapper.selectAllByFont(log, startTime, endTime);
            //匹配权限
            Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
            Set<String> menus = user.getMenus();
            if(null != logs && !logs.isEmpty()){
                if(null != menus && !menus.isEmpty()){
                    int deleteOper = 0;
                    for(String menu : menus){
                        if(StringUtils.isNotBlank(menu)){
                            if("/otherManage/deleteLogById".equals(menu)){
                                deleteOper = 1;
                            }
                        }
                    }
                    for (Emr_Log obj : logs){
                        obj.setDeleteOper(deleteOper);
                    }
                }
            }
            PageInfo pageInfo = new PageInfo<>(logs);
            return JSON.toJSONString(pageInfo);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName deleteLogById
     * @Description: 根据id删除日志
     * @Param 无
     * @Returnt
     * @Author: 曾文和
     * @CreateDate: 2019-07-10
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-10
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/otherManage/deleteLogById")
    @RequestMapping("deleteLogById/{logId}")
    @ResponseBody
    public ResultUtil deleteLogById(@PathVariable("logId")Integer logId) throws Exception{
        logService.deleteLogById(logId);
        return ResultUtil.ok();
    }

    /**
     * @MethodName deleteLogByIds
     * @Description: 根据id集合批量删除日志
     * @Param 无
     * @Returnt
     * @Author: 曾文和
     * @CreateDate: 2019-07-10
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-10
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("deleteLogByIds/{ids}")
    @RequiresPermissions("/otherManage/deleteLogByIds")
    @ResponseBody
    public ResultUtil deleteLogByIds(@PathVariable("ids")String ids) throws Exception{
        String[] idList = ids.split(",");
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < idList.length; i++) {
            if(StringUtils.isNoneBlank(idList[i])){
                if(i != idList.length - 1){
                    str.append(idList[i]).append(",");
                }else{
                    str.append(idList[i]);
                }
            }
        }
        logService.deleteLogByIds(str.toString());
        return ResultUtil.ok();
    }

    /**
     * @MethodName: exportExcel
     * @Description: 根据搜索条件导出excel
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-27
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-27
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/otherManage/exportExcel")
    @RequestMapping(value="exportExcel",produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public void exportExcel(HttpServletResponse response, Emr_Log log, String startTime, String endTime,String checks){
        String tableThNames = "操作人,日志主题,日志内容,备注,操作时间,ip地址";
        String fieldCns = "creater,logTitle,logContent,remark,createDate,ip";
        List<Emr_Log> logs = new ArrayList<>();
        try {
            //构造excel的数据
            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);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
    }
}
