package com.goafanti.admin.controller;

import java.text.ParseException;
import java.util.Calendar;
import java.util.UUID;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.goafanti.admin.bo.InputAdmin;
import com.goafanti.admin.service.AdminService;
import com.goafanti.common.bo.Result;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.controller.CertifyApiController;
import com.goafanti.common.enums.AchievementAuditStatus;
import com.goafanti.common.enums.AdminFields;
import com.goafanti.common.enums.CertifySubmitType;
import com.goafanti.common.enums.IdentityAuditStatus;
import com.goafanti.common.enums.IdentityProcess;
import com.goafanti.common.enums.OrganizationIdentityFields;
import com.goafanti.common.enums.UserFields;
import com.goafanti.common.enums.UserIdentityFields;
import com.goafanti.common.enums.UserLevel;
import com.goafanti.common.model.Admin;
import com.goafanti.common.model.OrganizationIdentity;
import com.goafanti.common.model.User;
import com.goafanti.common.model.UserIdentity;
import com.goafanti.common.utils.DateUtils;
import com.goafanti.common.utils.PasswordUtil;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.easemob.EasemobUtils;
import com.goafanti.user.bo.InputOrganizationIdentity;
import com.goafanti.user.bo.InputUser;
import com.goafanti.user.bo.InputUserIdentity;
import com.goafanti.user.service.JpushEasemobAccountService;
import com.goafanti.user.service.OrganizationIdentityService;
import com.goafanti.user.service.UserIdentityService;
import com.goafanti.user.service.UserService;

@Controller
@RequestMapping(value = "/api/admin")
public class AdminApiController extends CertifyApiController {
	@Resource
	private UserService						userService;
	@Resource
	private UserIdentityService				userIdentityService;
	@Resource
	private OrganizationIdentityService		organizationIdentityService;
	@Resource(name = "passwordUtil")
	private PasswordUtil					passwordUtil;
	@Resource
	private AdminService					adminService;
	@Resource
	private JpushEasemobAccountService 		jpushEasemobAccountService;
	@Autowired
	EasemobUtils							easemobUtils;

	/**
	 * 获取营销员及营销经理下拉
	 */
	@RequestMapping(value = "/salesman", method = RequestMethod.GET)
	public Result getSalesMan() {
		Result res = new Result();
		res.setData(adminService.selectSalesman());
		return res;
	}

