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

import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.uas.platform.b2b.dao.EnterpriseDao;
import com.uas.platform.b2b.dao.UserDao;
import com.uas.platform.b2b.model.Enterprise;
import com.uas.platform.b2b.model.User;
import com.uas.platform.b2b.service.EnterpriseService;
import com.uas.platform.b2b.service.UserService;
import com.uas.platform.b2b.support.SendMailService;
import com.uas.platform.b2b.support.TokenService;
import com.uas.platform.core.model.Constant;
import com.uas.platform.core.util.HttpUtil;
import com.uas.platform.core.util.encry.Md5Utils;
import com.uas.platform.core.util.serializer.FlexJsonUtils;

@Service
public class EnterpriseServiceImpl implements EnterpriseService{

	@Autowired
	private EnterpriseDao enterpriseDao;
	@Autowired
	private UserService userService;
	@Autowired
	private UserDao userDao;
	@Autowired
	private TokenService tokenService;
	@Autowired
	private SendMailService sendMailService;
	
	@Override
	public String bussinessCodeEnable(String code) {
		Enterprise enterprise = enterpriseDao.findEnterpriseByEnBussinessCode(code);
		if(enterprise == null) {
			return "ENABLE";
		} else if(enterprise.getEnable() == 1) {
			return "USED";
		} else {
			return "APPLYING";
		}
	}

	@Override
	public Enterprise registerEnterprise(Enterprise enterprise) {
		Enterprise en = enterpriseDao.findEnterpriseByEnBussinessCode(enterprise.getEnBussinessCode());
		if(en == null && userService.isEmailUseable(enterprise.getEnAdminEmail()) && 
				userService.isTelUseable(enterprise.getEnAdminTel())) {
			enterprise.setEnDate(new Date());
			enterprise.setEnable(Constant.NO);
			Enterprise newEnterprise = enterpriseDao.save(enterprise);//保存enterprise
			User user = new User();
			user.setUserEmail(enterprise.getEnAdminEmail());
			user.setUserTel(enterprise.getEnAdminTel());
			user.setEnterprises(new HashSet<Enterprise>());
			user.addEnterprise(newEnterprise);//添加userenterpris对应关系
			user.setEnable(Constant.NO);
			User newUser = userDao.save(user);//保存user
			newEnterprise.setEnAdminuu(newUser.getUserUU());//设置管理员UU号
			newEnterprise = enterpriseDao.save(newEnterprise);//再次保存enterprise
			//添加要传输的数据
			newEnterprise.setEnAdminEmail(enterprise.getEnAdminEmail());
			newEnterprise.setEnAdminTel(enterprise.getEnAdminTel());
			newEnterprise.setEnBussinesscodeImg(newEnterprise.getEnBussinessCodeAttach().getId());
			sendToAduit(newEnterprise);//传给管理平台进行资料审核
			return newEnterprise;
		}
		return null;
	}

	@Override
	public HttpResponse sendToAduit(Enterprise enterprise) {
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("data", FlexJsonUtils.toJson(enterprise));
		HttpResponse response = HttpUtil.sendPostRequest(
				"http://192.168.253.157:8081/platform-manage/b2b/unaudited", params);
		return response;
	}

	@Override
	public String audit(Long uu, String result, String reason) {
		Enterprise enterprise = enterpriseDao.findEnterpriseByUu(uu);
		if(enterprise != null) {
			if(result.equals("ALLOW")) {//审核通过
				String encodeString = tokenService.getEncodeToken("enterprise", uu);
				User admin = userDao.findUserByUserUU(enterprise.getEnAdminuu()).get(0);
				Map<String, Object> model = new HashMap<String, Object>();
				model.put("name", enterprise.getEnName());
				model.put("email", admin.getUserEmail());
				model.put("rootpath", "http://192.168.253.157:8081/platform-b2b/");
				model.put("uu", enterprise.getUu());
				model.put("checkcode", encodeString);
				sendMailService.sendTemplateMail("suntugui@qq.com",//TEST用自己的邮箱
						"欢迎注册优软管理平台账号", model, "velocity/registerActivate.vm");
				return "ALLOW";
			} else if(result.equals("NOTALLOW")) {//审核不通过
				User admin = userDao.findUserByUserUU(enterprise.getEnAdminuu()).get(0);
				enterpriseDao.delete(enterprise);//删除企业记录
				userDao.delete(admin);//删除企业管理员记录
				Map<String, Object> model = new HashMap<String, Object>();
				model.put("name", enterprise.getEnName());
				model.put("email", admin.getUserEmail());
				model.put("reason", reason);
				sendMailService.sendTemplateMail("suntugui@qq.com",//TEST用自己的邮箱
						"很遗憾账号未能通过审核", model, "velocity/invalid.vm");
				return "NOTALLOW";
			} else {
				return "审核结果参数出错";
			}
		}
		return "找不到uu号对应的企业";
	}

	@Override
	public String activateCheck(Long uu, String checkcode) {
		Enterprise enterprise = enterpriseDao.findEnterpriseByUu(uu);
		if(enterprise != null) {
			if(!enterprise.isEnabled()) {
				if(tokenService.isCertified("enterprise", uu, checkcode)) {
					enterprise.setEnable(Constant.YES);
					User admin = userDao.findUserByUserUU(enterprise.getEnAdminuu()).get(0);
					admin.setEnable(Constant.YES);
					userDao.save(admin);
					enterpriseDao.save(enterprise);
					return "SUCCESS";
				} else {
					return "验证码错误，激活失败";
				}
			} else {
				return "企业账号已激活，操作失败";
			}
		}
		return "找不到uu号对应的企业账号";
	}

	@Override
	public String sendActivateEmail(Long enuu) {
		Enterprise enterprise = enterpriseDao.findEnterpriseByUu(enuu);
		String encodeString = tokenService.getEncodeToken("enterprise", enuu);
		User admin = userDao.findUserByUserUU(enterprise.getEnAdminuu()).get(0);
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("name", enterprise.getEnName());
		model.put("email", admin.getUserEmail());
		model.put("rootpath", "http://192.168.253.157:8081/platform-b2b/");
		model.put("uu", enuu);
		model.put("checkcode", encodeString);
		sendMailService.sendTemplateMail("suntugui@qq.com",//TEST用自己的邮箱
				"欢迎注册优软管理平台账号", model, "velocity/registerActivate.vm");
		return "SUCCESS";
	}

	@Override
	public String setAdminPassword(Long enuu, String password) {
		Enterprise enterprise = enterpriseDao.findEnterpriseByUu(enuu);
		User admin = userDao.findUserByUserUU(enterprise.getEnAdminuu()).get(0);
		admin.setUserPwd(Md5Utils.encode(password, admin.getUserUU()));
		userDao.save(admin);
		return "SUCCESS";
	}

}
