package com.uas.account.controller;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uas.account.core.ICallable;
import com.uas.account.core.Page;
import com.uas.account.core.util.ExecuteUtils;
import com.uas.account.dao.UserDao;
import com.uas.account.entity.App;
import com.uas.account.entity.AppCreateInfo;
import com.uas.account.entity.Setting;
import com.uas.account.entity.Token;
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.exception.AccountException;
import com.uas.account.service.AppService;
import com.uas.account.service.PlatformManageService;
import com.uas.account.service.SettingService;
import com.uas.account.service.SysDataToMallService;
import com.uas.account.service.TokenService;
import com.uas.account.service.UserService;
import com.uas.account.service.UserSpaceService;
import com.uas.account.viewmodel.ApplyAppView;
import com.uas.account.viewmodel.UserSpaceDetailView;
import com.uas.account.web.BaseController;
import com.uas.message.mail.service.MailService;

@Controller
@RequestMapping("/api/userspace")
public class UserSpaceManagerController extends BaseController {

	@Autowired
	private UserSpaceService userSpaceService;
	@Autowired
	private MailService mailService;
	@Autowired
	private SettingService settingService;
	@Autowired
	private TokenService tokenService;
	@Autowired
	private UserService userService;
	@Autowired
	private UserDao userDao;
	@Autowired
	private AppService appService;
	@Autowired
	private PlatformManageService platformManageService;
	@Autowired
	private SysDataToMallService sysDataToMallService;

	/**
	 * aapid 为 saas
	 */
	private final String saas = "saas";

	/**
	 * appid 为 uas
	 */
	private final String uas = "uas";

	/**
	 * appid 为 b2b
	 */
	private final String b2b = "b2b";

	/**
	 * appid 为 mall
	 */
	private final String mall = "mall";