	/**
	 * 管理员角色
	 */
	@RequestMapping(value = "/role", method = RequestMethod.GET)
	public Result getRole(String uid) {
		Result res = new Result();
		if (StringUtils.isBlank(uid)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "管理员ID"));
			return res;
		}
		res.setData(adminService.selectRoleByPrimaryKey(uid));
		return res;
	}

	/**
	 * 管理员本人信息详情
	 */
	@RequestMapping(value = "/adminInfo", method = RequestMethod.GET)
	public Result adminInfo() {
		Result res = new Result();
		if (TokenManager.hasRole(AFTConstants.SUPERADMIN)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "超级管理员"));
			return res;
		}
		res.setData(adminService.selectByPrimaryKey(TokenManager.getAdminId()));
		return res;
	}

	/**
	 * 管理员修改本人信息
	 */
	@RequestMapping(value = "/updateAdminInfo", method = RequestMethod.POST)
	public Result updateAdminInfo(@Valid InputAdmin admin, String pwd, BindingResult bindingResult) {
		Result res = new Result();

		if (TokenManager.hasRole(AFTConstants.SUPERADMIN)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "超级管理员"));
			return res;
		}
		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					AdminFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		if (StringUtils.isBlank(admin.getId())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "用户id"));
			return res;
		}

		if (StringUtils.isBlank(admin.getMobile())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "登录帐号为空", "登录帐号"));
			return res;
		}

		if (StringUtils.isBlank(admin.getName())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "用户名为空", "用户名"));
			return res;
		}

		Admin a = adminService.selectByMobile(admin.getMobile().trim(),null);
		if (!TokenManager.getAdminId().equals(a.getId())) {
			res.getError().add(buildError(ErrorConstants.USER_ALREADY_EXIST, "当前用户已注册！"));
			return res;
		}

		Admin ad = new Admin();
		BeanUtils.copyProperties(admin, ad);
		Admin aa = adminService.selectByPrimaryKey(TokenManager.getAdminId());
		ad.setMobile(ad.getMobile().trim());
		ad.setCreateTime(aa.getCreateTime());

		if (!StringUtils.isBlank(ad.getPassword())) {
			if (StringUtils.isBlank(pwd)) {
				res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "", "原密码"));
				return res;
			}
			if (!aa.getPassword().equals(passwordUtil.getEncryptPwd(pwd, aa.getCreateTime()))) {
				res.getError().add(buildError(ErrorConstants.PWD_NOT_MATCH_ERROR, "", "原密码"));
				return res;
			}
		} else {
			ad.setPassword(aa.getPassword());
		}
		ad.setPassword(passwordUtil.getEncryptPwd(ad));
		res.setData(adminService.updateByPrimaryKey(ad));
		return res;
	}

	/**
	 * 新增用户
	 */
	@RequestMapping(value = "/addNewUser", method = RequestMethod.POST)
	public Result addNewUser(@Valid InputUser inputUser, BindingResult bindingResult) {
		Result res = new Result();

		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					UserFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		if (StringUtils.isBlank(inputUser.getMobile())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "mobile", "mobile"));
			return res;
		}


		User user = userService.selectByMobieAndType(inputUser.getMobile().trim(), null);
		if (null != user) {
			res.getError().add(buildError(ErrorConstants.USER_ALREADY_EXIST, "当前用户已注册！"));
			return res;
		}
		User u = new User();
		u.setId(UUID.randomUUID().toString());
		u.setMobile(inputUser.getMobile().trim());
		u.setPassword(inputUser.getMobile().trim());
		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		u.setCreateTime(now.getTime());
		u.setPassword(passwordUtil.getEncryptPwd(u));
		u.setLvl(UserLevel.GENERAL.getCode());
		u.setAid(TokenManager.getAdminId());
		userService.insertRegister(u,inputUser.getUnitName(), inputUser.getUsername());
		return res;
	}

	/**
	 * 个人用户信息明细
	 */
	@RequestMapping(value = "/userDetail", method = RequestMethod.POST)
	public Result userDetail(String uid) {
		Result res = new Result();

		if (StringUtils.isBlank(uid)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到用户", "用户"));
			return res;
		}
		res.setData(userIdentityService.selectUserIdentityByUserIdAdmin(uid));
		return res;
	}

	/**
	 * 修改个人用户信息
	 */
	@RequestMapping(value = "/updateUserDetail", method = RequestMethod.POST)
	public Result updateUserDetail(@Valid InputUserIdentity userIdentity, BindingResult bindingResult,
			String paymentDateFormattedDate, String saveSign) {
		Result res = new Result();

		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					UserIdentityFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		if (StringUtils.isBlank(userIdentity.getId())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到认证ID", "认证ID"));
			return res;
		}

		if (StringUtils.isBlank(userIdentity.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到用户", "用户"));
			return res;
		}

		if (StringUtils.isBlank(saveSign)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到保存提交方式", "保存提交方式"));
			return res;
		}

		UserIdentity idd = userIdentityService.selectUserIdentityByUserId(userIdentity.getUid());
		if (IdentityAuditStatus.COMMITTED.getCode().equals(idd.getAuditStatus())) {
			res.getError().add(buildError("", "审核中，无法保存或提交！"));
			return res;
		}

		Integer level = userIdentity.getLevel();
		if (!UserLevel.GENERAL.getCode().equals(level)) {
			User u = userService.selectByPrimaryKey(userIdentity.getUid());
			if (UserLevel.GENERAL.getCode().equals(u.getLvl())) {
				res.getError().add(buildError(ErrorConstants.NON_CERTIFIED, "未通过实名认证，无法操作！"));
				return res;
			}
		}

		if (!saveSign.equals(CertifySubmitType.SAVE.getCode())
				&& !saveSign.equals(CertifySubmitType.SUBMIT.getCode())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "保存提交方式"));
			return res;
		}

		if (!StringUtils.isBlank(paymentDateFormattedDate)) {
			try {
				userIdentity.setPaymentDate(DateUtils.parseDate(paymentDateFormattedDate, AFTConstants.YYYYMMDD));
			} catch (ParseException e) {
			}
		}

		UserIdentity ui = new UserIdentity();
		BeanUtils.copyProperties(userIdentity, ui);

		if (CertifySubmitType.SUBMIT.getCode().equals(saveSign)) {
			User u = userService.selectByPrimaryKey(userIdentity.getUid());
			if (!UserLevel.GENERAL.getCode().equals(u.getLvl())) {
				res.getError().add(buildError("", "已通过实名认证，无法操作！"));
				return res;
			}
			ui.setProcess(IdentityProcess.COMMITTED.getCode());
			ui.setAuditStatus(IdentityAuditStatus.COMMITTED.getCode());
		}
		res.setData(userIdentityService.updateUserDetail(ui, saveSign, level));
		return res;
	}

	/**
	 * 团体用户明细
	 */
	@RequestMapping(value = "/orgDetail", method = RequestMethod.POST)
	public Result orgDetail(String uid) {
		Result res = new Result();
		if (StringUtils.isBlank(uid)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到用户", "用户"));
			return res;
		}
		//res.setData(organizationIdentityService.selectOrgIdentityDetailByUserIdAdmin(uid));
		return res;
	}

	/**
	 * 修改团体用户信息
	 */
	@RequestMapping(value = "/updateOrgDetail", method = RequestMethod.POST)
	public Result updateOrgDetail(@Valid InputOrganizationIdentity orgIdentity, BindingResult bindingResult,
			String paymentDateFormattedDate, String saveSign) {
		Result res = new Result();

		if (bindingResult.hasErrors()) {
			res.getError().add(buildErrorByMsg(bindingResult.getFieldError().getDefaultMessage(),
					OrganizationIdentityFields.getFieldDesc(bindingResult.getFieldError().getField())));
			return res;
		}

		if (StringUtils.isBlank(orgIdentity.getUid())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到用户", "用户"));
			return res;
		}

		if (StringUtils.isBlank(saveSign)) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "找不到保存提交方式", "保存提交方式"));
			return res;
		}

		if (!saveSign.equals(CertifySubmitType.SAVE.getCode())
				&& !saveSign.equals(CertifySubmitType.SUBMIT.getCode())) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "保存提交方式"));
			return res;
		}

		OrganizationIdentity idd = organizationIdentityService.selectOrgIdentityByUserId(orgIdentity.getUid());
		if (IdentityAuditStatus.COMMITTED.getCode().equals(idd.getAuditStatus())) {
			res.getError().add(buildError("", "审核中，无法保存或提交！"));
			return res;
		}
		Integer level = orgIdentity.getLevel();
		if (!UserLevel.GENERAL.getCode().equals(level)) {
			User u = userService.selectByPrimaryKey(orgIdentity.getUid());
			if (UserLevel.GENERAL.getCode().equals(u.getLvl())) {
				res.getError().add(buildError(ErrorConstants.NON_CERTIFIED, "未通过实名认证，无法操作！"));
				return res;
			}
		}

		if (!StringUtils.isBlank(paymentDateFormattedDate)) {
			try {
				orgIdentity.setPaymentDate(DateUtils.parseDate(paymentDateFormattedDate, AFTConstants.YYYYMMDD));
			} catch (ParseException e) {
			}
		}

		OrganizationIdentity oi = new OrganizationIdentity();
		BeanUtils.copyProperties(orgIdentity, oi);
		if (orgIdentity.getRegisteredCapital() != null) {
			oi.setRegisteredCapital(orgIdentity.getRegisteredCapital());
		}
		if (CertifySubmitType.SUBMIT.getCode().equals(saveSign)) {
			User u = userService.selectByPrimaryKey(oi.getUid());
			if (!UserLevel.GENERAL.getCode().equals(u.getLvl())) {
				res.getError().add(buildError("", "已通过实名认证，无法操作！"));
				return res;
			}
			oi.setProcess(IdentityProcess.COMMITTED.getCode());
			oi.setAuditStatus(IdentityAuditStatus.COMMITTED.getCode());
		}
		//res.setData(organizationIdentityService.updateOrgDetail(oi, saveSign, level));
		return res;
	}
	
	
	/**
	 * 团体用户明细
	 * 
	 * type 0-个人  1-单位
	 */
	@RequestMapping(value = "/listJpushUser", method = RequestMethod.GET)
	public Result getJpushUser(Integer type,Integer pageNo,Integer pageSize) {
		Result res = new Result();
		if(type==null ||(type!=0 && type !=1)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR,"","类型错误"));
			return res;
		}
		res.setData(jpushEasemobAccountService.findJpushClientsByType(type, pageNo, pageSize));
		return res;
	}
	
	//获得专家顾问审核数据
	@RequestMapping(value="/getExpertAuditList", method = RequestMethod.GET )
	public Result getExpertAuditList(InputUserIdentity identity, Integer pageNo, Integer pageSize){
		Result res = new Result();
		res.setData(userIdentityService.getExpertAuditList(identity, pageNo, pageSize));
		return res;
	}
	
	//获得某个人认证的详情信息
	@RequestMapping(value="/getUserIdentityByUid" , method = RequestMethod.GET)
	public Result getUserIdentityByUid(String uid){
		Result res = new Result();
		res.setData(userIdentityService.getUserIdentityByUid(uid));
		return res;
	}
		
	//管理员更改审核状态
	@RequestMapping(value="/auditing", method = RequestMethod.POST)
	public Result auditing(UserIdentity identity){
		Result res = new Result();
		if(AchievementAuditStatus.UNAUDITED.getCode().intValue() == identity.getAuditStatus() && null == identity.getAuditInfo()){
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR,"","审核不通过时必须填写原因"));
		}
		res.setData(userIdentityService.updateAuditing(identity));
		return res;
	}
	//管理员打回专家顾问
		@RequestMapping(value="/annul", method = RequestMethod.POST)
		public Result annul(UserIdentity identity){
			Result res = new Result();
			if (StringUtils.isBlank(identity.getId())) {
				res.getError().add(buildError(ErrorConstants.PARAM_ERROR,"","撤销"));
				return res;
			}
			identity.setAuditStatus(3);
			identity.setAuditInfo("");
			res.setData(userIdentityService.updateAuditing(identity));
			return res;
		}
	
	//获得注册用户信息
	@RequestMapping(value="/user/info", method = RequestMethod.GET)
	public Result userInfo(User user, Integer pageNo, Integer pageSize){
		Result res = new Result();
		//默认注册的正常用户
		if(null == user.getSource()) user.setSource(0);
		if(null == user.getStatus()) user.setStatus(0);
		res.setData(userService.getUserInfo(user, pageNo, pageSize));
		return res;
	}
	
	
	
}
