package com.bonus.hn.bearing.capacity.backstage.manager.service.impl;

import com.bonus.hn.bearing.capacity.backstage.manager.dao.UserDao;
import com.bonus.hn.bearing.capacity.backstage.manager.dao.UtilDao;
import com.bonus.hn.bearing.capacity.backstage.manager.entity.LonLat;
import com.bonus.hn.bearing.capacity.backstage.manager.entity.MapBean;
import com.bonus.hn.bearing.capacity.backstage.manager.entity.UserDto;
import com.bonus.hn.bearing.capacity.backstage.manager.entity.ZNode;
import com.bonus.hn.bearing.capacity.backstage.manager.model.SysUser;
import com.bonus.hn.bearing.capacity.backstage.manager.service.UserService;
import com.bonus.hn.bearing.capacity.backstage.manager.utils.StringHelper;
import com.bonus.hn.bearing.capacity.backstage.manager.utils.UserUtil;
import com.bonus.hn.bearing.capacity.backstage.project.entity.FileBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
 * @author bonus
 */
@Service
public class UserServiceImpl implements UserService {

	private static final Logger log = LoggerFactory.getLogger("adminLogger");
	@Resource
	private UtilDao utilDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private BCryptPasswordEncoder passwordEncoder;

	@Override
	@Transactional
	public SysUser saveUser(UserDto userDto) {
		SysUser user = userDto;
		user.setPassword(passwordEncoder.encode(user.getPassword()));
		user.setStatus(SysUser.Status.VALID);
		userDao.save(user);
		saveUserRoles(user.getId(), userDto.getRoleIds());

		log.debug("新增用户{}", user.getUsername());
		return user;
	}

	private void saveUserRoles(Long userId, List<Long> roleIds) {
		if (roleIds != null) {
			userDao.deleteUserRole(userId);
			if (!CollectionUtils.isEmpty(roleIds)) {
				userDao.saveUserRoles(userId, roleIds);
			}
		}
	}

	@Override
	public SysUser getUser(String username) {
		return userDao.getUser(username);
	}

	@Override
	public void changePassword(String username, String oldPassword, String newPassword) {
		SysUser u = userDao.getUser(username);
		if (u == null) {
			throw new IllegalArgumentException("用户不存在");
		}

		if (!passwordEncoder.matches(oldPassword, u.getPassword())) {
			throw new IllegalArgumentException("旧密码错误");
		}

		userDao.changePassword(u.getId(), passwordEncoder.encode(newPassword));

		log.debug("修改{}的密码", username);
	}



	@Override
	@Transactional
	public SysUser updateUser(UserDto userDto) {
		userDao.update(userDto);
		saveUserRoles(userDto.getId(), userDto.getRoleIds());

		return userDto;
	}

/**-------------------------------------------用户管理新方法-----------------------------------------------------------------*/
	@Override
	public List<SysUser> getMsgList(SysUser o) {
		o.setLevel(UserUtil.getLoginUser().getLevel());
		o.setOrgIds(UserUtil.getLoginUser().getOrgId());
		return userDao.getMsgList(o);
	}

	@Override
	public List<ZNode> getDepartmentTree() {
		ZNode o = new ZNode();
		o.setLevels(UserUtil.getLoginUser().getLevel());
		o.setOrgIds(UserUtil.getLoginUser().getOrgId());
		return userDao.getDepartmentTree(o);
	}

	@Override
	public List<MapBean> getRole() {
		return userDao.getRole();
	}

	@Override
	public int addInfo(SysUser bean) {
//		int num = utilDao.determineIfExists("sys_user","id_card",bean.getIdCard(),"");
//		if(num > 0){
//			num = 3;
//		}else {
			int phone = utilDao.personIfExists("sys_user","phone",bean.getPhone());
			if(phone >0){
				return 5;
			}
			bean.setPassword(passwordEncoder.encode("HNczl@123456"));
		int num = userDao.addInfo(bean);
			//返回主键  插入sys_role_user表中去
			int team = userDao.insertroleUser(bean);
//		}
		return num;
	}

	@Override
	public int updateInfo(SysUser bean) {
		int num =0;
//		int phone = utilDao.personIfExists("sys_user","phone",bean.getPhone());
		int phone = utilDao.phoneIfExists("sys_user","phone",bean.getPhone(),bean.getId().toString());
		if(phone >0){
			return 5;
		}
		num = userDao.updateInfo(bean);
		int team = userDao.updateRoleUser(bean);
		return num;
	}

	@Override
	public int updatePerson(SysUser bean) {
		int num =0;
		bean.setId(UserUtil.getLoginUser().getId());
		int phone = utilDao.phoneIfExists("sys_user","phone",bean.getPhone(),bean.getId().toString());
		if(phone >0){
			return 5;
		}
		num = userDao.updateInfo(bean);
		int team = userDao.updateRoleUser(bean);
		return num;
	}

