package com.uas.account.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uas.account.core.Logger;
import com.uas.account.core.Page;
import com.uas.account.core.Status;
import com.uas.account.dao.ChangeAdminDao;
import com.uas.account.dao.UserDao;
import com.uas.account.dao.UserSpaceDao;
import com.uas.account.entity.App;
import com.uas.account.entity.ChangeAdminDetail;
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.VisibleError;
import com.uas.account.util.AccountUtils;
import com.uas.sso.common.util.HttpUtil;
import com.uas.sso.common.util.HttpUtil.ResponseWrap;

@Service
@Transactional
public class ChangeAdminServiceImpl implements ChangeAdminService {

	@Autowired
	private ChangeAdminDao changeAdminDao;

	@Autowired
	private UserSpaceService userSpaceService;

	@Autowired
	private UserSpaceDao userSpaceDao;

	@Autowired
	private UserDao userDao;

	@Autowired
	private AppService appService;

	@Autowired
	private UserService userService;

	@Autowired
	private SysDataToMallService sysService;

	private Logger logger = Logger.getLogger();

	private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");

	@Override
	public ChangeAdminDetail save(ChangeAdminDetail detail) {
		return changeAdminDao.save(detail);
	}

	@Override
	@CacheEvict(value = "userspaces", allEntries = true)
	public ChangeAdminDetail submit(ChangeAdminDetail detail) {
		ChangeAdminDetail oldDetail = findByBusinessCode(detail.getBusinessCode());
		if (oldDetail != null && oldDetail.getAuditStatus().equals(Status.UNAUDIT.value())) {
			throw new VisibleError("请勿重复提交申请！");
		}
		UserSpace userSpace = userSpaceService.findOne("b2b", StringUtils.trimAllWhitespace(detail.getBusinessCode()));
		if (userSpace == null) {
			throw new VisibleError("暂未查询到与“" + detail.getEnName() + "”相关的企业信息，请检查输入的企业与营业执照是否匹配或先进行注册");
		}
		detail.setAuditStatus(Status.UNAUDIT.value());
		detail.setEnDate(new Date());
		detail.setBusinessCode(detail.getBusinessCode());
		detail.setEnName(detail.getEnName());
		detail.setAdminName(detail.getAdminName());
		detail.setAdminTel(detail.getAdminTel());
		detail.setAdminEmail(detail.getAdminEmail());
		detail.setAppId(userSpace.getAppId());
		detail.setMethod(detail.getMethod());
		// 存储管理员信息
		UserDetail userDetail = userService.findOne(detail.getAdminTel());
		List<User> user = userService.findByUID(detail.getAdminTel());
		if (CollectionUtils.isEmpty(user)) {
			for (User users : user) {
				users.setAppId(userSpace.getAppId());
				users.setName(detail.getAdminName());
				users.setUid(detail.getAdminTel());
				users.setSecondUID(detail.getAdminEmail());
				users.setSpaceUID(detail.getBusinessCode());
				User userInfo = user.get(0);
				userDao.save(userInfo);
				if (userDetail == null) {
					UserDetail userDetails = new UserDetail();
					userDetails.setEmail(detail.getAdminEmail());
					userDetails.setName(detail.getAdminName());
					userDetails.setMobile(detail.getAdminTel());
					logger.info("userDao", String.format("通过{Mobile, %s}存储管理员信息", userDetails.getMobile()));
					userDao.save(userDetails);
					// 传过去给b2b，生成UU号
					App app = appService.findOne(detail.getAppId());
					try {
						userService.syncUserToApp(app, userInfo, userDetails);
					} catch (Exception e) {
						logger.error("更换管理员", String.format("传输数据出错", userDetails.getName(), userDetails.getMobile()));
						e.printStackTrace();
					}
					userService.save(userInfo, userDetails);
				}

			}
		}

		logger.info(this.getClass(), detail.getBusinessCode(),
				String.format("更换管理员申请信息存储，%s From: %s, To: sso", userSpace.getName(), userSpace.getAppId()),
				userSpace);
		return changeAdminDao.save(detail);
	}

	/**
	 * 查询所有信息
	 */
	@Override
	public Page<ChangeAdminDetail> findAll(int pageNumber, int pageSize, String name, String businessCode,
			String userName) {
		return changeAdminDao.findAll(pageNumber, pageSize, null, name, businessCode, userName);
	}

