package com.palmnest.webapp.controller.app;

import com.palmnest.application.AppConstants;
import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.FileUploadUtils;
import com.palmnest.application.core.util.NumberUtils;
import com.palmnest.application.core.util.RegularPattern;
import com.palmnest.application.dto.AppServiceMenuDto;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.SmsAuthCode;
import com.palmnest.service.AppMenuService;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.ServiceProjectAllocationManager;
import com.palmnest.service.estateserve.SmsAuthCodeManager;
import com.palmnest.service.redis.BaseRedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("/appuser/user")
public class SuperUserController {


	@Autowired
	private AppUserManager                  appUserManager;
	@Autowired
	private PasswordEncoder                 passwordEncoder;
	@Autowired
	private BaseRedisService                baseRedisService;
	@Autowired
	private AppMenuService                  appMenuService;
	@Autowired
	private SmsAuthCodeManager              smsAuthCodeManager;
	@Autowired
	private ServiceProjectAllocationManager serviceProjectAllocationManager;
	@Autowired
	private OrganizationManager             organizationManager;

	private long time = 60 * 60 * 24 * 7;//7天有效

	/**
	 * 获取验证码接口
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/getAuthCode")
	@ResponseBody
	public AppResultDto authCode(@RequestParam String telephone) {
		if (StringUtils.isBlank(telephone) || !RegularPattern.isMobileNO(telephone)) {
			return AppResultUtil.createErrorDto(AppConstants.PHONE_VALIDATE_ERROR, "请输入有效电话号码");
		}
		String code    = NumberUtils.getValidateCode();
		String content = "您的验证码为" + code + "，15分钟内有效，如非本人操作，请忽略。 【中航超级前台】";
		//发送短信
		String result = smsAuthCodeManager.sendSms(telephone, content);
		if ("Sucess".equals(result.trim())) {
			SmsAuthCode model = new SmsAuthCode();
			model.setCode(code);
			model.setUserMobile(telephone);
			model.setType("1");
			model.setCreateTime(new Date());
			model.setIsEnabled(ElementConstant.YESORNO_1);
			smsAuthCodeManager.saveModel(model);

			return AppResultUtil.createSuccesDto();
		}
		return AppResultUtil.createErrorDto(AppConstants.GET_CODE_ERROR, "获取验证码失败");
	}

	/**
	 * 用户注册
	 *
	 * @param telephone
	 * @param authCode
	 * @param password
	 * @param deviceType
	 * @param deviceNo
	 * @return
	 */
	@RequestMapping("/register")
	@ResponseBody
	public AppResultDto register(String telephone, String authCode, String password, Integer deviceType, @RequestParam(required = false) String deviceNo) {

		log.info("telephone:" + telephone);
		if (StringUtils.isEmpty(telephone) || StringUtils.isEmpty(authCode)
				|| StringUtils.isEmpty(password) || !RegularPattern.isMobileNO(telephone)) {
			return AppResultUtil.createErrorDto(AppConstants.USER_NAME_OR_PASSWORD_NULL, "请正确填写信息");
		}
		SmsAuthCode smsAuthCode = smsAuthCodeManager.getSmsAuthCode(telephone, authCode, "1", 15);
		if (smsAuthCode == null) {
			return AppResultUtil.createErrorDto(AppConstants.AUTH_CODE_ERROR, "验证码不正确");
		}
		AppUser user = appUserManager.getAppUsersByPhone(telephone);
		//根据电话号码登录
		if (user != null && (user.getIsEnabled() == null || user.getIsEnabled().equals("1"))) {
			return AppResultUtil.createErrorDto(AppConstants.PHONE_USER_EXIST, "手机号对应用户已存在，请登录");
		}

		user = new AppUser();
		user.setUserMobile(telephone);
		user.setUserType("1");//APP
		user.setPassword(passwordEncoder.encodePassword(password, null));
		user.setRoleType("1");
		user.setOrganizationId(10);//TODO 选择企业
		user.setDeviceType(deviceType);
		user.setDeviceNo(deviceNo);
		user.setIsEnabled("1");
		appUserManager.save(user);
//		String token = JwtUtil.getToken(userName);
//		baseRedisService.set(user.getUsername(), token,time );
//		baseRedisService.set(token, user.getUsername(), time);
		//UserDto dto = userManager.convertDto(user);
//		dto.setToken(token);
		return AppResultUtil.createSuccesDto();
	}

