package com.cab.controller;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.cab.model.User;
import com.cab.service.UserService;
import com.cab.service.UserServiceImpl;
import com.cku.core.RESTResponse;
import com.cku.upyun.ImageFtp;
import com.cku.util.ServletUtils;

@Controller
@RequestMapping(value = "user")
public class UserController {
	// private static final Logger logger =
	// Logger.getLogger(ProvinceController.class);

	@Autowired
	public UserServiceImpl userService;

	@RequestMapping(value = "/login")
	public void api_login(HttpServletResponse response,
			HttpServletRequest request) throws IOException {
		RESTResponse result = null;
		try {
			String username = ServletUtils.getParameter(request, "username");
			String password = ServletUtils.getParameter(request, "password");
			String dynamic = ServletUtils.getParameter(request, "dynamic");

			User um = userService.login(username, password, dynamic);
			result = new RESTResponse("user", um);
		} catch (Exception e) {
			result = new RESTResponse(e);
		}

		ServletUtils.writeResponse(response, result);
	}

	@RequestMapping(value = "/register")
	public void api_register(HttpServletResponse response,
			HttpServletRequest request) throws IOException {
		RESTResponse result = null;
		try {
			String username = ServletUtils.getParameter(request, "username");
			String password = ServletUtils.getParameter(request, "password");
			String validation_code = ServletUtils.getParameter(request,"validation_code");
			String phone = ServletUtils.getParameter(request, "phone");
			String name = ServletUtils.getParameter(request, "name");
			String realname = ServletUtils.getParameter(request, "real_name",null);
			
			String ip = request.getRemoteAddr();

			User um = userService.register(username, password, phone,validation_code, ip, name,realname);
			result = new RESTResponse("user", um);
		} catch (Exception e) {
			result = new RESTResponse(e);
		}

		ServletUtils.writeResponse(response, result);
	}

	@RequestMapping(value = "/modify-password")
	public void api_modify_password(HttpServletResponse response,
			HttpServletRequest request) throws IOException {
		RESTResponse result = null;
		try {
			String username = ServletUtils.getParameter(request, "username");
			String old_password = ServletUtils.getParameter(request,"old_password");
			String new_password = ServletUtils.getParameter(request,"new_password");

			userService.modifyPassword(username, old_password, new_password);
			result = new RESTResponse();
		} catch (Exception e) {
			result = new RESTResponse(e);
		}

		ServletUtils.writeResponse(response, result);
	}

	// 修改用户头像
	@RequestMapping(value = "/update_avatar")
	public void api_update_avater(HttpServletResponse response,HttpServletRequest request,
			@RequestParam(value = "file", required = false) MultipartFile file)throws Exception {
		RESTResponse result = null;
		Long userId = UserService.verifyUserId(request);
		String fileName = file.getOriginalFilename();
		int lastIndex = fileName.lastIndexOf(".");
		String fileNameEnd = fileName.substring(lastIndex);
		String newFileName = UUID.randomUUID()+fileNameEnd;
		String resultOra = "";
		try {
			 resultOra = ImageFtp.uploadBytes(ImageFtp.AVATAR_PATH_TEST, newFileName, file.getBytes());
			 int user = userService.updateAvatar(userId,resultOra);
			 if(user>0){
				 result = new RESTResponse("items", resultOra);				 
			 }else{
				 resultOra = "";
				 result = new RESTResponse(-1,"上传头像失败");				 
			 }
			 
		} catch (IOException e) {
			e.printStackTrace();
		}
		ServletUtils.writeResponse(response, result);

	}

	@RequestMapping(value = "/reset-password")
	public void api_reset_password(HttpServletResponse response,
			HttpServletRequest request) throws IOException {
		RESTResponse result = null;
		try {
			String username = ServletUtils.getParameter(request, "username");
			String password = ServletUtils.getParameter(request, "password");
			String validation_code = ServletUtils.getParameter(request,
					"validation_code");
			String phone = ServletUtils.getParameter(request, "phone");

			userService.resetPassword(username, password, phone,
					validation_code);
			result = new RESTResponse();
		} catch (Exception e) {
			result = new RESTResponse(e);
		}

		ServletUtils.writeResponse(response, result);
	}

