package com.manage.controller;

import com.manage.annotation.OptionalLog;
import com.manage.annotation.RequiresPermissions;
import com.manage.dao.Power_User_DictMapper;
import com.manage.encrypt.Base64;
import com.manage.encrypt.MD5;
import com.manage.entity.Power_Dept;
import com.manage.entity.Power_User;
import com.manage.service.Power_DeptService;
import com.manage.service.cache.CacheManager;
import com.manage.service.ImportExcel.ImportExcelUtil;
import com.manage.util.*;
import com.manage.vo.*;
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 com.manage.service.Power_UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
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.io.OutputStream;
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/15
 * @Description:
 */

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private Power_UserService powerUserService;
    @Autowired
    private Power_DeptService deptService;
    @Autowired
    private Power_User_DictMapper userDictMapper;
    @RequiresPermissions(value="/user/pageUI")
    @ResponseBody
    @RequestMapping("/pageList")
    public PageHelper<Power_UserVo> list(Power_UserVo powerUser, HttpServletRequest request){
        PageHelper<Power_UserVo>pageHelper = new PageHelper<Power_UserVo>();
        try {
            int total = powerUserService.getTotal(powerUser,request);
            pageHelper.setTotal(total);
            List<Power_UserVo>list = powerUserService.findSomeByMore(powerUser,request);
            pageHelper.setRows(list);
            CacheManager.addExcCount("noExc");
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
        }
        return pageHelper;
    }

    @OptionalLog(module = "查看",methods = "用户管理页面")
    @RequiresPermissions(value="/user/pageUI")
    @RequestMapping("/pageUI")
    public String pageUI(Model model,HttpServletRequest request){
        CacheManager.addExcCount("noExc");
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        //根据登陆者查询所属医院id。非系统管理员，查询所属医院id
        Integer dictId  = null;
        if(!user.getRoleId().equals(0)){
            Power_User_Dict power_user_dict = userDictMapper.selectDictIdByUserId(user.getUserId());
            dictId = power_user_dict.getDictId();
        }
        List<Power_DeptVo> depts = deptService.selectDeptByDictId(dictId,null);
        model.addAttribute("depts",depts);
        return "userDir/user";
    }
    @OptionalLog(module = "查看",methods = "用户管理页面")
    @RequiresPermissions(value="/user/pageUI1")
    @RequestMapping("/pageUI1")
    public String pageUI1(Model model,HttpServletRequest request){
        CacheManager.addExcCount("noExc");
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        //根据登陆者查询所属医院id。非系统管理员，查询所属医院id
        Integer dictId  = null;
        if(!user.getRoleId().equals(0)){
            Power_User_Dict power_user_dict = userDictMapper.selectDictIdByUserId(user.getUserId());
            dictId = power_user_dict.getDictId();
        }
        List<Power_DeptVo> depts = deptService.selectDeptByDictId(dictId,null);
        model.addAttribute("depts",depts);
        return "userDir/user1";
    }

    @OptionalLog(module = "导出excel",methods = "用户管理")
    @RequiresPermissions(value="/user/export")
    @RequestMapping("/export")
    public void download(Power_UserVo powerUser,HttpServletRequest request,HttpServletResponse response){
        try {
            powerUserService.export(powerUser,request,response);
            CacheManager.addExcCount("noExc");
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
        }
    }
    @OptionalLog(module = "导出excel",methods = "用户管理")
    @RequiresPermissions(value="/user/export")
    @RequestMapping("/export1")
    public void download1(Power_UserVo powerUser,HttpServletRequest request,HttpServletResponse response){
        try {
            powerUserService.export1(powerUser,request,response);
            CacheManager.addExcCount("noExc");
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
        }
    }

    @RequestMapping("/checkUserName")
    @ResponseBody
    public Msg checkUserName(String userName){
        try {
            List<Power_User> list = powerUserService.checkUserName(userName);
            CacheManager.addExcCount("noExc");
            if(null != list && !list.isEmpty()){
                return Msg.fail("用户名已存在!");
            }else{
                return Msg.success();
            }
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return Msg.fail();
        }
    }

    @OptionalLog(module = "新增",methods = "用户管理",fieldName = "userName")
    @RequiresPermissions(value="/user/add")
    @RequestMapping("/add")
    @ResponseBody
    public Msg add(Power_User powerUser){
        try {
            List<Power_User> user = powerUserService.checkUserName(powerUser.getUserName());
            CacheManager.addExcCount("noExc");
            if(null != user && !user.isEmpty()){
                return  Msg.fail("用户已存在!");
            }else{
                powerUserService.insertSelective(powerUser);
                return Msg.success();
            }
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return Msg.fail();
        }


    }

    @OptionalLog(module = "删除",methods = "用户管理",fieldName = "userName",tableName = "power_user")
    @RequiresPermissions(value="/user/delete")
    @RequestMapping("/delete")
    @ResponseBody
    public Msg delete(Integer userId){
        try {
            powerUserService.deleteByPrimaryKey(userId);
            CacheManager.addExcCount("noExc");
            return  Msg.success();
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return Msg.fail("删除失败,请联系系统管理员!");
        }
    }


    @OptionalLog(module = "修改",methods = "用户管理",fieldName = "userName")
    @RequiresPermissions(value="/user/update")
    @RequestMapping("/update")
    @ResponseBody
    public Msg update(Power_User powerUser,HttpServletRequest request){
        try {
            List<Power_User> user = powerUserService.checkUserName(powerUser.getUserName());
            if(null != user && !user.isEmpty() && !user.get(0).getUserId().equals(powerUser.getUserId())){
                return Msg.fail("用户名已存在!");
            }else{
                powerUserService.updateByPrimaryKeySelective(powerUser,request);
                CacheManager.addExcCount("noExc");
                return Msg.success();
            }

        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return Msg.fail("更新失败，请联系系统管理员!");
        }
    }

    @OptionalLog(module = "重置密码",methods = "用户管理",fieldName = "userName",tableName = "power_user")
    @RequiresPermissions(value="/user/resetPassword")
    @RequestMapping("/resetPassword")
    @ResponseBody
    public Msg update(Integer userId){
        try {
            ServletRequestAttributes attr=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request =attr.getRequest();
            Power_UserVo powerUser = powerUserService.selectByPrimaryKey(userId);
            powerUser.setUserPwd(Base64.encode(MD5.KL("000000")));
            powerUserService.updateByPrimaryKeySelective(powerUser,request);
            CacheManager.addExcCount("noExc");
            return Msg.success();
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return Msg.fail();
        }
    }
    @RequestMapping("/selectUser")
    @ResponseBody
    public Power_User selectUser(Integer userId){
        try {
            Power_User powerUser = powerUserService.selectByPrimaryKey(userId);
            CacheManager.addExcCount("noExc");
            return  powerUser;
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return null;
        }
    }
    @RequestMapping(value = "/toUpdatePassword")
    public String toUpdatePassword(HttpServletRequest request, Model model){
        try {
            Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
            Power_UserVo userVo = powerUserService.selectByPrimaryKey(user.getUserId());
            model.addAttribute("user",userVo);
            CacheManager.addExcCount("noExc");
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
        }
        return "/userDir/updatePassword";
    }

    @OptionalLog(module = "修改密码",methods = "用户管理")
    @RequestMapping(value = "/updatePassword")
    @ResponseBody
    public Msg updatePassword(String userPwd){
        try {
            boolean result = powerUserService.updatePassword(userPwd);
            CacheManager.addExcCount("noExc");
            return Msg.success().add("result",result);
        }catch (Exception e){
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return Msg.fail();
        }
    }

    /**
     * @Date 2019-10-11
     * @Author zengwh
     *  @Description 导入excel
     * */
    @OptionalLog(module = "导入excel",methods = "用户管理")
    @RequiresPermissions(value="/user/importExcel")
    @RequestMapping(value="/importExcel",method = {RequestMethod.POST})
    @ResponseBody
    public ResponseEntity<String> importExcel(HttpServletRequest request){
        OutputStream os = null;
        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 = {"userName","userPwd","name","userSex","userAge","userTel","userEmail","userPosition","roleId","deptId","effective","remark"};
            //判断集中类中的方法名
            String[] judgeMethods = {"judgeUserName","judgePassWord",null,"convertSex",null,"judgeUserTel","judgeUserEmail",null,"judgeRoleId","judgeDeptId","convertEffective","judgeRemark"};
            Power_User userVo = new Power_User();
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            Power_UserVo user = (Power_UserVo)request.getSession().getAttribute("CURRENT_USER");
            userVo.setCreater(user.getUserName());
            userVo.setUpdater(user.getUserName());
            userVo.setCreateDate(fmt.format(new Date()));
            userVo.setUpdateDate(fmt.format(new Date()));
            //实例化
            ImportExcelUtil.newInstance("power_UserMapper",userVo, Power_User.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){
            CacheManager.addExcCount("exc");
            //抛异常
            return new ResponseEntity<String>(e.getMessage(), responseHeaders, HttpStatus.OK);
        }finally {
            if(os != null){
                try {
                    os.flush();
                    os.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}