	@Override
	public SysUser getListPerson() {
		String id = UserUtil.getLoginUser().getId().toString();
		return userDao.getListById(id);
	}

	@Override
	public int delById(SysUser bean) {
		return userDao.delById(bean);
	}

	@Override
	public int resetPassword(SysUser bean) {
		bean.setPassword(passwordEncoder.encode(bean.getPassword()));
		return userDao.resetPassword(bean);
	}

	@Override
	public int updateSwitchListen(SysUser bean) {
		return userDao.updateSwitchListen(bean);
	}

	@Override
	public SysUser getListById(String id) {
		return userDao.getListById(id);
	}

	@Override
	public int updateMyInfo(SysUser bean) {
		return userDao.updateMyInfo(bean);
	}

	@Override
	public List<SysUser> getSystemNotification(SysUser o) {
		o.setUserId(UserUtil.getLoginUser().getId().toString());
		return userDao.getSystemNotification(o);
	}

	@Override
	public List<Map<String, Object>> getLoginLogs() {
		List<Map<String, Object>> result = new ArrayList<>();
		String userId = UserUtil.getLoginUser().getId().toString();
		List<SysUser> sysUsers = userDao.findAllByOrderByCreateTimeDesc(userId);
		Map<String, List<Map<String, String>>> resultMap = new LinkedHashMap<>();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");

		for (SysUser sysUser : sysUsers) {
			String loginDate = dateFormat.format(sysUser.getCreateTime());

			Map<String, String> record = new LinkedHashMap<>();
			record.put("system", sysUser.getSystemName());
			record.put("ip", sysUser.getIpAddress());
			record.put("hostName", sysUser.getHostName());
			record.put("time", timeFormat.format(sysUser.getCreateTime()));

			if (!resultMap.containsKey(loginDate)) {
				resultMap.put(loginDate, new ArrayList<>());
			}
			resultMap.get(loginDate).add(record);
		}

		for (Map.Entry<String, List<Map<String, String>>> entry : resultMap.entrySet()) {
			Map<String, Object> dateRecord = new LinkedHashMap<>();
			dateRecord.put("date", entry.getKey());
			dateRecord.put("records", entry.getValue());
			result.add(dateRecord);
		}

		return result;
	}

	@Override
	public int addLoginLog() {
        int num = 0;
        try {
            // 获取当前IP地址
            InetAddress ipAddress = InetAddress.getLocalHost();
            String ip = ipAddress.getHostAddress();

            // 获取系统名称
            String systemName = System.getProperty("os.name");

            // 获取所在位置（主机名）
            String hostName = ipAddress.getHostName();

            LocalDate currentYearMonth = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String formattedYearMonth = currentYearMonth.format(formatter);

            String id = UserUtil.getLoginUser().getId().toString();

            // 创建SysUser对象并设置值
            SysUser sysuser = new SysUser();
            sysuser.setIpAddress(ip);
            sysuser.setSystemName(systemName);
            sysuser.setHostName(hostName);
            sysuser.setMonth(formattedYearMonth);
            sysuser.setUserId(id);

            num = utilDao.insertLoginInfo(sysuser);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return num;
    }

	@Override
	public int upLoginLog(SysUser bean) {
		return utilDao.upLoginLog(bean);
	}


	@Override
	public List<FileBean> getDownloadRecord(FileBean o) {
		o.setUserId(UserUtil.getLoginUser().getId()+"");
		return userDao.getDownloadRecord(o);
	}

	@Override
	public int delRecordById(FileBean bean) {
		return userDao.delRecordById(bean);
	}

	@Override
	public int delAll(FileBean bean) {
		bean.setUserId(UserUtil.getLoginUser().getId().toString());
		return userDao.delAll(bean);
	}

	@Override
	public int delReadAlready(FileBean bean) {
		bean.setUserId(UserUtil.getLoginUser().getId().toString());
		return userDao.delReadAlready(bean);
	}

	@Override
	public int updateLonLat(String proId, String meridian) {
		List<LonLat> list = userDao.getLonLatByProId(proId);
		int number = 0;
		for (int i = 0; i < list.size(); i++) {
			String lon1 =StringHelper.replaceSpace(list.get(i).getGeodeticLon());
			String lat1 = StringHelper.replaceSpace(list.get(i).getGeodeticLat());
			String l = StringHelper.coordinateTransform(Double.parseDouble(lon1),Double.parseDouble(lat1),meridian);
			LonLat bean = new LonLat();
			String lon = l.split(",")[0];
			String lat = l.split(",")[1];
			bean.setProId(proId);
			bean.setId(list.get(i).getId());
			bean.setLon(lon);
			bean.setLat(lat);
			number = userDao.updateLonLat(bean);
		}

		return number;
	}

}
