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

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

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.TeacherDao;
import com.ym.mec.biz.dal.entity.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ym.mec.biz.dal.dao.EmployeeDao;
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.page.PageInfo;
import com.ym.mec.common.security.SecurityUtils;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.util.collection.MapUtil;

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

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private ObjectMapper objectMapper;
	@Autowired
	private SysUserFeignService sysUserFeignService;
	@Autowired
	private TeacherDao teacherDao;

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

	@Override
	public void add(Employee employee) throws Exception {
		SysUser user = sysUserFeignService.getUserByMobile(employee.getPhone());
		if(user != null){
			employee.setUserType(SysUserType.SYSTEM);
			teacherDao.updateUser(employee);
			return;
		}
		//保存用户表信息
		sysUserFeignService.addUser(employee);
		//注册到融云

		//保存教师表数据
		employeeDao.insert(employee);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateEmployee(Employee employee) {
		employeeDao.update(employee);
		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 IOException {
		String url = "http://auth-server/queryUserInfo";

		String base64ClientCredentials = Base64.getEncoder().encodeToString("app:app".getBytes());

		HttpHeaders headers = new HttpHeaders();
		headers.add("Authorization", "bearer " + SecurityUtils.getToken());
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

		HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(null, headers);

		ResponseEntity<String> resp = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

		Map map = objectMapper.readValue(resp.getBody(), Map.class);

		queryInfo.setOrganId(Long.valueOf(map.get("organId").toString()));
		PageInfo<EmployeeDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
		Map<String, Object> params = new HashMap<String, Object>();
		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:
				Employee employee=new Employee();
				employee.setUserId(employeeId.intValue());
				employee.setDemissionDate(new Date());
				employeeDao.update(employee);
				break;
		}
	}
}