package com.ylcm.sys.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ylcm.sys.common.Constants;
import com.ylcm.sys.domain.Permission;
import com.ylcm.sys.domain.Role;
import com.ylcm.sys.domain.User;
import com.ylcm.sys.excel.model.UserImportDTO;
import com.ylcm.sys.exception.BaseException;
import com.ylcm.sys.mapper.UserMapper;
import com.ylcm.sys.service.RoleService;
import com.ylcm.sys.service.UserService;


@SuppressWarnings({ "unchecked", "rawtypes" })
@Service
public class UserServceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private RoleService roleService;
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.yaozhitech.dspoms.service.UserService#addUser(com.yaozhitech.dspoms
	 * .domain.User)
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public int addUser(User user, Integer roleId) {

		int t = userMapper.addUser(user);
		
		if (user.getUid() > 0 && roleId != null && roleId > 0) {
			roleService.delUserRolesByUserId(user.getUid());
			roleService.addUserRole(user.getUid(), roleId);
		}
		return t;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.yaozhitech.dspoms.service.UserService#updUser(com.yaozhitech.dspoms
	 * .domain.User)
	 */
	@Override
	public void updUser(User user) {

		/**
		 * 1、调用修改接口
		 */
		userMapper.updUser(user);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaozhitech.dspoms.service.UserService#delUser(int)
	 */
	@Override
	public void delUser(int userId) {

		/**
		 * 1、调用删除接口
		 */
		userMapper.delUser(userId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.yaozhitech.dspoms.service.UserService#getRowCount(java.lang.String,
	 * java.lang.String, int, int, int, int)
	 */
	@Override
	public int getRowCount(Map map) {

		/**
		 * 2、调用接口（根据条件统计用户总数）
		 */
		return userMapper.getRowCount(map);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.yaozhitech.dspoms.service.UserService#getUserList(java.lang.String,
	 * java.lang.String, int, int, int, int)
	 */
	@Override
	public List<User> getUserList(Map map) {
		/**
		 * 2、调用接口（分页获取用户信息）
		 */
		return userMapper.getUserList(map);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaozhitech.dspoms.service.UserService#getUserById(int)
	 */
	@Override
	public User getUserById(int userId) {

		/**
		 * 1、调用接口（根据用户标识获取用户信息）
		 */
		return userMapper.getUserById(userId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.yaozhitech.dspoms.service.UserService#delUsersByIds(java.lang.String
	 * [])
	 */
	@Override
	public void delUsersByIds(String[] ids) {

		/**
		 * 1、调用接口（删除用户信息(只删除未关联角色的用户)）
		 */
		userMapper.delUsersByIds(ids);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaozhitech.dspoms.service.UserService#updatePwd(int,
	 * java.lang.String)
	 */
	@Override
	public void updatePwd(int userId, String pwd) {

		/**
		 * 1、组装查询条件map
		 */
		Map map = new HashMap();
		map.put("userId", userId);
		map.put("password", pwd);

		/**
		 * 2、调用修改密码接口
		 */
		userMapper.updatePwd(map);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaozhitech.dspoms.service.UserService#checkUser(java.util.Map)
	 */
	@Override
	public int getCheckUser(String loginName) {

		/**
		 * 1、组装查询条件map
		 */
		Map map = new HashMap();
		map.put("loginName", loginName);

		/**
		 * 2、调用接口（用户唯一性判断）
		 */
		return userMapper.getCheckUser(map);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.yaozhitech.dspoms.service.UserService#getUserByLoginNameNeId(java
	 * .util.Map)
	 */
	@Override
	public int getUserByLoginNameNeId(int uid, String loginName) {

		/**
		 * 1、组装查询条件map
		 */
		Map map = new HashMap();
		map.put("uid", uid);
		map.put("loginName", loginName);

		/**
		 * 2、调用接口（根据登录名和用户标识查找登录名是否已存在）
		 */
		return userMapper.getUserByLoginNameNeId(map);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.yaozhitech.dspoms.service.UserService#getUserByLoginName(java.lang
	 * .String)
	 */
	@Override
	public User getUserByLoginName(String loginName) {

		/**
		 * 1、调用接口（根据登录名获取用户信息）
		 */
		return userMapper.getUserByLoginName(loginName);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaozhitech.dspoms.service.UserService#updUserStatus(int, int)
	 */
	@Override
	public void updUserStatus(int uid, int status) {

		/**
		 * 1、组装查询条件map
		 */
		Map map = new HashMap();
		map.put("uid", uid);
		map.put("status", status);
		userMapper.updUserStatus(map);
	}

	@Override
	public Boolean getCheckUserByOpenId(String openid) {
		Boolean flag = false;
		/**
		 * 1、组装查询条件map
		 */
		Map map = new HashMap();
		map.put("openid", openid);
		int result = userMapper.getCheckUserByOpenId(map);
		if (result > 0) {
			flag = true;
		}
		/**
		 * 2、调用接口（用户唯一性判断）
		 */
		return flag;
	}

	@Override
	public User getUserByOpenId(String openid) {
		Map map = new HashMap();
		map.put("openid", openid);
		return userMapper.getUserByOpenId(map);
	}

	@Override
	public List<Permission> getPermissoins(List<Permission> list) {
		List<Permission> perList = new ArrayList<Permission>();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Permission info = list.get(i);
				if (Constants.MENU_TYPE.equals(info.getType())) {
					perList.add(info);
					list.remove(i);
					i--;
				}
			}
		}
		Iterator<Permission> perIt = perList.iterator();
		while (perIt.hasNext()) {
			List<Permission> subList = new ArrayList<Permission>();
			Permission per = perIt.next();
			for (int i = 0; i < list.size(); i++) {
				Permission info = list.get(i);
				if (Constants.SUB_MENU_TYPE.equals(info.getType())) {
					if (per.getPermissionId() == info.getPid()) {
						subList.add(info);
						list.remove(i);
						i--;
					}
				}
			}
			per.setSubPerms(subList);
		}
		return perList;
	}
	
	
	@Override
    public void exportExcel(HttpServletRequest request,HttpServletResponse response) throws IOException {
        Map map = (Map) request.getSession().getAttribute(Constants.USER_SEARCH_PARAMETERS);
        int pageSize = 100000;// 单表行数上限（除表头外的实际数据行数）
        map.put("pageIndex", 0);
        map.put("pageSize", pageSize);
        /*
         * 1.获取原数据
         * */
        List<User> source = userMapper.getUserList(map);
        
        int sourceSize = source.size();
        int pageNum = sourceSize / pageSize + 1;// 表数量
        
        /*
         * 2.将数据填充进excel文件对象
         * */
        // 创建Workbook对象，对应Excel文件
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 创建sheet对象，对应文件中的表格
        XSSFSheet sheet = null;
        // 创建row对象，对应表格的行
        XSSFRow row = null;
        // 创建cell对象，对应表格的列
        XSSFCell cell = null;
        
        // 单表数据行数有上限，若超出，则新建一张表
        Integer temp = 0;// 临时变量
        for (int page = 0; page < pageNum; page++) {

            // 新建一张表
            sheet = workbook.createSheet("sheet" + (page+1) );
            // 表格宽度
            sheet.setDefaultColumnWidth(25);
            // 表格头部
            row = sheet.createRow(0);
//            row.setHeightInPoints(ExcelUtil.HERGHT_HEAD);
            cell = row.createCell(0);cell.setCellValue("用户名");
            cell = row.createCell(1);cell.setCellValue("姓名");
            cell = row.createCell(2);cell.setCellValue("手机号");
            cell = row.createCell(3);cell.setCellValue("邮箱");
            cell = row.createCell(4);cell.setCellValue("性别");
            cell = row.createCell(5);cell.setCellValue("角色");
            // 表格主体数据，从第二行开始
            for (int index = 0; index < pageSize; index++) {
                temp = page * pageSize + index;
                if (temp >= sourceSize) {
                    break;
                }
                User item = source.get(temp);
                row = sheet.createRow(index + 1);
//                row.setHeightInPoints(ExcelUtil.HERGHT_SHEET);
                cell = row.createCell(0);cell.setCellValue(item.getLoginName());
                cell = row.createCell(1);cell.setCellValue(item.getNickName());
                cell = row.createCell(2);cell.setCellValue(item.getTelephone());
                cell = row.createCell(3);cell.setCellValue(item.getEmail());
                cell = row.createCell(4);cell.setCellValue((item.getSex() != null && item.getSex() == 0 )? "男" : (item.getSex() != null && item.getSex() == 1 ? "女" : "") );
                cell = row.createCell(5);cell.setCellValue(item.getRoleName());
            }
            
        }
        /*
         * 3.输出文件对象
         * */
        if (workbook != null) {
            /* 添加样式 */
//            ExcelUtil.createXSSFCellStyle(workbook);
            
            /* 输出 */
//            ExcelUtil.exportWorkbook(response, workbook, "用户管理");
        }
        
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
	public String importUserBatch(List<UserImportDTO> importDTOs) throws Exception {
		List<Role> roleList = roleService.getRoleList();
		Map<String,Integer> roleMap = new HashMap<String,Integer>();
		for(Role role : roleList){
			roleMap.put(role.getName(), role.getRoleId());
		}
		int index = 2; //表格从第二行开始
		for (UserImportDTO importDTO : importDTOs) {
			index ++;
			User user = importDTO.toUser();
			int size = getCheckUser(user.getLoginName());
			if (size > 0) {
				throw new BaseException("第"+ index + "行，用户数据重复");
			}		
			Integer roleId = roleMap.get(importDTO.getRole());
			if (roleId == null) {
				throw new BaseException("第"+ index + "行，找不到对应的角色");
			}
			addUser(user, roleId);
		}
		return "ok";
	}

}