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.YesOrNoEnum;
import com.ym.mec.biz.dal.dao.EmployeeDao;
import com.ym.mec.biz.dal.dao.SysUserCashAccountDao;
import com.ym.mec.biz.dal.dao.TeacherDao;
import com.ym.mec.biz.dal.dto.EmployeeDto;
import com.ym.mec.biz.dal.dto.SimpleUserDto;
import com.ym.mec.biz.dal.entity.Employee;
import com.ym.mec.biz.dal.entity.SysUserCashAccount;
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.exception.BizException;
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.apache.commons.lang3.StringUtils;
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.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;
	@Autowired
	private SysUserCashAccountDao sysUserCashAccountDao;

	@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.getId() != null){
			Employee employee1 = employeeDao.get(user.getId());
			if(employee1 == null){
				if(StringUtils.isEmpty(user.getPassword())){
					employee.setPassword(new BCryptPasswordEncoder().encode(ParamEnum.INIT_PASSWORD.getCode().toString()));
				}
				employee.setUserId(user.getId());
				employee.setId(user.getId());
				employeeDao.insert(employee);
				//新增用户角色
				employeeDao.batchAddEmployeeRole(user.getId(),employee.getRoleIds());
				employee.setUserType(user.getUserType() + ",SYSTEM");
				teacherDao.updateUser(employee);
				return;
			}else{
				throw new BizException("员工已存在");
			}
		}
		employee.setPassword(new BCryptPasswordEncoder().encode(ParamEnum.INIT_PASSWORD.getCode().toString()));
		employee.setUserType("SYSTEM");
		teacherDao.addSysUser(employee);
		employee.setUserId(employee.getId());
        employeeDao.insert(employee);
		//新增用户角色
		employeeDao.batchAddEmployeeRole(employee.getId(),employee.getRoleIds());
		//添加用户现金账户
		sysUserCashAccountDao.insert(new SysUserCashAccount(employee.getId(),"CNY"));
		ImResult imResult = imFeignService.register(new ImUserModel(employee.getId().toString(), employee.getUsername(),null));
		employee.setImToken(imResult.getToken());
		teacherDao.updateUser(employee);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateEmployee(Employee employee) {
		Employee employee1 = employeeDao.get(employee.getId());
		if(null==employee1){
			throw new BizException("员工信息不存在");
		}
		employee.setUserId(employee.getId());
		if(StringUtils.isNotEmpty(employee.getPhone())){
			SysUser sysUser = sysUserFeignService.queryUserByMobile(employee.getPhone());
			if(sysUser != null && !sysUser.getId().equals(employee.getUserId())){
				throw new BizException("手机号已存在");
			}
		}
		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 BizException("获取用户信息失败");
		}
		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(Integer employeeId, EmployeeOperateEnum operate) {
		Employee employee = employeeDao.get(employeeId);
		switch (operate){
			case RESET_PASSWORD:
				employeeDao.updatePassword(employeeId,new BCryptPasswordEncoder().encode(ParamEnum.INIT_PASSWORD.getCode().toString()));
				break;
			case LOCK_UNLOCK:
				SysUser sysUser = sysUserFeignService.queryUserById(employeeId);
				if(employee != null && employee.getDemissionDate() != null && sysUser.getLockFlag() == 1){
					throw new BizException("操作失败：离职员工不允许解冻");
				}
				employeeDao.updateUserLockStatus(employeeId);
				break;
			case DEMISSION:
				employeeDao.updateUserLock(employeeId,1);
				employeeDao.updateUserDemissionDate(employeeId);
				break;
			case REINSTATE:
				//离职，如果有关联课程组教务老师，
				employeeDao.updateUserDemissionDate(employeeId);
				break;
		}
	}

	@Override
	public List<SimpleUserDto> findByRole(String roleIds, String organIds) {
		return employeeDao.findByRole(roleIds,organIds);
	}

	@Override
	public HashMap<String, Integer> hasCourseGroupRelation(Integer employeeId) {
		Integer hasCourseGroupRelation = employeeDao.hasCourseGroupRelation(employeeId);
		Integer hasCourseSchedule = employeeDao.hasCourseSchedule(employeeId);
		HashMap<String, Integer> map = new HashMap<>(2);
		map.put("hasCourseGroupRelation",hasCourseGroupRelation);
		map.put("hasCourseSchedule",hasCourseSchedule);
		return map;
	}

	@Override
	public void updateEducationTeacherId(Integer currentUserId, Integer targetUserId) {
		employeeDao.updateEducationTeacherId(currentUserId,targetUserId);
	}
}