	@RequestMapping(value = "/modify-info")
	public void api_modify_info(HttpServletResponse response,
			HttpServletRequest request) throws IOException {
		RESTResponse result = null;
		try {
			Long userId = UserService.verifyUserId(request);
			String name = ServletUtils.getParameter(request, "name", null);
			Integer is_female = ServletUtils.getParameterInt(request,"is_female", null);
			String age = ServletUtils.getParameter(request, "age", null);
			Integer province_id = ServletUtils.getParameterInt(request, "province_id",null);
			Integer city_id = ServletUtils.getParameterInt(request, "city_id",null);
			Integer area_id = ServletUtils.getParameterInt(request, "area_id",null);
			String realName = ServletUtils.getParameter(request, "realName", null);					
			userService.updateInfo(userId, name, is_female, age,province_id,city_id, area_id,realName);
			
			result = new RESTResponse();
		} catch (Exception e) {
			result = new RESTResponse(e);
		}

		ServletUtils.writeResponse(response, result);
	}
	
	/**
	 * 
	 * @Description：验证验证码并生成随机码（设置支付密码）
	 * @author: zhuoHeng
	 * @version: 2016年4月27日 上午9:35:46
	 */
	@RequestMapping(value="/validateIdentities")
	public void validateIdentities(HttpServletResponse response,HttpServletRequest request) throws IOException{
		RESTResponse result = null;
		try {
			Long userId = UserService.verifyUserId(request);
			String validation_code = ServletUtils.getParameter(request,"validation_code");	
			String uuid = userService.validateIdentities(userId,validation_code);
			
			result = new RESTResponse("uuid",uuid);
		} catch (Exception e) {
			result = new RESTResponse(e);
		}

		ServletUtils.writeResponse(response, result);
	}
	
	/**
	 * 
	 * @Description：验证身份证号并设置支付密码（设置支付密码）
	 * @author: zhuoHeng
	 * @version: 2016年4月28日 上午11:50:21
	 */
	@RequestMapping(value="/setPayPassWord")
	public void setPayPassWord(HttpServletResponse response,HttpServletRequest request) throws IOException{
		RESTResponse result = null;
		try {
			Long userId = UserService.verifyUserId(request);
			String cardId = ServletUtils.getParameter(request,"cardId");	
			String uuid = ServletUtils.getParameter(request,"uuid");
			String payPsw = ServletUtils.getParameter(request,"payPsw");
			userService.setPayPassWord(userId,cardId,uuid,payPsw);
			
			result = new RESTResponse();
		} catch (Exception e) {
			result = new RESTResponse(e);
		}

		ServletUtils.writeResponse(response, result);
	}
	/**
	 * 
	 * @Description：修改支付密码
	 * @author: zhuoHeng
	 * @version: 2016年4月28日 下午2:55:24
	 */
	@RequestMapping(value="/updatePayPassWord")
	public void updatePayPassWord(HttpServletResponse response,HttpServletRequest request) throws IOException{
		RESTResponse result = null;
		try {
			Long userId = UserService.verifyUserId(request);
			String uuid = ServletUtils.getParameter(request,"uuid");
			String old_password = ServletUtils.getParameter(request,"old_password");
			String new_password = ServletUtils.getParameter(request,"new_password");
			userService.updatePayPassWord(userId,old_password,new_password,uuid);
			
			result = new RESTResponse();
		} catch (Exception e) {
			result = new RESTResponse(e);
		}

		ServletUtils.writeResponse(response, result);
	}
	
	/**
	 * 
	 * @Description：验证支付密码
	 * @author: zhuoHeng
	 * @version: 2016年4月28日 下午3:23:17
	 */
	@RequestMapping(value = "/validatePayPassWord")
	public void validatePayPassWord(HttpServletResponse response,HttpServletRequest request) throws IOException{
		RESTResponse result = null;
		try {
			Long userId = UserService.verifyUserId(request);
			String payPsw = ServletUtils.getParameter(request,"payPsw");
			String dynamic = ServletUtils.getParameter(request,"dynamic");
			userService.validatePayPassWord(userId,payPsw,dynamic);
			
			result = new RESTResponse();
		} catch (Exception e) {
			result = new RESTResponse(e);
		}

		ServletUtils.writeResponse(response, result);
	}
}
