package com.uas.account.controller;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.uas.account.core.util.ChineseUtils;
import com.uas.account.core.util.ExecuteUtils;
import com.uas.account.core.util.StringUtil;
import com.uas.account.entity.App;
import com.uas.account.entity.Setting;
import com.uas.account.entity.User;
import com.uas.account.entity.UserDetail;
import com.uas.account.entity.UserSpace;
import com.uas.account.entity.UserSpaceDetail;
import com.uas.account.entity.UserView;
import com.uas.account.service.AppService;
import com.uas.account.service.SettingService;
import com.uas.account.service.UserService;
import com.uas.account.service.UserSpaceService;
import com.uas.account.viewmodel.ApplyAppView;
import com.uas.account.web.BaseController;
import com.uas.dfs.service.FileClient;
import com.uas.message.mail.service.MailService;
import com.uas.sso.SSOHelper;
import com.uas.sso.SSOToken;

/**
 * 提供用户操作企业相关信息，need signin
 * 
 * @author yingp
 * 
 */
@Controller
@RequestMapping("/userspace")
public class UserSpaceController extends BaseController {

	@Autowired
	private UserService userService;
	@Autowired
	private UserSpaceService userSpaceService;
	@Autowired
	private AppService appService;
	@Autowired
	private MailService mailService;
	@Autowired
	private SettingService settingService;
	@Autowired
	private FileClient fileClient;

	/**
	 * 用户申请为企业开通应用
	 * 
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/applyApp", method = RequestMethod.GET)
	public ModelAndView applyApp(String appId) {
		SSOToken token = SSOHelper.attrToken(request);
		UserView user = JSON.parseObject(token.getData(), UserView.class);

		App app = appService.findOne(appId);
		if (null == app) {
			return new ModelAndView("common/error", error("404", "未找到您要开通的应用"));
		}

		if (StringUtils.isEmpty(user.getSpaceUID()) || StringUtils.isEmpty(user.getUid())) {
			return new ModelAndView("common/error", error("您的账户信息未核实，无法开通" + app.getDescription()));
		}

		UserSpace oldUs = userSpaceService.findOne(appId, user.getSpaceUID());

		if (null != oldUs) {
			// 如果企业已经开通该应用
			User oldUser = userService.findOne(appId, oldUs.getId(), user.getUid());
			if (null != oldUser) {
				// 直接重定向到该应用主页
				if (!StringUtils.isEmpty(app.getHomePage())) {
					return new ModelAndView("redirect:" + app.getHomePage().replace("$domain", user.getSpaceDomain()));
				} else {
					return new ModelAndView("common/error", error(String.format("%s 已开通%s，您可以直接访问", oldUs.getName(), app.getDescription())));
				}
			} else {
				// 但是个人账号还未开通
				return new ModelAndView("common/error", error(String.format("%s 已开通%s，请联系企业管理员开通您的个人账号", oldUs.getName(),
						app.getDescription())));
			}
		}
		UserSpaceDetail detail = userSpaceService.findByBusinessCode(user.getSpaceUID());
		if (StringUtils.isEmpty(detail.getDomain())) {
			detail.setDomain(generateDefaultDomain(detail));
		}

		// 开通应用的界面
		return new ModelAndView("us/apply_" + appId, success(detail).addAttribute("user", user).addAttribute("appId", appId));
	}

	/**
	 * 生成默认域名
	 * 
	 * @return
	 */
	private String generateDefaultDomain(UserSpaceDetail detail) {
		String domain = null;
		if (!StringUtils.isEmpty(detail.getUrl())) {
			Pattern p = Pattern.compile("http(s)*://(.+\\.)*(.+)\\..+", Pattern.CASE_INSENSITIVE);
			Matcher m = p.matcher(detail.getUrl());
			if (m.find()) {
				domain = m.group(3);
			}
		}
		if (domain == null)
			domain = StringUtil.substr(ChineseUtils.converterToFirstSpell(StringUtils.trimAllWhitespace(detail.getName())), 0, 16);
		UserSpaceDetail oldOne = userSpaceService.findByDomain(domain);
		if (oldOne != null) {
			domain = StringUtil.substr(ChineseUtils.converterToSpell(StringUtils.trimAllWhitespace(detail.getName())), 0, 16);
			oldOne = userSpaceService.findByDomain(domain);
			if (oldOne != null)
				domain = null;
		}
		return domain;
	}

	/**
	 * 开通应用
	 * 
	 * @param businessCode
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/applyApp", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap applyApp(String businessCode, final String appId, final ApplyAppView view, @RequestBody MultipartFile file) {
		final UserSpaceDetail detail = userSpaceService.findByBusinessCode(businessCode);
		if (detail == null) {
			return error("您的企业注册资料已经失效，请重新注册");
		}
		detail.setDomain(view.getDomain());
		if (null != file && !file.isEmpty()) {
			try {
				String path = fileClient.upload(file.getBytes(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),
						null);
				if (path != null) {
					detail.setLogoImage(path);
					try {
						userSpaceService.save(detail);
					} catch (Exception e) {
						fileClient.delete(path);
						throw e;
					}
				} else {
					return error("请检查您的企业LOGO图片");
				}
			} catch (IOException e) {
				return error("请检查您的企业LOGO图片");
			}
		} else {
			userSpaceService.save(detail);
		}
		// TODO 这里填写的用户，还要判断是否已开通默认应用
		userSpaceService.applyApp(businessCode, appId, null, view.getUserDetails());
		view.getUserDetails().add(new UserDetail(detail));
		// 知会下企业用户
		ExecuteUtils.asyncExecute(new Runnable() {

			@Override
			public void run() {
				for (UserDetail user : view.getUserDetails()) {
					if (!StringUtils.isEmpty(user.getEmail())) {
						// 邮件
						Setting mailTpl = settingService.findOne("templateForSendMailWhenRegisterFinished." + appId + "."
								+ (!StringUtils.isEmpty(user.getDepartment()) ? user.getDepartment() : "管理员"));
						if (mailTpl != null) {
							ModelMap data = new ModelMap();
							data.put("domain", detail.getDomain());
							data.put("spaceName", detail.getName());
							data.put("name", user.getName());
							data.put("uid", user.getMobile());
							data.put("job", user.getJob());
							mailService.send(mailTpl.getValue(), user.getEmail(), data);
						}
					}
				}
			}
		});
		// 信息有变，修改sso信息
		SSOToken token = SSOHelper.attrToken(request);
		UserView user = JSON.parseObject(token.getData(), UserView.class);
		user.setSpaceDomain(detail.getDomain());
		token = new SSOToken(request, user.getUid());
		token.setData(JSON.toJSONString(user));
		SSOHelper.setSSOCookie(request, response, token, true);
		return success();
	}

}
