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.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.CertifySubmitType;
import com.goafanti.common.enums.IdentityAuditStatus;
import com.goafanti.common.enums.IdentityProcess;
import com.goafanti.common.enums.UserFields;
import com.goafanti.common.enums.UserIdentityFields;
import com.goafanti.common.enums.UserLevel;
import com.goafanti.common.enums.UserType;
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.InputUser;
import com.goafanti.user.bo.InputUserIdentity;
import com.goafanti.user.service.OrgHumanResourceService;
import com.goafanti.user.service.OrganizationIdentityService;
import com.goafanti.user.service.UserAbilityService;
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
	private OrgHumanResourceService			orgHumanResourceService;

	@Resource
	private UserAbilityService				userAbilityService;
	@Resource(name = "passwordUtil")
	private PasswordUtil					passwordUtil;
	@Resource
	private AdminService					adminService;
	@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 = "/customer", method = RequestMethod.GET)
	public Result getCustomer(Integer number, String mobile, Integer auditStatus, String auditName, String email,
			String startCreateTime, String endCreateTime, Integer type, String pageNo, String pageSize) {
		Result res = new Result();
		if (null == type) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "用户类型", "用户类型"));
			return res;
		}
		if (!UserType.PERSONAL.getCode().equals(type) && !UserType.ORGANIZATION.getCode().equals(type)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "用户类型", "用户类型"));
			return res;
		}
		Integer pNo = 1;
		Integer pSize = 10;
		if (StringUtils.isNumeric(pageSize)) {
			pSize = Integer.parseInt(pageSize);
		}
		if (StringUtils.isNumeric(pageNo)) {
			pNo = Integer.parseInt(pageNo);
		}
		res.setData(userService.selectUserByAid(number, mobile, auditStatus, auditName, email,
				TokenManager.getAdminId(), startCreateTime, endCreateTime, type, pNo, pSize));
		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 = "/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;
		}

		if (null == inputUser.getType()) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "type", "type"));
			return res;
		}

		User user = userService.selectByMobieAndType(inputUser.getMobile().trim(), inputUser.getType());
		if (null != user) {
			res.getError().add(buildError(ErrorConstants.USER_ALREADY_EXIST, "当前用户已注册！"));
			return res;
		}

		if (UserType.ORGANIZATION.getCode().equals(inputUser.getType())
				&& StringUtils.isBlank(inputUser.getUnitName())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "公司名称", "公司名称"));
			return res;
		}

		if (UserType.PERSONAL.getCode().equals(inputUser.getType()) && StringUtils.isBlank(inputUser.getUsername())) {
			res.getError().add(buildError(ErrorConstants.PARAM_EMPTY_ERROR, "用户名称", "用户名称"));
			return res;
		}

		User u = new User();
		u.setId(UUID.randomUUID().toString());
		u.setMobile(inputUser.getMobile().trim());
		u.setPassword(inputUser.getMobile().trim());
		u.setType(inputUser.getType());
		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 = "/getAdminRoleList", method = RequestMethod.GET)
	public Result getAdminRoleList(String roleName){
		Result res = new Result();
		if( StringUtils.isBlank(roleName)){
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "角色名称必须指定"));
			return res;
		}
		res.setData(adminService.getAdminRoleList( roleName));
		return res;
	}

	/**
	 * 锁定密码未更改的用户
	 */
	@RequestMapping(value = "/lockAdmin", method = RequestMethod.POST)
	public Result updateLockAdmin() {
		Result res = new Result();
		res.setData(adminService.updateLockAdmin());
		return res;
	}
	/**
	 * 新建常用联系人
	 */
	@RequestMapping(value = "/addFrequentContacts", method = RequestMethod.POST)
	public Result addFrequentContacts(String id) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "常用联系人"));
			return res;
		}
		res.setData(adminService.addFrequentContacts(id));
		return res;
	}
	/**
	 * 常用联系人列表
	 */
	@RequestMapping(value = "/frequentContactsList", method = RequestMethod.GET)
	public Result frequentContactsList(String departmentId,String name,String roleName,Integer pageSize,Integer pageNo) {
		Result res = new Result();
		res.setData(adminService.frequentContactsList(departmentId, name,roleName, pageSize, pageNo));
		return res;
	}
	/**
	 * 删除常用联系人
	 */
	@RequestMapping(value = "/deleteFrequentContacts", method = RequestMethod.POST)
	public Result deleteFrequentContacts(String id) {
		Result res = new Result();
		if (StringUtils.isBlank(id)) {
			res.getError().add(buildError(ErrorConstants.PARAM_ERROR, "", "常用联系人"));
			return res;
		}
		res.setData(adminService.deleteFrequentContacts(id));
		return res;
	}
	
}
