package com.ym.mec.biz.service.impl;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.auth.api.enums.SysUserType;
import com.ym.mec.auth.api.enums.YesOrNoEnum;
import com.ym.mec.biz.dal.dao.EmployeeDao;
import com.ym.mec.biz.dal.dao.TeacherDao;
import com.ym.mec.biz.dal.dto.EmployeeDto;
import com.ym.mec.biz.dal.entity.Employee;
import com.ym.mec.biz.dal.enums.EmployeeOperateEnum;
import com.ym.mec.biz.dal.enums.ParamEnum;
import com.ym.mec.biz.dal.page.EmployeeQueryInfo;
import com.ym.mec.biz.service.EmployeeService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.entity.ImResult;
import com.ym.mec.common.entity.ImUserModel;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.im.ImFeignService;
import com.ym.mec.util.collection.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Integer, Employee>  implements EmployeeService {
	
	@Autowired
	private EmployeeDao employeeDao;

	@Autowired
	private ImFeignService imFeignService;
	@Autowired
	private SysUserFeignService sysUserFeignService;
	@Autowired
	private TeacherDao teacherDao;

	@Override
	public BaseDAO<Integer, Employee> getDAO() {
		return employeeDao;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void add(Employee employee){
		SysUser user = sysUserFeignService.queryUserByMobile(employee.getPhone());
		if(user != null){
            user.setUserType(SysUserType.SYSTEM);
			teacherDao.updateUser(user);
			Employee employee1 = employeeDao.get(user.getId());
			if(employee1 == null || employee1.getId() == null){
				employee.setUserId(user.getId());
				employeeDao.insert(employee);
				//删除当前用户角色
				employeeDao.delEmployeeRole(user.getId());
				//新增用户角色
				employeeDao.batchAddEmployeeRole(user.getId(),employee.getRoleIds());
			}
			return;
		}
		employee.setPassword(new BCryptPasswordEncoder().encode(ParamEnum.INIT_PASSWORD.getCode().toString()));
		employee.setUserType(SysUserType.SYSTEM);
		teacherDao.addSysUser(employee);
		employee.setUserId(employee.getId());
        employeeDao.insert(employee);
		//删除当前用户角色
		employeeDao.delEmployeeRole(employee.getId());
		//新增用户角色
		employeeDao.batchAddEmployeeRole(employee.getId(),employee.getRoleIds());
		ImResult imResult = imFeignService.register(new ImUserModel(employee.getId().toString(), employee.getUsername(), employee.getAvatar()));
		employee.setImToken(imResult.getToken());
		employeeDao.update(employee);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateEmployee(Employee employee) {
		Employee employee1 = employeeDao.get(employee.getId());
		if(null==employee1){
			employeeDao.insert(employee);
		}else{
			employee.setUserId(employee.getId());
			employeeDao.update(employee);
		}
		//删除当前用户角色
		employeeDao.delEmployeeRole(employee.getId());
		//新增用户角色
		employeeDao.batchAddEmployeeRole(employee.getId(),employee.getRoleIds());
		teacherDao.updateUser(employee);
	}

	@Override
	public void deleteEmployee(Long userId) {
		SysUser sysUser=new SysUser();
		sysUser.setId(userId.intValue());
		sysUser.setDelFlag(YesOrNoEnum.YES);
		teacherDao.updateUser(sysUser);
	}

	@Override
	public PageInfo queryEmployByOrganId(EmployeeQueryInfo queryInfo) throws Exception {
		SysUser user = sysUserFeignService.queryUserInfo();
		if(user == null){
			throw new Exception("获取用户信息失败");
		}

		queryInfo.setOrganId(user.getOrganId().longValue());
		PageInfo<EmployeeDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
		Map<String, Object> params = new HashMap<>();
		MapUtil.populateMap(params, queryInfo);

		List<EmployeeDto> dataList = null;
		int count = employeeDao.queryEmployByOrganIdCount(params);
		if (count > 0) {
			pageInfo.setTotal(count);
			params.put("offset", pageInfo.getOffset());
			dataList = employeeDao.queryEmployByOrganId(params);

		}
		if (count == 0) {
			dataList = new ArrayList<>();
		}
		pageInfo.setRows(dataList);
		return pageInfo;
	}

	@Override
	public void employeeOperate(Long employeeId, EmployeeOperateEnum operate) {
		switch (operate){
			case RESET_PASSWORD:
				employeeDao.updatePassword(employeeId,new BCryptPasswordEncoder().encode(ParamEnum.INIT_PASSWORD.getCode().toString()));
				break;
			case LOCK_UNLOCK:
				employeeDao.updateUserLockStatus(employeeId);
				break;
			case DEMISSION:
				employeeDao.updateUserDemissionDate(employeeId);
				break;
			case REINSTATE:
				employeeDao.updateUserDemissionDate(employeeId);
				break;
		}
	}
}