	@RequestMapping("/login")
	@ResponseBody
	public AppResultDto login(String telephone, String password, Integer deviceType, @RequestParam(required = false) String deviceNo) {
		if (StringUtils.isEmpty(telephone) || StringUtils.isEmpty(password)) {
			return AppResultUtil.createErrorDto(AppConstants.USER_NAME_OR_PASSWORD_NULL, "电话号码或密码为空");
		}
		System.out.println("登录接口----start");
		System.out.println("参数----telephone：" + telephone);
		System.out.println("参数----password：" + password);
		System.out.println("参数----deviceType：" + deviceType);
		//根据电话号码登录
		AppUser user = appUserManager.getAppUsersByPhone(telephone);
		//电话号码查询不到就用账号查询
//		if(user == null) {
//			user = userManager.getUserByUsername2(telephone);
//		}
		if (user == null) {
			return AppResultUtil.createErrorDto(AppConstants.USER_NOT_EXIST, "用户不存在");
		}
		System.out.println("用户密码：" + password + " 加密后：" + passwordEncoder.encodePassword(password, null));
		if (!passwordEncoder.encodePassword(password, null).equals(user.getPassword())) {
			return AppResultUtil.createErrorDto(AppConstants.PASSWORD_ERROR, "密码错误");
		}
		user.setDeviceType(deviceType);
		user.setDeviceNo(deviceNo);
		appUserManager.save(user);
//		String token = JwtUtil.getToken(userName);
//		baseRedisService.set(user.getUsername(), token,time );
//		baseRedisService.set(token, user.getUsername(), time);
//		dto.setToken(token);
		return AppResultUtil.createSuccesDto(appUserManager.convertToAppDto(user));
	}