	/**
	 * 审核通过
	 */
	@Override
	public Page<ChangeAdminDetail> findAllEnable(int pageNumber, int pageSize, String name, String businessCode,
			String userName) {
		return changeAdminDao.findAll(pageNumber, pageSize, Status.ENABLED.value(), name, businessCode, userName);
	}

	/**
	 * 待审核
	 */
	@Override
	public Page<ChangeAdminDetail> findAllUnAudit(int pageNumber, int pageSize, String name, String businessCode,
			String userName) {
		return changeAdminDao.findAll(pageNumber, pageSize, Status.UNAUDIT.value(), name, businessCode, userName);
	}

	/**
	 * 审核失败
	 */
	@Override
	public Page<ChangeAdminDetail> findAllUnApply(int pageNumber, int pageSize, String name, String businessCode,
			String userName) {
		return changeAdminDao.findAll(pageNumber, pageSize, Status.UNAPPLY.value(), name, businessCode, userName);
	}

	/**
	 * 更换管理员审核通过
	 */
	@Override
	public void enable(String businessCode) {
		UserSpaceDetail detail = userSpaceService.findByBusinessCode(businessCode);
		ChangeAdminDetail chdetail = findByBusinessCode(businessCode);
		UserDetail userdetail = userDao.findOne(chdetail.getAdminTel());
		UserSpace userSpace = userSpaceService.findOne(chdetail.getAppId(), businessCode);
		App app = appService.findOne(chdetail.getAppId());
		if (userdetail == null) {
			UserDetail userDetailInfo = new UserDetail();
			userDetailInfo.setEmail(chdetail.getAdminEmail());
			userDetailInfo.setName(chdetail.getAdminName());
			userDetailInfo.setMobile(chdetail.getAdminTel());
			userDetailInfo.setJob("管理员");
			userDao.save(userDetailInfo);
			User newUser = new User();
			newUser.setAppId(chdetail.getAppId());
			newUser.setName(chdetail.getAdminName());
			newUser.setUid(chdetail.getAdminTel());
			newUser.setSecondUID(chdetail.getAdminEmail());

			// 同步到商务平台
			try {
				userService.syncUserToApp(app, newUser, userDetailInfo);
			} catch (Exception error) {
				throw new VisibleError(error.getMessage());
			}
			try {
				AccountUtils.saveUser(chdetail.getAdminTel(), businessCode, userDetailInfo);
			} catch (Exception e) {
				throw new VisibleError("新增用户失败");
			}

			newUser.setSpaceId(userSpace.getId());
			newUser.setSpaceUID(businessCode);
			newUser.setSpaceDialectUID(userSpace.getDialectUID());
			List<UserView> user = userService.findByAppAndUID(chdetail.getAppId(), chdetail.getAdminTel());
			if (!CollectionUtils.isEmpty(user)) {
				newUser.setPassword(user.get(0).getPassword());
				newUser.setSalt(user.get(0).getSalt());
				newUser.setDialectUID(user.get(0).getDialectUID());
				chdetail.setAdminuu(Long.valueOf(newUser.getDialectUID()));
			}
			newUser = userDao.save(newUser);
			try {
				sysService.user(newUser);
				logger.info("更换管理员", "同步用户" + newUser.getDialectUID() + "到商城，time:" + sdf.format(new Date()));
			} catch (Exception e) {
				logger.error("更换管理员", "同步用户" + newUser.getDialectUID() + "到商城失败,time" + sdf.format(new Date()));
			}
		} else if (userdetail != null) {
			User userInfo = userDao.findOne(chdetail.getAppId(), businessCode, chdetail.getAdminTel());
			if (userInfo == null) {
				User userInfos = new User();
				UserDetail userDetail = new UserDetail();
				userInfos.setAppId(chdetail.getAppId());
				userInfos.setName(chdetail.getAdminName());
				userInfos.setUid(chdetail.getAdminTel());
				userInfos.setSecondUID(chdetail.getAdminEmail());
				userInfos.setSpaceId(userSpace.getId());
				userInfos.setSpaceUID(businessCode);
				userInfos.setSpaceDialectUID(userSpace.getDialectUID());
				List<UserView> user = userService.findByAppAndUID(chdetail.getAppId(), chdetail.getAdminTel());
				if (!CollectionUtils.isEmpty(user)) {
					userInfos.setPassword(user.get(0).getPassword());
					userInfos.setSalt(user.get(0).getSalt());
					userInfos.setDialectUID(user.get(0).getDialectUID());
					chdetail.setAdminuu(Long.valueOf(userInfos.getDialectUID()));
				}
				userInfos = userDao.save(userInfos);
				try {
					sysService.user(userInfos);
					logger.info("更换管理员", "同步用户" + userInfos.getDialectUID() + "到商城，time:" + sdf.format(new Date()));
				} catch (Exception e) {
					logger.error("更换管理员", "同步用户" + userInfos.getDialectUID() + "到商城失败,time" + sdf.format(new Date()));
				}
				userDetail.setEmail(chdetail.getAdminEmail());
				userDetail.setName(chdetail.getAdminName());
				userDetail.setMobile(chdetail.getAdminTel());
				userdetail.setJob("管理员");
				// 同步到商务平台
				try {
					userService.syncUserToApp(app, userInfos, userDetail);
				} catch (Exception error) {
					throw new VisibleError(error.getMessage());
				}
				try {
					AccountUtils.saveUser(chdetail.getAdminTel(), businessCode, userDetail);
				} catch (Exception e) {
					throw new VisibleError("新增用户失败");
				}
				userDao.save(userDetail);
			}
		}
		if (detail != null) {
			detail.setAdminName(chdetail.getAdminName());
			detail.setAdminTel(chdetail.getAdminTel());
			detail.setAdminEmail(chdetail.getAdminEmail());
			detail.setBusinessCode(chdetail.getBusinessCode());
			userSpaceDao.save(detail);
		} else {
			throw new VisibleError("找不到该企业资料");
		}
		chdetail.setAuditStatus(Status.ENABLED.value());
		chdetail = changeAdminDao.save(chdetail);
		try {
			logger.info(this.getClass(), detail.getBusinessCode(),
					String.format("更换管理员审核通操作，%s From: %s, To: b2b", userSpace.getName(), userSpace.getAppId()),
					userSpace);
			syncUserToApp(app, chdetail);
			sysService.ChangeAdmin(chdetail);
		} catch (Exception e) {
			logger.error(this.getClass(), detail.getBusinessCode(),
					String.format("更换管理员审核通操作，%s From: %s, To: b2b", userSpace.getName(), userSpace.getAppId()),
					userSpace);
			throw new VisibleError(e.getMessage());
		}

	}

