package com.manage.controller;

import com.manage.annotation.OptionalLog;
import com.manage.annotation.RequiresPermissions;
import com.manage.entity.Power_Role;
import com.manage.service.cache.CacheManager;
import com.manage.service.Power_RoleService;
import com.manage.service.ImportExcel.ImportExcelUtil;
import com.manage.util.ExceptionPrintUtil;
import com.manage.util.Msg;
import com.manage.util.PageHelper;
import com.manage.vo.ImportExcelEntity;
import com.manage.vo.Power_RoleVo;
import com.manage.vo.Power_UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * @Author:ly
 * @Date:Creatid in 10:10 2019/4/28
 * @Description:
 */

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    Power_RoleService powerRoleService;

    /**
     * @Date 2019-4-25
     * @Author ly
     *  @Description 分页
     * */
    @RequiresPermissions(value="/role/pageUI")
    @RequestMapping("/pageList")
    @ResponseBody
    public PageHelper<Power_RoleVo> list(Power_RoleVo powerRole,HttpServletRequest request){
        PageHelper<Power_RoleVo>pageHelper = new PageHelper<Power_RoleVo>();
        try {
            //统计总记录数
            int total = powerRoleService.getTotal(powerRole,request);
            pageHelper.setTotal(total);
            //查询当前页实体对象
            List<Power_RoleVo> list = powerRoleService.findSomeByMore(powerRole,request);
            pageHelper.setRows(list);
            CacheManager.addExcCount("noExc");
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            CacheManager.addExcCount("exc");
            e.printStackTrace();
        }
        return pageHelper;
    }
    /**
     * @Date 2019-4-25
     * @Author ly
     *  @Description 返回页面
     * */
    @OptionalLog(module = "查看",methods = "角色管理页面")
    @RequiresPermissions(value="/role/pageUI")
    @RequestMapping("/pageUINotDown")
    public String pageUINotDown(){
        CacheManager.addExcCount("noExc");
        return "roleDir/roleNotDown";
    }

    /**
     * @Date 2019-08-02
     * @Author zengwenhe
     *  @Description 验证角色名是否重复
     * */
    @RequestMapping("/checkRoleName")
    @ResponseBody
    public Msg checkRoleName(String roleName) throws Exception{
        Power_Role role = powerRoleService.checkRoleName(roleName);
        CacheManager.addExcCount("noExc");
        if(null != role){
            return Msg.fail("角色名已存在!");
        }else{
            return Msg.success();
        }
    }

    /**
     * @Date 2019-4-25
     * @Author ly
     *  @Description 新增角色
     * */
    @OptionalLog(module = "新增",methods = "角色管理",fieldName = "roleName")
    @RequiresPermissions(value="/role/add")
    @RequestMapping("/add")
    @ResponseBody
    public Msg add(Power_Role powerRole) throws Exception{
        Power_Role role = powerRoleService.checkRoleName(powerRole.getRoleName());
        if(null != role){
            return Msg.fail("角色名不能重复!");
        }else{
            powerRoleService.insertSelective(powerRole);
        }
        CacheManager.addExcCount("noExc");
        return Msg.success();
    }

    /**
     * @Date 2019-4-25
     * @Author ly
     *  @Description 更新角色
     * */
    @OptionalLog(module = "修改",methods = "角色管理",fieldName = "roleName")
    @RequiresPermissions(value="/role/update")
    @RequestMapping("/update")
    @ResponseBody
    public Msg update(Power_Role powerRole,HttpServletRequest request) throws Exception{
        Power_Role role = powerRoleService.checkRoleName(powerRole.getRoleName());
        if(null != role && !role.getRoleId().equals(powerRole.getRoleId())){
            return Msg.fail("角色名不能重复!");
        }else{
            powerRoleService.updateByPrimaryKeySelective(powerRole,request);
        }
        CacheManager.addExcCount("noExc");
        return Msg.success();
    }
    /**
     * @Date 2019-4-25
     * @Author ly
     *  @Description 删除角色
     * */
    @OptionalLog(module = "删除",methods = "角色管理",fieldName = "roleName",tableName = "power_role")
    @RequiresPermissions(value="/role/delete")
    @RequestMapping("/delete")
    @ResponseBody
    public Msg delete(Integer roleId) throws Exception{
        powerRoleService.deleteByPrimaryKey(roleId);
        CacheManager.addExcCount("noExc");
        return Msg.success();
    }
    /**
     * @Date 2019-4-25
     * @Author ly
     *  @Description 查询角色
     * */
    @RequestMapping("/selectRole")
    @ResponseBody
    public Power_Role selectRole(Integer roleId){
        try {
            Power_Role powerRole = powerRoleService.selectByPrimaryKey(roleId);
            CacheManager.addExcCount("noExc");
            return powerRole;
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return null;
        }
    }
    /**
     * @Date 2019-4-25
     * @Author ly
     *  @Description 导出Excel
     * */
    @OptionalLog(module = "导出excel",methods = "角色管理")
    @RequiresPermissions(value="/role/export")
    @RequestMapping("/export")
    public void export(Power_RoleVo powerRole, HttpServletResponse response, HttpServletRequest request){
        try {
            powerRoleService.export(powerRole,response,request);
            CacheManager.addExcCount("noExc");
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            CacheManager.addExcCount("exc");
            e.printStackTrace();
        }
    }
    /**
     * @Date 2019-4-25
     * @Author ly
     *  @Description 导出Excel
     * */
    @OptionalLog(module = "导出excel",methods = "角色管理")
    @RequiresPermissions(value="/role/export")
    @RequestMapping("/exportNotDown")
    public void exportNotDown(Power_RoleVo powerRole, HttpServletResponse response, HttpServletRequest request){
        try {
            powerRoleService.exportNotDown(powerRole,response,request);
            CacheManager.addExcCount("noExc");
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            CacheManager.addExcCount("exc");
            e.printStackTrace();
        }
    }
    /**
     * @Date 2019-4-30
     * @Author ly
     *  @Description 查询角色列表
     * */
    @RequestMapping("/selectList")
    @ResponseBody
    public List<Power_RoleVo> selectList(HttpServletRequest request){
        try {
            List<Power_RoleVo> powerRoles = powerRoleService.selectListByPower(request);
            CacheManager.addExcCount("noExc");
            return  powerRoles;
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @Date 2019-10-11
     * @Author zengwh
     *  @Description 导入excel
     * */
    @OptionalLog(module = "导入excel",methods = "角色管理")
    @RequiresPermissions(value="/role/importExcel")
    @RequestMapping(value="/importExcelNotDown",method = {RequestMethod.POST})
    @ResponseBody
    public ResponseEntity<String> importExcelNotDown(HttpServletRequest request){
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(new MediaType("text","html",Charset.forName("UTF-8")));
        try {
            //读取文件
            MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
            MultipartFile multipartFile = multipartRequest.getFile("upfile");
            //属性名
            String[] fieldNames = {"roleName","remark","effective"};
            //判断集中类中的方法名
            String[] judgeMethods = {"judgeRoleName","judgeRemark","convertEffective"};
            //导入excel的操作
            Power_Role role = new Power_Role();
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            Power_UserVo user = (Power_UserVo)request.getSession().getAttribute("CURRENT_USER");
            role.setCreater(user.getUserName());
            role.setUpdater(user.getUserName());
            role.setCreateDate(fmt.format(new Date()));
            role.setUpdateDate(fmt.format(new Date()));
            //实例化
            ImportExcelUtil.newInstance("power_RoleMapper",role, Power_Role.class);
            //导入excel的操作
            ImportExcelEntity excelEntity = ImportExcelUtil.fileImport(multipartFile,fieldNames, judgeMethods);
            CacheManager.addExcCount("noExc");
            if(excelEntity.getSuccessCount() == 0 && excelEntity.getWrongCount() == 0){
                //无数据
                return new ResponseEntity<String>("无数据!", responseHeaders, HttpStatus.OK);
            }
            if(excelEntity.getWrongCount() == 0){
                //成功
                return new ResponseEntity<String>(null, responseHeaders, HttpStatus.OK);
            }else{
                //有出错数据
                String msgStr = excelEntity.getWorkBookKey()+"@已成功导入"+excelEntity.getSuccessCount()+"条,失败"+excelEntity.getWrongCount()+"条,随后将导出错误记录!";
                return new ResponseEntity<String>(msgStr, responseHeaders, HttpStatus.OK);
            }
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            CacheManager.addExcCount("exc");
            //抛异常
            return new ResponseEntity<String>(e.getMessage(), responseHeaders, HttpStatus.OK);
        }
    }
}

















