package com.uas.platform.b2b.manage.service.impl;

import com.uas.platform.b2b.manage.core.support.SystemSession;
import com.uas.platform.b2b.manage.dao.UserDao;
import com.uas.platform.b2b.manage.model.Constant;
import com.uas.platform.b2b.manage.service.UserService;
import com.uas.platform.b2b.manage.support.RestMailServiceImpl;
import com.uas.platform.b2b.manage.support.StringUtil;
import com.uas.platform.b2b.manage.core.util.StringUtils;
import com.uas.platform.b2b.manage.dao.SecretKeyRecordDao;
import com.uas.platform.b2b.manage.model.SecretKeyRecord;
import com.uas.platform.b2b.manage.model.User;
import com.uas.platform.b2b.manage.support.MyException;
import com.uas.platform.b2b.manage.support.SecurityConstant;
import com.uas.platform.core.util.encry.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 用户数据接口
 *
 * @author hejq
 * @date 2018-04-23
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RestMailServiceImpl mailService;

    @Autowired
    private SecretKeyRecordDao recordDao;

    /**
     * 通过电话号码查询用户信息
     *
     * @param tel 电话
     * @return User
     */
    @Override
    public User findByTel(String tel) {
        List<User> userList = userDao.findByTel(tel);
        return userList.size() > 0 ? userList.get(0) : null;
    }

    /**
     * 通过邮箱查询用户信息
     *
     * @param email 邮箱
     * @return User
     */
    @Override
    public User findUserByUserEmail(String email) {
        List<User> userList = userDao.findByEmail(email);
        return userList.size() > 0 ? userList.get(0) : null;
    }

    /**
     * 通过用户名查询用户信息
     *
     * @param name
     * @return User
     */
    @Override
    public User findUserByName(String name) {
        List<User> users = userDao.findUserByName(name);
        if (users.size() == 0) {
            throw new UsernameNotFoundException("没有找到您的账号 " + name);
        }
        return users.get(0);
    }

    /**
     * 通过账号密码登录
     *
     * @param userName 账号
     * @param passWord 密码
     * @param request request
     * @param response response
     * @throws MyException 自定义异常
     * @throws UnsupportedEncodingException 编码异常
     */
    @Override
    public void login(String userName, String passWord, HttpServletRequest request, HttpServletResponse response) throws MyException, UnsupportedEncodingException {
        List<User> users = userDao.findByTel(userName);
        if (CollectionUtils.isEmpty(users)) {
            users = userDao.findByEmail(userName);
            if (CollectionUtils.isEmpty(users)) {
                throw new MyException("未找到账号信息");
            }
        }
        User user = users.get(0);
        if (Md5Utils.encode(passWord, user.getName()).equals(user.getPassword())) {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            Cookie cookie = new Cookie(Constant.COOKIE_NAME, session.getId());
            response.addCookie(cookie);
            SystemSession.setUser(user);
        } else {
            throw new MyException("账号或密码错误");
        }
    }

    /**
     * 注册用户
     *
     * @param user 用户信息
     * @return User
     */
    @Override
    public User register(User user) {
        if (user.getEmail().contains(Constant.EMAIL_SUFFIX)) {
            String name = user.getEmail().substring(0, user.getEmail().indexOf("@"));
            user.setName(name);
        } else {
            user.setEmail(user.getEmail() + Constant.EMAIL_SUFFIX);
        }
        List<User> existUsers = userDao.findByEmail(user.getEmail());
        if (!CollectionUtils.isEmpty(existUsers)) {
            user.setId(existUsers.get(0).getId());
        }
        user.setPassword(Md5Utils.encode(user.getPassword(), user.getName()));
        return userDao.save(user);
    }

    /**
     * 根据填写邮箱发送修改密码链接
     *
     * @param email 邮箱
     */
    @Override
    public void sendResetPwdUrl(String email) {
        SecretKeyRecord record = recordDao.findByEmail(email);
        if (null != record) {
            if (System.currentTimeMillis() - record.getTime() > Constant.SECRECTTIME) {
                recordDao.delete(record);
                record = recordDao.save(new SecretKeyRecord(email, StringUtil.uuid()));
            }
        } else {
            record = recordDao.save(new SecretKeyRecord(email, StringUtil.uuid()));
        }
        String url = Constant.MANAGEURL + "/resetPwd/url?secretKey=" + record.getSecretKey();
        ModelMap map = new ModelMap();
        map.put("resetPwdUrl", url);
        try {
            mailService.send(Constant.RESETPWD_MOULD_URL, email, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过访问链接修改密码
     *
     * @param secretKey 秘钥
     * @param response 请求
     * @param request request
     * @return User
     * @throws IOException
     * @throws MyException
     * @throws ServletException
     */
    @Override
    public User resetPwd(String secretKey, HttpServletResponse response, HttpServletRequest request) throws IOException, MyException, ServletException {
        if (StringUtils.isEmpty(secretKey)) {
            response.sendRedirect(Constant.INVALIDURL);
        }
        SecretKeyRecord record = recordDao.findBySecretKey(secretKey);
        if (null == record) {
            response.sendRedirect(Constant.INVALIDURL);
        } else {
            if (System.currentTimeMillis() - record.getTime() > Constant.SECRECTTIME) {
                recordDao.delete(record);
                response.sendRedirect(Constant.INVALIDURL);
            } else {
                List<User> users = userDao.findByEmail(record.getEmail().trim());
                if (CollectionUtils.isEmpty(users)) {
                    throw new MyException("未找到该邮箱用户信息");
                } else {
                    SystemSession.setUser(users.get(0));
                    request.getSession().setAttribute("user", users.get(0));
                    recordDao.delete(record);
                    response.sendRedirect(Constant.RESETPWD_URL);
                }
            }
        }
        return null;
    }

    /**
     * 修改密码
     *
     * @param id 用户id
     * @param password 密码
     * @throws IOException
     */
    @Override
    public void resetPassword(Long id, String password, HttpServletResponse response) throws IOException {
        User user = userDao.findOne(id);
        user.setPassword(Md5Utils.encode(password, user.getName()));
        userDao.save(user);
        SystemSession.clear();
        response.sendRedirect(SecurityConstant.LOGIN_URL);
    };
}
