package cn.myapps.runtime.rest.user.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.alibaba.fastjson.JSONObject;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;

import cn.myapps.common.controller.Resource;
import cn.myapps.runtime.rest.common.controller.AbstractRESTController;
import cn.myapps.runtime.rest.user.model.User;
import cn.myapps.runtime.rest.user.service.UserService;
import net.sf.json.JSONArray;

@Controller(value="bpmUserController")
@RequestMapping(path = "/rest/bpm/user")
public class UserController extends AbstractRESTController {

	@Autowired
	@Qualifier("bpmUserService")
	UserService service;
	
	/**
	 * 新增用户
	 * @param accessToken
	 * @param postBody
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/save")
	@ResponseStatus(HttpStatus.OK)
	public Resource save(@RequestParam String accessToken, @RequestBody String postBody) throws Exception {
		User user = parseUser(postBody);
		String response = service.add(user);
		return success("created", response);
	}
	
	/**
	 * 通过用户账号获取用户信息
	 * @param accessToken
	 * @param postBody
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/find")
	@ResponseStatus(HttpStatus.OK)
	public Resource find(@RequestParam String accessToken, @RequestBody String postBody) throws Exception {
		DocumentContext parse = JsonPath.parse(postBody, configuration);
		String account = parse.read("$.account");
		User user = service.find(account);
		JSONObject userJSON = new JSONObject();
		userJSON.put("UserInfo", user);
		return success("ok", userJSON);
	}
	
	/**
	 * 更新用户信息
	 * @param accessToken
	 * @param postBody
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/update")
	@ResponseStatus(HttpStatus.OK)
	public Resource update(@RequestParam String accessToken, @RequestBody String postBody) throws Exception {
		JSONObject jsonObject=JSONObject.parseObject(postBody);
		String response = service.update(jsonObject);
		return success("ok", response);
	}
	
	/**
	 * 删除用户
	 * @param accessToken
	 * @param postBody
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/delete")
	@ResponseStatus(HttpStatus.OK)
	public Resource delete(@RequestParam String accessToken, @RequestBody String postBody) throws Exception {
		DocumentContext parse = JsonPath.parse(postBody, configuration);
		String account = parse.read("$.account");
		String response = service.delete(account);
		return success("ok", response);
	}
}
