package cn.wise.sc.cement.business.service.impl;

import cn.wise.sc.cement.business.entity.*;
import cn.wise.sc.cement.business.exception.BusinessExceptionEnum;
import cn.wise.sc.cement.business.mapper.SysPermissionMapper;
import cn.wise.sc.cement.business.mapper.SysRoleMapper;
import cn.wise.sc.cement.business.mapper.SysUserEnclosureMapper;
import cn.wise.sc.cement.business.mapper.SysUserMapper;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.LoginUser;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.query.SysUserEnclosureQuery;
import cn.wise.sc.cement.business.model.query.UserQuery;
import cn.wise.sc.cement.business.model.vo.ClientVo;
import cn.wise.sc.cement.business.model.vo.UserVo;
import cn.wise.sc.cement.business.service.ISysUserService;
import cn.wise.sc.cement.business.util.ExcelUtil;
import cn.wise.sc.cement.business.util.JwtUtil;
import cn.wise.sc.cement.business.util.RedisUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.BaseNumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ztw
 * @since 2020-08-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

	@Resource
	private SysUserMapper userMapper;
	@Resource
	private HttpServletRequest request;
	@Autowired
	RedisUtil redisUtil;
	@Resource
	private SysPermissionMapper permissionMapper;
	@Resource
	private SysRoleMapper roleMapper;
	@Autowired
	private UserServiceImpl userService;
	@Resource
	private SysUserEnclosureMapper sysUserEnclosureMapper;

	/**
	 * 当前登录用户
	 *
	 * @return
	 */
	@Override
	public LoginUser getLoginUser() {
		try {
			String token = request.getHeader("Authorization");
//			System.out.println("==================Authorization===================");
//			System.out.println(token);
			Map map = JwtUtil.parserToken(token);
			Object obj = redisUtil.getString(map.get("id").toString());
			BusinessExceptionEnum.CACHE_NOT_FOUND.assertNotNull(obj);
			SysUser sysUser = userMapper.selectById(Integer.valueOf(map.get("id").toString()));
			LoginUser loginUser = new LoginUser();
			BeanUtils.copyProperties(sysUser, loginUser);
			List<SysPermission> permissionList = permissionMapper.listByUserId(loginUser.getId());
			SysRole sysRole = roleMapper.byUserId(sysUser.getId());
			loginUser.setRoleList(sysRole);
			loginUser.setPermissions(permissionList);
			return loginUser;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 人员分页列表
	 *
	 * @param pageQuery
	 * @param status
	 * @param groupId
	 * @param name
	 * @return
	 */
	@Override
	public BaseResponse<IPage<UserVo>> getPage(PageQuery pageQuery, Integer status, Integer groupId, String name) {
		Map<String, Object> params = new HashMap<>();
		params.put("status", status);
		params.put("groupId", groupId);
		params.put("name", name);
		Page<UserVo> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
		IPage<UserVo> pages = userMapper.getPage(page, params);
		return BaseResponse.okData(pages);
	}

	/**
	 * 新增人员
	 *
	 * @param query
	 * @return
	 */
	@Override
	@Transactional
	public BaseResponse<SysUser> create(UserQuery query) {
		if (StringUtils.isEmpty(query.getPhone())) {
			return BaseResponse.errorMsg("手机号码不可为空!");
		}
		if(query.getRoleId() == null){
			return BaseResponse.errorMsg("请选择角色信息!");
		}
		QueryWrapper<SysUser> qw = new QueryWrapper<>();
		qw.eq("phone", query.getPhone());
		int count = userMapper.selectCount(qw);
		if (count > 0) {
			return BaseResponse.errorMsg("手机号已存在!");
		}
		SysUser user = new SysUser();
		BeanUtils.copyProperties(query, user);
		user.setStatus(1).setIsDelete(1).setCreateTime(LocalDateTime.now());
		userMapper.insert(user);

		saveUserRoles(user.getId(), query.getRoleId());
		return BaseResponse.okData(user);
	}

	/**
	 * 修改人员
	 *
	 * @param query
	 * @return
	 */
	@Override
	@Transactional
	public BaseResponse<SysUser> update(UserQuery query) {
		if(query.getId() == 1){
			return BaseResponse.errorMsg("不允许更改系统管理员信息!");
		}
		if (StringUtils.isEmpty(query.getPhone())) {
			return BaseResponse.errorMsg("手机号码不可为空!");
		}
		if(query.getRoleId() == null){
			return BaseResponse.errorMsg("请选择角色信息!");
		}
		QueryWrapper<SysUser> qw = new QueryWrapper<>();
		qw.eq("phone", query.getPhone());
		qw.ne("id", query.getId());
		int count = userMapper.selectCount(qw);
		if (count > 0) {
			return BaseResponse.errorMsg("手机号已存在!");
		}
		SysUser user = new SysUser();
		BeanUtils.copyProperties(query, user);
		user.setId(query.getId());
		userMapper.updateById(user);

		saveUserRoles(user.getId(), query.getRoleId());
		return BaseResponse.okData(user);
	}

	/**
	 * 保存用户和角色信息
	 * @param userId
	 * @param roleId
	 */
	private void saveUserRoles(Integer userId, Integer roleId) {
		if (userId != null) {
			userMapper.deleteUserRole(userId);
			if (roleId != null) {
				userMapper.saveUserRoles(userId, roleId);
			}
		}
	}

	/**
	 * 禁用启用
	 *
	 * @param status
	 * @param id
	 * @return
	 */
	@Override
	@Transactional
	public BaseResponse<String> status(Integer status, Integer id) {
		if(id == 1){
			return BaseResponse.errorMsg("不允许更改系统管理员状态!");
		}
		if (status == null || id == null) {
			return BaseResponse.errorMsg("参数错误!");
		}
		SysUser user = userMapper.selectById(id);
		if (user == null) {
			return BaseResponse.errorMsg("数据错误!");
		}
		user.setStatus(status);
		userMapper.updateById(user);
		String result = "";
		if (user.getStatus() == 1) {
			result = "已启用";
		} else {
			result = "已禁用";
		}
		return BaseResponse.okData(result);
	}

	/**
	 * 人员详情
	 *
	 * @param id
	 * @return
	 */
	@Override
	public BaseResponse<UserVo> findById(Integer id) {
		BusinessExceptionEnum.BAD_LICENCE_TYPE.assertNotNull(id);
		UserVo userVo = userMapper.getById(id);
		return BaseResponse.okData(userVo);
	}

	/**
	 * 上传人员附件
	 * @param query
	 * @return
	 */
	@Override
	@Transactional
	public BaseResponse<String> uploadPeoplePF(SysUserEnclosureQuery query) {
		LoginUser loginUser = userService.getLoginUser();
		if (loginUser == null){
			return BaseResponse.errorMsg("请登录账号");
		}
		if (query == null || query.getUserId() == null){
			return BaseResponse.errorMsg("参数错误");
		}
		SysUserEnclosure sysUserEnclosure = new SysUserEnclosure();
		sysUserEnclosure.setUserId(query.getUserId())
				.setEnclosureUrl(query.getEnclosureUrl())
				.setExtName(query.getExtName())
				.setAlias(query.getAlias())
				.setFlStatus(1)
				.setUploadTime(LocalDateTime.now());
		sysUserEnclosureMapper.insert(sysUserEnclosure);
		return BaseResponse.okMsg("成功");
	}

	/**
	 * 附件列表
	 * @param pageQuery
	 * @param userId
	 * @return
	 */
	@Override
	public BaseResponse<IPage<SysUserEnclosure>> getUserEnclosurePage(PageQuery pageQuery, Integer userId) {
		if(userId == null){
			return BaseResponse.errorMsg("请传入用户id");
		}
		Map<String, Object> params = new HashMap<>();
		params.put("userId", userId);
		Page<SysUserEnclosure> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
		IPage<SysUserEnclosure> pages = sysUserEnclosureMapper.getPage(page, params);
		return BaseResponse.okData(pages);
	}

	/**
	 * 删除人员附件
	 * @param id
	 * @return
	 */
	@Transactional
	@Override
	public BaseResponse<String> deleteUserEnclosure(Integer id) {
		if(id == null){
			return BaseResponse.errorMsg("参数错误");
		}
		SysUserEnclosure userEnclosure = sysUserEnclosureMapper.selectById(id);
		if(userEnclosure == null){
			return BaseResponse.errorMsg("人员附件信息错误");
		}
		sysUserEnclosureMapper.deleteById(id);
		return BaseResponse.okData("附件信息删除成功");
	}








	/**
	 * 人员详情列表导出
	 * @param status 状态
	 * @param name 姓名
	 * @return
	 */
//	@Override
//	public void exportList(Integer status, String filename, String name, HttpServletResponse response) {
//		Map<String, Object> params = new HashMap<>();
//		params.put("status", status);
//		params.put("name", name);
//		List<Map<String, Object>> list= userMapper.exportList(params);
//
//		if (!CollectionUtils.isEmpty(list)){
//			Map<String,Object> map=list.get(0);
//			String[] headers=new String[20];
//			headers[0] = "序号";
//			headers[1] = "用户账号";
//			headers[2] = "真实姓名";
//			headers[3] = "性别";
//			headers[4] = "组别id";
//			headers[5] = "职务id";
//			headers[6] = "微信号";
//			headers[7] = "职称";
//			headers[8] = "状态";
//			headers[9] = "工作年限";
//			headers[10] = "手机号";
//			headers[11] = "传真";
//			headers[12] = "专业";
//			headers[13] = "邮箱";
//			headers[14] = "从事本技术领域日期";
//			headers[15] = "从事本技术领域年限";
//			headers[16] = "文化程度";
//			headers[17] = "创建时间";
//			headers[18] = "修改时间";
//			headers[19] = "备注";
//
//			List<Object[]> datas=new ArrayList<>(list.size());
//			for (Map<String,Object>m:list){
//				Object[] objects=new Object[headers.length];
//				for (int j=0;j<headers.length;j++){
//					String obj=m.get(headers[j])==null?"":m.get(headers[j]).toString();
//					if (j==0 && obj!=null){
//						obj=obj.split("\\.")[0];
//					}
//					objects[j] = obj;
//				}
//				datas.add(objects);
//			}
//			ExcelUtil.excelExport(
//					filename==null || filename.trim().length() <= 0 ? "人员详情":filename ,headers, datas ,response);
//		}
//	}

}
