package com.reyun.service.impl;

import com.reyun.model.Account;
import com.reyun.repository.AccountRepository;
import com.reyun.service.RegedService;
import com.reyun.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by Administrator on 2017/5/5 0005.
 */
@Service
public class RegedServiceImpl implements RegedService {

    protected Logger logger = LoggerFactory.getLogger(RegedServiceImpl.class);

    @Autowired
    AccountRepository accountRepository;

    private static final String VERIFY_EMAIL_SEND_URL = Constant.adminUrl + "/api/tool/ioaccount/sendemail/";

    @Override
    public Boolean sendActiceEmail(String url, Long id) {

        Account account = this.accountRepository.findOne(id);

        Boolean result = new Boolean(true);

        String subject = "TrackingIo账号激活";

        StringBuilder content = new StringBuilder();
        content.append("<!doctype html> <html><head></head><body> ")
                .append("亲爱的用户：</br>")
                .append("您好，您于").append(DateUtil.format(new Date(account.getActiveTime()), DateUtil.C_TIME_PATTON_DEFAULT))
                .append("注册热云账号").append(account.getEmail())
                .append("，以下链接激活账号</br>")
                .append("<a href=\"" + url + "\">").append(url).append("</a>")
                .append("</body></html>");

        String contents = content.toString();
        List<String> list = new ArrayList<>();
        list.add(account.getEmail());

        try {
            MailUtils.sendHtmlEmail(subject, contents, list);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            result = false;
            return result;
        }
        return result;
    }

    @Override
    public String active(String token, Long id) {
        String result = "success";
        Account account = this.accountRepository.findOne(id);
        logger.info(account.getId().toString());
        logger.info(account.getActiveTime().toString());
        //1.验证token
        String trueToken = HashAlgorithms.MD5("superuser_" + account.getId() + account.getActiveTime());
        if (!trueToken.equals(token)) {
            result = "token failure";
        }

        //2.验证时间是否超过3天
        long activedate = account.getActiveTime();
        Date currentdate = DateUtil.getCurrentDate();

        if (DateUtil.minBetween(new Date(activedate), currentdate) > Integer.parseInt(Constant.mailValidTime)) {
            result = "active out of date";
        }

        if (account.getActiveStatus() == true) {
            result = "repeat url";
        }
        return result;
    }

    @Override
    public Account modifyEmail(Long id, String oldemail, String newemail) {

        Account account = this.accountRepository.findOne(id);

        Account result = new Account();
        //验证原邮件地址是否正确，不正确返回空类
        if (oldemail.equals(account.getEmail())) {
            account.setEmail(newemail);
            result = this.accountRepository.save(account);
        }
        return result;
    }

    @Override
    public Map<String,Object> sendForgetPwdEmail(String email) {

        Map<String,Object> result = new HashMap<String,Object>();
        Account one = this.accountRepository.findAccountByEmail(email);

        String url = Constant.accountCheckUrl + "/resetpwd.html#?";

        StringBuilder sb = new StringBuilder();
        //判断账号是否存在
        if (ValidateUtil.isValid(one)) {

            /**
             * 未激活的新用户
             */
            if (one.getStatus() != -3) {
                one.setForgetPwdTime(new Date().getTime());
                one.setForgetPwdStatus(false);
                Account account = this.accountRepository.save(one);

                //是否修改成功
                if (ValidateUtil.isValid(account)) {

                    sb.append(url).append("message=").append(HashAlgorithms.MD5("superuser_" + account.getId() + account.getForgetPwdTime())).append(account.getId());

                    String subject = "热云数据密码找回";

                    StringBuilder content = new StringBuilder();
                    content.append("<!doctype html> <html><head></head><body> ")
                            .append("亲爱的用户：</br>")
                            .append("您好，您于").append(DateUtil.format(new Date(account.getForgetPwdTime()), DateUtil.C_TIME_PATTON_DEFAULT))
                            .append("请求找回热云账号").append(account.getEmail())
                            .append("密码。</br>")
                            .append("点击此链接修改密码:</br>").append("<a href=\"" + sb.toString() + "\">").append(sb.toString()).append("</a>")
                            .append("</body></html>");

                    String contents = content.toString();
                    List<String> list = new ArrayList<>();
                    list.add(one.getEmail());
                    try {
                        MailUtils.sendHtmlEmail(subject, contents, list);
                    } catch (Exception e) {
                        logger.error(e.getMessage(),e);
                         result.put("message","send email error");
                    }
                    result.put("message","success");
                } else {
                    result.put("message","generate error");
                }
            }
            else if (one.getIsSuperUser()) {
                //主账号
                result.put("message", "newuser not actived");
                result.put("id", one.getId());
            }
            else {
                //子账号
                result.put("message", "new subAccount");
                result.put("id", one.getId());
            }
        } else {
            result.put("message","账号不存在");
        }
        return result;
    }