	@RequestMapping("/getUserById")
	@ResponseBody
	public AppResultDto getUserById(Integer userId) {
		if (userId == null) {
			AppResultUtil.createErrorDto(AppConstants.QUERY_USER_ERROR, "传入参数为空");
		}

		try {
			AppUser user = appUserManager.get(userId);
			if (user == null) {
				return AppResultUtil.createErrorDto(AppConstants.USER_NOT_EXIST, "用户不存在");
			}
			return AppResultUtil.createSuccesDto(appUserManager.convertToAppDto(user));
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.QUERY_USER_ERROR, "查询用户信息失败");
		}
	}

	@RequestMapping("/serviceMenuList")
	@ResponseBody
	public AppResultDto menuList(HttpServletRequest request) {
//		String userName = baseRedisService.get(request.getHeader("token"));
//		if(userName == null) {
//			AppResultDto rt = AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
//   		 	return rt;
//		}
		Integer organizationId = Integer.parseInt(request.getParameter("organizationId"));
		try {
			List<AppServiceMenuDto> services = serviceProjectAllocationManager.getServiceProjectAllocationList(organizationId, 0);
//			List<MenuDto> dtos = appMenuService.findMenuDto(userName);
			return AppResultUtil.createSuccesDto(services);
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.SERVICE_MENU_ERROR, "查询服务菜单失败");
		}
	}


	@RequestMapping("/uploadPhoto")
	@ResponseBody
	public AppResultDto uploadPhoto(Integer userId, MultipartHttpServletRequest request) {

//		String userName = baseRedisService.get(request.getHeader("token"));
//		if(userName == null) {
//			AppResultDto rt = AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
//   		 	return rt;
//		}

		MultipartFile file = request.getFile("file");
		if (file == null) {
			return AppResultUtil.createErrorDto(AppConstants.UPLOAD_PHOTO_ERROR, "请选择头像");
		}

		// 获得文件原始名称
		try {

			InputStream stream   = null;
			String      fileExt  = null;
			String      fileName = "";
			if (file != null) {
				stream = file.getInputStream();
				fileName = file.getOriginalFilename();
				fileName = new String(fileName.getBytes(), "utf-8");
				fileExt = StringUtils.isNotEmpty(fileName) ? fileName
						.substring(fileName.lastIndexOf("."))
						: StringUtils.EMPTY;
			}

			FileUploadUtils fileUploadUtils = new FileUploadUtils();
			fileUploadUtils.init();
			String  url       = fileUploadUtils.uploadFile(stream, fileExt);
			String  picUrl    = fileUploadUtils.fullVisitPath(url);
			AppUser user      = appUserManager.get(userId);
			String  oldPicUrl = user.getUserPhotoUrl();
			user.setUserPhotoUrl(picUrl);
			appUserManager.updateModel(user);
			//删除原来的头像
			if (oldPicUrl != null && !oldPicUrl.equals("")) {
				FileUploadUtils.deleteFileByPath(oldPicUrl);
			}
			return AppResultUtil.createSuccesDto(picUrl);
		} catch (IOException e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.UPLOAD_PHOTO_ERROR, "上传头像失败");
		}
	}

	@RequestMapping("/modifyPassword")
	@ResponseBody
	public AppResultDto modifyPassword(Integer userId, String oldPwd, String newPwd) {

		//修改密码
		try {
			if (StringUtils.isBlank(oldPwd)) {
				return AppResultUtil.createErrorDto(AppConstants.MODIFY_PWD_ERROR, "请输入原始密码");
			}
			if (StringUtils.isBlank(newPwd)) {
				return AppResultUtil.createErrorDto(AppConstants.MODIFY_PWD_ERROR, "请输入新密码");
			}
			AppUser user = appUserManager.get(userId);
			if (user == null) {
				return AppResultUtil.createErrorDto(AppConstants.REST_PASSWORD_ERROR, "电话号码对应的用户不存在");
			}
			System.out.println("用户原密码:" + user.getPassword());
			if (!passwordEncoder.encodePassword(oldPwd, null).equals(user.getPassword())) {
				return AppResultUtil.createErrorDto(AppConstants.MODIFY_PWD_ERROR, "密码修改失败，原始密码错误，请检查.");
			}
			boolean retFlag = appUserManager.updateUserPwd(user.getUserMobile(), newPwd);
			if (retFlag) {
				System.out.println("修改密码成功");
				return AppResultUtil.createSuccesDto(appUserManager.convertToAppDto(user));
			} else {
				return AppResultUtil.createErrorDto(AppConstants.MODIFY_PWD_ERROR, "密码修改失败，原始密码错误，请检查.");
			}

		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.MODIFY_PWD_ERROR, "修改密码失败");
		}
	}

	@RequestMapping("/modifyTelephone")
	@ResponseBody
	public AppResultDto modifyTelephone(Integer userId, String telephone) {
		try {
			AppUser user = appUserManager.get(userId);
			if (user == null) {
				return AppResultUtil.createErrorDto(AppConstants.UPDATE_PHONE_ERROR, "用户不存在");
			}
			if (StringUtils.isBlank(telephone) || !RegularPattern.isMobileNO(telephone)) {
				return AppResultUtil.createErrorDto(AppConstants.PHONE_VALIDATE_ERROR, "请输入有效电话号码");
			}
			user.setUserMobile(telephone);
			appUserManager.updateModel(user);
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.UPDATE_PHONE_ERROR, "修改密码失败");
		}
	}


	@RequestMapping("/loginOut")
	@ResponseBody
	public AppResultDto loginOut(Integer userId) {
		try {
			//机器码清空
			AppUser user = appUserManager.get(userId);
			user.setDeviceNo(null);
			user.setDeviceType(null);
			appUserManager.updateModel(user);
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.LOGIN_OUT_ERROR, "退出登录失败");
		}
	}


	@RequestMapping("/resetPassword")
	@ResponseBody
	public AppResultDto resetPassword(String telephone, String authCode, String newPwd) {

		//重置密码
		try {
			if (StringUtils.isBlank(authCode)) {
				return AppResultUtil.createErrorDto(AppConstants.REST_PASSWORD_ERROR, "请输入验证码");
			}

			if (StringUtils.isBlank(newPwd)) {
				return AppResultUtil.createErrorDto(AppConstants.REST_PASSWORD_ERROR, "请输入新密码");
			}

			SmsAuthCode smsAuthCode = smsAuthCodeManager.getSmsAuthCode(telephone, authCode, "1", 15);
			if (smsAuthCode == null) {
				return AppResultUtil.createErrorDto(AppConstants.AUTH_CODE_ERROR, "验证码不正确");
			}

			AppUser user = appUserManager.getAppUsersByPhone(telephone);
			if (user == null) {
				return AppResultUtil.createErrorDto(AppConstants.REST_PASSWORD_ERROR, "电话号码对应的用户不存在");
			}

			boolean retFlag = appUserManager.updateUserPwd(telephone, newPwd);
			if (retFlag) {
				return AppResultUtil.createSuccesDto(appUserManager.convertToAppDto(user));
			} else {
				return AppResultUtil.createErrorDto(AppConstants.REST_PASSWORD_ERROR, "重置密码失败");
			}

		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.REST_PASSWORD_ERROR, "重置密码失败");
		}
	}

	/**
	 * 更新机器码
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/updateDeviceNo")
	@ResponseBody
	public AppResultDto updateDeviceNo(Integer userId, Integer deviceType, @RequestParam(required = false) String deviceNo) {
		try {
			AppUser user = appUserManager.get(userId);
			user.setDeviceType(deviceType);
			user.setDeviceNo(deviceNo);
			;
			appUserManager.updateModel(user);
			return AppResultUtil.createSuccesDto(appUserManager.convertToAppDto(user));
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.UPDATE_DEVICENO_ERROR, "更新设备码失败");
		}
	}


	@RequestMapping("/organizationList")
	@ResponseBody
	public AppResultDto organizationList(Integer userId) {
		try {
			return AppResultUtil.createSuccesDto(organizationManager.findAll());
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createErrorDto(AppConstants.OGR_LIST_ERROR, "查询项目列表失败");
		}
	}

}