	/**
	 * 更换管理员审核未通过
	 */
	@Override
	public void disable(String businessCode, String reason) {
		ChangeAdminDetail detail = findByBusinessCode(businessCode);
		if (detail != null) {
			detail.setAuditStatus(Status.UNAPPLY.value());
			detail.setAuditResult(reason);
			detail.setEnDate(new Date());
			logger.info(this.getClass(), detail.getBusinessCode(),
					String.format("更换管理员审核未通过操作，%s From: %s, to: sso", detail.getEnName(), detail.getAppId()), detail);
			changeAdminDao.save(detail);
		} else {
			logger.error("更换管理员", String.format("根据{businessCode: %s}没有找到企业信息", businessCode));
			throw new VisibleError("找不到该企业资料");
		}
	}

	/**
	 * 通过businessCode查询所有信息
	 */
	@Override
	public ChangeAdminDetail findByBusinessCode(String businessCode) {
		return changeAdminDao.findByBusinessCode(businessCode);
	}

	@Override
	public ChangeAdminDetail syncUserToApp(App app, ChangeAdminDetail detail) throws Exception {
		String url = app.getBackChangeAdminUrl();
		detail.setEnDate(null); // 不需要传输时间，而且时间需要进行转换处理
		if (!StringUtils.isEmpty(url)) {
			JSONObject formData = JSON.parseObject(JSON.toJSONString(detail));
			ResponseWrap res = HttpUtil.doPost(url, formData);// 5分钟超时
			if (!res.isSuccess())
				throw new Exception(res.getContent());
		}
		return null;
	}


}
