package com.manage.service.ipml;

import com.manage.dao.Power_UserMapper;
import com.manage.dao.User_Dept_MenuMapper;
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.Power_RoleService;
import com.manage.service.Power_UserService;
import com.manage.util.ActionScopeUtils;
import com.manage.util.Constant;
import com.manage.vo.Power_UserVo;
import com.manage.vo.User_Dept_Menu;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

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

/**
 * @Author:hjl
 * @Date:Creatid in 1:19 2019/4/17
 * @Description:
 */
@Service
public class Power_UserServiceImpl implements Power_UserService {

    @Autowired
    private Power_UserMapper powerUserMapper;

    @Autowired
    Power_DeptService power_deptService;

    @Autowired
    Power_RoleService powerRoleService;

    @Autowired
    User_Dept_MenuMapper userDeptMenuMapper;

    @Override
    public int deleteByPrimaryKey(Integer userId) {
        return powerUserMapper.deleteByPrimaryKey(userId);
    }

    @Override
    public int insert(Power_User record) {
        return powerUserMapper.insert(record);
    }

    @Override
    public List<Power_User> checkUserName(String userName){
        return powerUserMapper.checkUserName(userName);
    }

    @Override
    public int insertSelective(Power_User powerUser) {
        //取得当前登录账号
        ServletRequestAttributes attr=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request =attr.getRequest();
        HttpSession session= request.getSession();
        Power_User powerUser1 =(Power_User) session.getAttribute("CURRENT_USER");

        if(powerUser.getUserPwd() != null && powerUser.getUserName() != null){
            powerUser.setUserPwd(Base64.encode(MD5.KL(powerUser.getUserPwd())));
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        String date = df.format(new Date());// new Date()为获取当前系统时间
        powerUser.setCreater(powerUser1.getUserName());
        powerUser.setCreateDate(date);
        powerUser.setUpdater(powerUser1.getUserName());
        powerUser.setUpdateDate(date);
        return powerUserMapper.insertSelective(powerUser);
    }

    @Override
    public Power_UserVo selectByPrimaryKey(Integer userId) {
        StringBuilder power_depts = new StringBuilder();
        Power_UserVo power_user = powerUserMapper.selectByPrimaryKey(userId);
        power_user.setUserPwd(MD5.JM(Base64.decode(power_user.getUserPwd())));
        List<Power_Dept> power_depts1 = power_deptService.selectByPrimaryKeys(power_user.getDeptId());
        for(int j=0;j<power_depts1.size();j++){
            if(j<power_depts1.size()-1){
                power_depts.append(power_depts1.get(j).getDeptName()).append(",");
            }else{
                power_depts.append(power_depts1.get(j).getDeptName());
            }
        }
        power_user.setPowerDepts(power_depts.toString());
        return power_user;
    }

    @Override
    public int updateByPrimaryKeySelective(Power_User powerUser,HttpServletRequest request) {
        //取得当前登录账号
        HttpSession session= request.getSession();
        Power_User powerUser1 =(Power_User) session.getAttribute("CURRENT_USER");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        String date = df.format(new Date());// new Date()为获取当前系统时间
        powerUser.setUpdater(powerUser1.getUserName());
        powerUser.setUpdateDate(date);
        return powerUserMapper.updateByPrimaryKeySelective(powerUser);
    }

    @Override
    public int updateByPrimaryKey(Power_User record) {
        return powerUserMapper.updateByPrimaryKey(record);
    }

    @Override
    public Power_UserVo findPowerUserByUserNameAndUserPwd(Power_User powerUser) {
        if(powerUser.getUserPwd() != null && powerUser.getUserName() != null){
            powerUser.setUserPwd(Base64.encode(MD5.KL(powerUser.getUserPwd())));
            powerUser.setEffective(Constant.EFFECTIVE_YES);
            Power_UserVo user = powerUserMapper.findPowerUserByUserNameAndUserPwd(powerUser);
            return user;
        }
        return null;
    }

    @Override
    public boolean validUserRoleMenu(String url, Integer userId) {
        List<User_Dept_Menu> menus = userDeptMenuMapper.validUserRoleMenu(userId,url);
        if(null != menus && !menus.isEmpty()){
            return true;
        }else{
            return false;
        }
    }
    //登录的是角色0才显示所有用户信息，如果是角色-100则只显示该用户所在医院的所有用户信息，
    //如果是其它的则只显示该登录用户自己的用户信息
    @Override
    public List<Power_UserVo> findSomeByMore(Power_UserVo powerUser,HttpServletRequest request) {
        //取得当前登录账号
        HttpSession session= request.getSession();
        Power_UserVo powerUser1 =(Power_UserVo) session.getAttribute("CURRENT_USER");
        Set<String> perms = powerUser1.getMenus();
        if(null != powerUser1 && powerUser1.getRoleId()!=0){
            powerUser.setUserId(powerUser1.getUserId());
            powerUser.setRoleId(powerUser1.getRoleId());
        }
        List<Power_UserVo> someByMore = powerUserMapper.findSomeByMore(powerUser);
        for(int i=0;i<someByMore.size();i++){
            Power_UserVo power_user = someByMore.get(i);
            //设置编辑和删除权限
            int isUpdate = 0;
            int isDelete = 0;
            if(null != perms && !perms.isEmpty()){
                for(String menu : perms){
                    if("/user/update".equals(menu)){
                        isUpdate = 1;
                    }
                    if("/user/delete".equals(menu)){
                        isDelete = 1;
                    }

                }
            }

            power_user.setIsUpdate(isUpdate);
            power_user.setIsDelete(isDelete);
        }
        return someByMore;
    }

    @Override
    public int getTotal(Power_UserVo powerUser,HttpServletRequest request) {
        //取得当前登录账号
        HttpSession session= request.getSession();
        Power_User powerUser1 =(Power_User) session.getAttribute("CURRENT_USER");
        if(powerUser1.getRoleId()==0){
            powerUser.setUserId(null);
        }else if(powerUser1.getRoleId()==-100){
            powerUser.setUserId(powerUser1.getUserId());
        }else{
            powerUser.setUserId(powerUser1.getUserId());
        }
        return powerUserMapper.getTotal(powerUser);
    }

    @Override
    public void export(Power_UserVo powerUser,HttpServletRequest request,HttpServletResponse response) throws Exception {
        List<Power_UserVo> powerUsers = this.findSomeByMore(powerUser,request);
        if(null != powerUsers && !powerUsers.isEmpty()){
            for (int i = 0; i < powerUsers.size(); i++) {
                if(null != powerUsers.get(i).getUserSex()){
                    if(powerUsers.get(i).getUserSex() == 1){
                        powerUsers.get(i).setSex("女");
                    }else{
                        powerUsers.get(i).setSex("男");
                    }
                }
                if(powerUsers.get(i).getEffective() == 1){
                    powerUsers.get(i).setEffectiveCn("是");
                }else{
                    powerUsers.get(i).setEffectiveCn("否");
                }
            }
        }
        String tableThNames = "账号,姓名,性别,年龄,移动电话,邮箱地址,用户职位,所属角色,所属部门,是否有效,创建时间,创建人,修改时间,修改人";
        String fieldCns = "userName,name,sex,userAge,userTel,userEmail,userPosition,roleName,powerDepts,effectiveCn,createDate,creater,updateDate,updater";
        //文件名
        String fileName = "用户列表(" + new SimpleDateFormat("yyyy_MM_dd HH_mm_ss").format(new Date()) + ").xls";
        //ExportExcelUtil
        com.manage.util.ExportExcelUtil exportExcelUtil = new com.manage.util.ExportExcelUtil();
        //导出excel的操作
        exportExcelUtil.expordExcel(tableThNames,fieldCns,powerUsers,fileName,response);
    }
    @Override
    public void export1(Power_UserVo powerUser,HttpServletRequest request,HttpServletResponse response) throws Exception {
        List<Power_UserVo> powerUsers = this.findSomeByMore(powerUser,request);
        if(null != powerUsers && !powerUsers.isEmpty()){
            for (int i = 0; i < powerUsers.size(); i++) {
                if(null != powerUsers.get(i).getUserSex()){
                    if(powerUsers.get(i).getUserSex() == 1){
                        powerUsers.get(i).setSex("女");
                    }else{
                        powerUsers.get(i).setSex("男");
                    }
                }
                if(powerUsers.get(i).getEffective() == 1){
                    powerUsers.get(i).setEffectiveCn("是");
                }else{
                    powerUsers.get(i).setEffectiveCn("否");
                }
            }
        }
        String tableThNames = "账号,姓名,性别,年龄,移动电话,邮箱地址,用户职位,所属角色,所属部门,是否有效,创建时间,创建人,修改时间,修改人";
        String fieldCns = "userName,name,sex,userAge,userTel,userEmail,userPosition,roleName,powerDepts,effectiveCn,createDate,creater,updateDate,updater";
        //文件名
        String fileName = "用户列表(" + new SimpleDateFormat("yyyy_MM_dd HH_mm_ss").format(new Date()) + ").xls";
        //ExportExcelUtil
        com.manage.util.ExportExcelUtil exportExcelUtil = new com.manage.util.ExportExcelUtil();
        //导出excel的操作
        exportExcelUtil.expordExcel(tableThNames,fieldCns,powerUsers,fileName,response);
    }

    @Override
    public boolean updatePassword(String newUserPwd) {
        Power_User powerUser = (Power_User) ActionScopeUtils.getSessionAttribute(Constant.CURRENT_USER);
        if(StringUtils.isNotBlank(newUserPwd)){
            powerUser.setUserPwd(Base64.encode(MD5.KL(newUserPwd)));
            powerUserMapper.updateByPrimaryKeySelective(powerUser);
            return true;
        }
        return false;
    }

    @Override
    public String generateUUID(Integer userId) {
        return null;
    }

    @Override
    public Power_UserVo findPowerUserByUserNameAndRemark(Power_User powerUser) {
        return powerUserMapper.findPowerUserByUserNameAndRemark(powerUser);
    }

}