    @Override
    public String updatepwd(Long id, String newpwd, String token) {
        String result = "update failure";
        Account one = this.accountRepository.findOne(id);

        String newPwdmd5 = CipherUtil.generatePassword(newpwd);

        String trueToken = HashAlgorithms.MD5("superuser_" + id + one.getForgetPwdTime());
        Date forgetTime = new Date(one.getForgetPwdTime());


        //验证token
        if (null != trueToken && trueToken.equals(token)) {
            //验证链接有效性
            if (DateUtil.minBetween(forgetTime, new Date()) < Integer.parseInt(Constant.mailValidTime) && !one.getForgetPwdStatus()) {

                one.setPassword(newPwdmd5);
                one.setForgetPwdStatus(true);

                //子账号激活设置密码
                if(!one.getIsSuperUser() && one.getStatus() == -3){
                    one.setStatus(1);
                }

                Account account = this.accountRepository.save(one);

                if (ValidateUtil.isValid(account)) {
                    result = "update success";
                }

            } else {
                result = "out of date or repeat Upwd request";
            }
        } else {
            result = "invalid request";
        }
        return result;
    }

    @Override
    public String validatepass(String message) {

        String result = "success";

        String tokenstr = message.substring(0, 32);
        String idstr = message.substring(32, message.length());

        Account one = this.accountRepository.findOne(Long.parseLong(idstr));
        if (ValidateUtil.isValid(one)) {
            String trueToken = HashAlgorithms.MD5("superuser_" + idstr + one.getForgetPwdTime());
            Date forgetTime = new Date(one.getForgetPwdTime());

            if (trueToken.equals(tokenstr)) {
                //验证链接有效性
                System.out.println("++++++++" + Integer.parseInt(Constant.mailValidTime));

                if (DateUtil.minBetween(forgetTime, new Date()) > Integer.parseInt(Constant.mailValidTime)) {
                    result = "out of date";
                } else if (one.getForgetPwdStatus() == true) {
                    result = "updated";
                } else {
                    result = "success";
                }
            } else {
                result = "invalid request";
            }
        } else {
            result = "invalid request";
        }
        System.out.println("_+++" + result);
        return result;
    }

    @Override
    public Boolean sendactivewhenUpdateEmail(String url, String newemail, Long time) {
        Boolean result = new Boolean(true);

        String subject = "TrackingIo账号激活";

        StringBuilder content = new StringBuilder();
        content.append("<!doctype html> <html><head></head><body> ")
                .append("亲爱的用户：</br>")
                .append("您好，您于").append(DateUtil.format(new Date(time), DateUtil.C_TIME_PATTON_DEFAULT))
                .append("注册热云账号").append(newemail)
                .append("，以下链接激活账号</br>")
                .append("<a href=\"" + url + "\">").append(url).append("</a>")
                .append("</body></html>");

        String contents = content.toString();
        List<String> list = new ArrayList<>();
        list.add(newemail);

        try {
            MailUtils.sendHtmlEmail(subject, contents, list);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            result = false;
            return result;
        }
        return result;
    }

    @Override
    public void verifyAccount(Account account, String ip) {

        account.setStatus(-1);
        Account result = this.accountRepository.save(account);

        String token = HashAlgorithms.MD5("superuser_" + account.getId());

        //审核
        final String sendEmailUrl = VERIFY_EMAIL_SEND_URL + account.getId()+"/"+token + "?ip=" + (StringUtil.isEmpty(ip)?"unknown":ip);
        Thread sendEmailThread = new Thread(){
            @Override
            public void run(){
                HttpClientUtil.doHttpGetRequest(sendEmailUrl,"trackingio");
            }
        };
        sendEmailThread.setName("sendEmailThread");
        sendEmailThread.start();
    }

}