	/**
	 * 企业信息新增、修改
	 * 
	 * @param userSpace
	 * @param userSpaceDetail
	 * @param apps
	 *            绑定应用（为空表示开通全部默认应用）
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public ModelMap save(UserSpace userSpace, UserSpaceDetail userSpaceDetail, String apps) {
		if (userSpace == null || userSpace.getName() == null
				|| (userSpace.getId() == null && (userSpace.getAppId() == null || userSpace.getUid() == null)))
			return error("参数错误");
		boolean isNew = userSpaceService.save(userSpace, userSpaceDetail,
				null == apps ? null : new HashSet<String>(Arrays.asList(apps.split(","))));
		if (isNew && !StringUtils.isEmpty(userSpaceDetail.getAdminEmail())) {
			// 邮件通知
			Setting mailTpl = settingService.findOne("templateForSendMailWhenRegisterFinished." + userSpace.getAppId() + ".管理员");
			if (mailTpl != null) {
				ModelMap data = new ModelMap();
				data.put("domain", userSpaceDetail.getDomain());
				data.put("spaceName", userSpaceDetail.getName());
				data.put("name", userSpaceDetail.getAdminName());
				data.put("uid", userSpaceDetail.getAdminTel());
				data.put("job", "管理员");
				mailService.send(mailTpl.getValue(), userSpaceDetail.getAdminEmail(), data);
			}
		}
		return success(userSpaceService.findByUID(userSpace.getUid()));
	}

	/**
	 * 取消企业开通的应用
	 * 
	 * @param userSpace
	 * @return
	 */
	@RequestMapping(params = "_operate=unbind", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap apiUnbind(UserSpace userSpace) {
		if (userSpace == null || userSpace.getAppId() == null)
			throw new AccountException("参数错误");
		userSpaceService.delete(userSpace);
		return success();
	}

	/**
	 * 按应用查找企业
	 * 
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ResponseBody
	public Page<UserSpace> findAll(String appId, int pageNumber, int pageSize) {
		return userSpaceService.findAll(appId, pageNumber, pageSize);
	}

	/**
	 * 企业开通应用统计
	 * 
	 * @return
	 */
	@RequestMapping(value = "/count", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap count() {
		return success(userSpaceService.getUserSpaceAppCount());
	}

	/**
	 * 按UID查找企业所使用的全部应用
	 * 
	 * @param uid
	 * @return
	 */
	@RequestMapping(value = "/{uid}", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap findOne(@PathVariable("uid") String uid) {
		return success(userSpaceService.findByUID(uid));
	}

	/**
	 * 按注册号查找企业详细信息
	 * 
	 * @param businessCode
	 * @return
	 */
	@RequestMapping(value = "/detail/{businessCode}", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap findDetail(@PathVariable("businessCode") String businessCode) {
		return success(userSpaceService.findByBusinessCode(businessCode));
	}

	/**
	 * 按注册号查找企业详细信息
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/detail/id/{id}", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap findDetailById(@PathVariable("id") Long id) {
		return success(userSpaceService.findById(id));
	}

	/**
	 * 查找所有企业的信息
	 * 
	 * @param name
	 * @param businessCode
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value = "/detail/list", method = RequestMethod.GET)
	@ResponseBody
	public Page<UserSpaceDetailView> findAllDetail(String name, String businessCode, String address, int pageNumber, int pageSize) {
		return userSpaceService.findAll(name, businessCode, address, pageNumber, pageSize);
	}

	/**
	 * 按状态查找企业信息，已激活
	 * 
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value = "/detail/list", params = "status=ENABLED", method = RequestMethod.GET)
	@ResponseBody
	public Page<UserSpaceDetailView> findAllEnabledDetail(String name, String businessCode, int pageNumber, int pageSize) {
		return userSpaceService.findAllEnable(name, businessCode, pageNumber, pageSize);
	}

	/**
	 * 按状态查找企业信息，待审批
	 * 
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value = "/detail/list", params = "status=UNAUDIT", method = RequestMethod.GET)
	@ResponseBody
	public Page<UserSpaceDetailView> findAllUnAuditDetail(String name, String businessCode, int pageNumber, int pageSize) {
		return userSpaceService.findAllUnAudit(name, businessCode, pageNumber, pageSize);
	}

	/**
	 * 按状态查找企业信息，审批未通过
	 * 
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	@RequestMapping(value = "/detail/list", params = "status=UNAPPLY", method = RequestMethod.GET)
	@ResponseBody
	public Page<UserSpaceDetailView> findAllUnApplyDetail(String name, String businessCode, int pageNumber, int pageSize) {
		return userSpaceService.findAllUnApply(name, businessCode, pageNumber, pageSize);
	}

	/**
	 * 按状态查找企业信息，未激活
	 * 
	 * @param name
	 * @return
	 */
	@RequestMapping(value = "/detail/list", params = "status=UNACT", method = RequestMethod.GET)
	@ResponseBody
	public Page<UserSpaceDetailView> findAllUnActiveDetail(String name, String businessCode, int pageNumber, int pageSize) {
		return userSpaceService.findAllUnActive(name, businessCode, pageNumber, pageSize);
	}

	/**
	 * 审批通过
	 * 
	 * @param businessCode
	 * @return
	 */
	@RequestMapping(value = "/detail/audit", params = "enable=1")
	@ResponseBody
	public ModelMap enableDetail(String businessCode, Long id) {
		userSpaceService.enable(businessCode);
		UserSpaceDetail detail = userSpaceService.findByBusinessCode(businessCode);
		// 邮件
		return sendEmail(detail.getAdminEmail(), businessCode);
	}

	/**
	 * 审批未通过
	 * 
	 * @param reason
	 * @param businessCode
	 * @return
	 */
	@RequestMapping(value = "/detail/audit", params = "enable=0")
	@ResponseBody
	public ModelMap disableDetail(String reason, String businessCode, Long id) {
		userSpaceService.disable(id, reason);
		UserSpaceDetail detail = userSpaceService.findById(id);
		// 邮件
		Setting mailTpl = settingService.findOne("templateForSendMailAfterRegisterFailed");
		if (mailTpl != null && detail.getAdminEmail() != null) {
			ModelMap data = new ModelMap();
			data.put("reason", reason);
			data.put("content", detail);
			mailService.send(mailTpl.getValue(), detail.getAdminEmail(), data);
			return success();
		}
		return error("没有找到邮件模板，请设置后重新发送激活邮件");
	}

	/**
	 * 重新发送激活邮件
	 * 
	 * @param email
	 * @param businessCode
	 * @return
	 */
	@RequestMapping(value = "/detail/send")
	@ResponseBody
	public ModelMap sendEmail(String email, String businessCode) {
		UserSpaceDetail detail = userSpaceService.findByBusinessCode(businessCode);
		// 邮件
		Setting mailTpl = settingService.findOne("templateForSendMailAfterRegisterSuccess");
		if (mailTpl != null && detail.getAdminEmail() != null) {
			// 3 days
			final Token token = new Token(detail.getBusinessCode(), 259200);

			tokenService.save(token);
			ModelMap data = new ModelMap();
			data.put("token", token.getId());
			data.put("content", detail);
			mailService.send(mailTpl.getValue(), email, data);
			return success();
		}
		return error("没有找到邮件模板，请设置后重新发送邮件");
	}

	/**
	 * 修改管理员邮箱
	 * 
	 * @param email
	 * @param businessCode
	 * @param tel
	 * @return
	 */
	@RequestMapping(value = "/detail/updateMail", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap updateEmail(String email, String businessCode, String tel) {
		UserSpaceDetail detail = userSpaceService.findByBusinessCode(businessCode);
		UserDetail userdetail = userService.findOne(tel);
		if (detail != null) {
			detail.setAdminEmail(email);
			userSpaceService.save(detail);
		} else {
			return error("暂未查询到企业相关信息，可能已被删除");
		}

		if (userdetail != null) {
			userdetail.setEmail(email);
			userDao.save(userdetail);
		} else {
			return error("暂未询到用户相关信息，可能已被删除");
		}
		return success("修改邮箱成功");
	}

	/**
	 * 开通应用
	 * 
	 * @param businessCode
	 * @param app
	 * @return
	 */
	@RequestMapping(value = "/applyApp")
	@ResponseBody
	public ModelMap applyApp(String businessCode, final String app, final ApplyAppView view) {
		final UserSpaceDetail detail = userSpaceService.findByBusinessCode(businessCode);
		userSpaceService.applyApp(businessCode, app, view.getPassword(), view.getUserDetails());
		view.getUserDetails().add(new UserDetail(detail));
		// 知会下企业用户
		ExecuteUtils.asyncExecute(new Runnable() {

			@Override
			public void run() {
				ExecuteUtils.execute(new ICallable<Void, UserDetail>() {

					@Override
					public Void call(UserDetail user) throws Exception {
						// 邮件
						Setting mailTpl = settingService.findOne("templateForSendMailWhenRegisterFinished." + app + "."
								+ (!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);
						}
						return null;
					}

				}, view.getUserDetails());
			}
		});
		return success();
	}

	/**
	 * 修改企业名称简称
	 * 
	 * @param id
	 * @param renewName
	 * @param renewShortName
	 * @return
	 */
	@SuppressWarnings("unused")
	@RequestMapping(value = "/renewUserSpace", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap renewUserSpace(Long id, String renewName, String renewShortName, String renewAdress, String renewUid) {
		UserSpaceDetail detail = userSpaceService.findById(id);
		String businessCode = detail.getBusinessCode();
		if (detail != null) {
			if (renewName != null) {
				detail.setName(renewName);
			}
			if (renewShortName != null) {
				detail.setShortName(renewShortName);
			}
			if (renewAdress != null) {
				detail.setAddress(renewAdress);
			}
			if (renewUid != null) {
				detail.setBusinessCode(renewUid);
			}
			userSpaceService.save(detail);
			//更新ac$userspace中的信息
			UserSpace space = userSpaceService.findOne(b2b, businessCode);
			if (space != null) {
				Long enuu = Long.valueOf(space.getDialectUID());
				detail.setUu(enuu);
				space.setName(renewName);
				space.setUid(renewUid);
				try {
					userSpaceService.update(space, space.getId());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// 同步到平台更新企业信息
			App app = appService.findOne(b2b);
			try {
				userSpaceService.callbacktoAppAfterUpdate(app, detail);

			} catch (Exception e) {
				e.printStackTrace();
			}
			// 更新管理平台企业信息的数据
			try {
				platformManageService.updateEnterpriseInfoInManage(detail, businessCode);
			} catch (Exception e) {
				e.printStackTrace();
			}
			// 更新管理平台控制中心数据
			try {
				platformManageService.updateMasterInfoInManage(detail, businessCode);
			} catch (Exception e) {
				e.printStackTrace();
			}
			// 同步更新到商城
			try {
				sysDataToMallService.UserSpace(space, detail);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			return error("暂未查询到企业相关信息，请刷新后重试");
		}
		return success("企业名称修改成功");
	}
	
	/**
	 * 校验企业名称
	 * 
	 * @param name
	 * @return
	 */
	@RequestMapping(params = "_operate=validName", method = RequestMethod.GET)
	@ResponseBody
	public AppCreateInfo validName(String name) {
		// 去掉可能存在的空格再进行检验
		name = StringUtils.trimAllWhitespace(name);
		AppCreateInfo info = new AppCreateInfo();
		info.setHasCreate(false);
		info.setInCloud(false);
		if (!StringUtils.isEmpty(name)) {
			UserSpaceDetail detail = userSpaceService.findByName(name);
			if (null != detail) {
				// 是否注册过saas
				UserSpace userSpace = userSpaceService.findOne(saas, detail.getBusinessCode());
				if (userSpace != null) {
					info.setHasCreate(true);
				}
				// 是否注册过uas
				userSpace = userSpaceService.findOne(uas, detail.getBusinessCode());
				if (userSpace != null) {
					info.setHasCreate(true);
				}
				// 是否注册过平台
				userSpace = userSpaceService.findOne(b2b, detail.getBusinessCode());
				if (userSpace != null) {
					info.setInCloud(true);
					info.setBusinessCode(userSpace.getUid());
				}
			}
		}
		return info;
	}

	/**
	 * 校验企业营业执照
	 * 
	 * @param businessCode
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(params = "_operate=validBusinessCode", method = RequestMethod.GET)
	@ResponseBody
	public AppCreateInfo validBusinessCode(String businessCode) throws UnsupportedEncodingException {
		// 去掉可能存在的空格再进行检验
		businessCode = StringUtils.trimAllWhitespace(businessCode);
		AppCreateInfo info = new AppCreateInfo();
		info.setHasCreate(false);
		info.setInCloud(false);
		if (!StringUtils.isEmpty(businessCode)) {
			UserSpaceDetail detail = userSpaceService.findByBusinessCode(businessCode);
			if (null != detail) {
				// 是否注册过saas
				UserSpace userSpace = userSpaceService.findOne(saas, detail.getBusinessCode());
				if (userSpace != null) {
					info.setHasCreate(true);
				}
				// 是否注册过uas
				userSpace = userSpaceService.findOne(uas, detail.getBusinessCode());
				if (userSpace != null) {
					info.setHasCreate(true);
				}
				// 是否注册过平台
				userSpace = userSpaceService.findOne(b2b, detail.getBusinessCode());
				if (userSpace != null) {
					info.setInCloud(true);
					info.setName(userSpace.getName());
				}
			}
		}
		return info;
	}

	/**
	 * 通过营业执照号查找 企业详细信息
	 *
	 * @param businessCode
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(params = "_operate=findByBusinessCode", method = RequestMethod.GET)
	@ResponseBody
	public UserSpaceDetail findByBusinessCode(String businessCode) throws UnsupportedEncodingException {
		return userSpaceService.findByBusinessCode(businessCode);
	}
	
	/**
	 * ERP、SAAS新开账套注册平台
	 * 
	 * @param detail
	 * @param userInfos
	 */
	@RequestMapping(params = "_operate=registerBranchAccount", method = RequestMethod.POST)
	@ResponseBody
	public AppCreateInfo applyApp(String detail, String userInfos) {
		AppCreateInfo info = new AppCreateInfo();
		List<UserDetail> users = JSON.parseArray(userInfos, UserDetail.class);
		UserSpaceDetail userSpaceDetail = JSONObject.parseObject(detail, UserSpaceDetail.class);
		userSpaceDetail.setRegisterDate(new Date().getTime());
		userSpaceDetail = userSpaceService.save(userSpaceDetail);
		String password = null;
		User user = userService.findOne(uas, userSpaceDetail.getBusinessCode(), userSpaceDetail.getAdminTel());
		if (user != null) {
			password = user.getPassword();
		} else {
			user = userService.findOne(saas, userSpaceDetail.getBusinessCode(), userSpaceDetail.getAdminTel());
			if (user != null) {
				password = user.getPassword();
			} else {
				password = "111111";
			}
		}
		userSpaceService.applyApp(userSpaceDetail.getBusinessCode(), b2b, password, users);
		// 注册完后查询uu号等信息
		UserSpace space = userSpaceService.findOne(b2b, userSpaceDetail.getBusinessCode());
		if (null != space) {
			info.setInCloud(true);
			info.setEnuu(space.getDialectUID());
		} else {
			info.setInCloud(false);
		}
		return info;
	}
	
	/**
	 * 根据用户的手机号码查找对应的所属企业和企业地址
	 * 
	 * @param tel
	 * @return
	 */
	@RequestMapping(value = "/userSpaceDetail", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap getUserSpaceDetail(String tel) {
		List<String> tels = Arrays.asList(tel.split(","));
		return CollectionUtils.isEmpty(tels) ? new ModelMap("listdata", "请先输入电话号码")
				: new ModelMap("listdata", userSpaceService.findByTel(tels));
	}

	/**
	 * 根据用户的手机号查询企业信息和个人信息
	 * 
	 * @param tel
	 * @return
	 */
	@RequestMapping(value = "/userInfos", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap getUserInfos(String tel) {
		List<String> tels = Arrays.asList(tel.split(","));
		return CollectionUtils.isEmpty(tels) ? new ModelMap("listdata", "请先输入电话号码")
				: new ModelMap("listdata", userSpaceService.findUserByTel(tels));
	}

	/**
	 * 通过企业名称查询企业相关信息
	 * 
	 * @param keyword
	 * @return
	 */
	@RequestMapping(value = "/userSpaceDetail/keyword", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap getUserSpaceDetailByKeyword(String keyword, Integer pageNumber) {
		return StringUtils.isEmpty(keyword) ? new ModelMap("listdata", "请先输入企业名称")
				: new ModelMap("listdata", userSpaceService.findByKeyword(keyword, pageNumber));
	}

	/**
	 * 通过企业名称查询该企业的员工的信息
	 * 
	 * @param name
	 * @param pageNumber
	 * @return
	 */
	@RequestMapping(value = "/employees", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap getEmployees(String name, Integer pageNumber) {
		return StringUtils.isEmpty(name) ? new ModelMap("listdata", "请先输入企业名称")
				: new ModelMap("listdata", userService.findByEnName(name, pageNumber));
	}

	/**
	 * 商城个人用户重新注册企业相关
	 * 
	 * @param detail
	 * @return
	 */
	@RequestMapping(params = "_operate=registForMall", method = RequestMethod.POST)
	@ResponseBody
	public AppCreateInfo applyAppForMall(String detail) {
		AppCreateInfo info = new AppCreateInfo();
		UserSpaceDetail userSpaceDetail = JSONObject.parseObject(detail, UserSpaceDetail.class);
		userSpaceDetail.setRegisterDate(new Date().getTime());
		userSpaceDetail = userSpaceService.save(userSpaceDetail);
		String password = null;
		List<UserView> users = userService.findByAppAndUID(b2b, userSpaceDetail.getAdminTel());
		if (!CollectionUtils.isEmpty(users)) {
			password = users.get(0).getPassword();
		} else {
			password = "111111";
		}
		userSpaceService.applyApp(userSpaceDetail.getBusinessCode(), b2b, password, null);
		// 注册完后查询uu号等信息
		UserSpace space = userSpaceService.findOne(b2b, userSpaceDetail.getBusinessCode());
		if (null != space) {
			info.setInCloud(true);
			info.setEnuu(space.getDialectUID());
		} else {
			info.setInCloud(false);
		}
		return info;
	}
}
