 package com.dbs.mplus.controller.admin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerMapping;

import com.dbs.mplus.exception.admin.AdminControllerException;
import com.dbs.mplus.exception.mobile.MobileControllerException;
import com.dbs.mplus.framework.exception.MPlusServiceException;
import com.dbs.mplus.framework.service.admin.userAttr.UserAttrService;
import com.dbs.mplus.framework.service.admin.userAttr.repository.dao.UserAttr;

/**
 * 사용자 속성 관리 화면 
 * @author 
 *
 */
@Controller
@RequestMapping("/admin/userAttr")
public class UserAttrController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserAttrService userAttrService;

	@RequestMapping(value = "/view.page", method = RequestMethod.GET)
	public Model user(Model model) throws AdminControllerException {
		return model; 
	}
	
	// 전체 사용자 리스트 (+속성정보)
	// 속성정보가 복수이면 동일한 사용자가 복수로 나옴
	@RequestMapping(value="/getList.json", method = RequestMethod.POST)
	@ResponseBody 
	public Map<String, Object> getUserList(@RequestBody Map<String, Object> map) throws AdminControllerException {
		try {
			if(this.logger.isDebugEnabled()) { 
				this.logger.debug("사용자 속성 관리 리스트 요청");
			} 
			final String searchText = (String)map.get("searchText");
			final String selectUserType = (String)map.get("selectUserType");
			
			if(searchText != null && !searchText.isEmpty()) {
				if(selectUserType.equals("userId")) {
					map.put("userId", searchText);
				}
				else if(selectUserType.equals("userName")) {
					map.put("userName", searchText);
				}
			}
			
			List<Map<String, Object>> sortList = new ArrayList<Map<String, Object>>();
			Map<String, Object> sortItem = new HashMap<String, Object>();
			sortItem.put("field", "registerDt");
			sortItem.put("dir", "desc");
			
			sortList.add(sortItem);
			map.put("sort", sortList);
			
			return this.userAttrService.findListByAttrCondiction(map);
		}
		catch(final MPlusServiceException ex) {
			throw new AdminControllerException(ex); 
		}
	}
	
	// 특정 사용자의 속성 리스트를 리턴
	@RequestMapping(value="/getUserAttrList.json", method = RequestMethod.POST)
	@ResponseBody 
	public List<UserAttr> getUserAttrList(@RequestBody UserAttr userAttr) throws AdminControllerException {
		try {
			if(this.logger.isDebugEnabled()) { 
				this.logger.debug("사용자 속성 리스트 요청");
			} 

			return this.userAttrService.findUserAttrList(userAttr);
		}
		catch(final MPlusServiceException ex) {
			throw new AdminControllerException(ex); 
		}
	}

	@RequestMapping(value = "/save.json", method = RequestMethod.POST)
	@ResponseBody
	public UserAttr save(@RequestBody UserAttr userAttr) throws AdminControllerException {

		try { 
			this.userAttrService.save(userAttr);;
		}
		catch(final MPlusServiceException ex) {
			this.logger.error("사용자 속성 저장실패. userAttr : " + userAttr, ex);
			throw new AdminControllerException(ex); 
		}
		
		this.logger.debug(userAttr.toString());
		
		return userAttr;
	}

	/**
	 * 
	 * @param userAttr
	 * @throws AdminControllerException
	 */
	@RequestMapping(value = "/remove.json", method = RequestMethod.POST)
	public void remove(@RequestBody UserAttr userAttr) throws AdminControllerException {
		try { 
			//사용자가 선택한 속성
			final Long useAttrOrder = userAttrService.selectUseAttrOrder(userAttr);
			//사용자가 삭제할 속성 순서
			final Long userAttrOrder = userAttr.getUserAttrOrder();
			if(useAttrOrder.equals(userAttrOrder)){
				throw new AdminControllerException("사용자가 선택한 속성입니다.");
			}
			
			this.userAttrService.removeUserAttr(userAttr);
			
			if( useAttrOrder > userAttrOrder ) {
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("userId", userAttr.getUserId());
				param.put("useAttrOrder", useAttrOrder - 1);
				this.userAttrService.modifyUserUseAttrOrder(param);
			}
		}
		catch(final MPlusServiceException ex) { 
			this.logger.error("사용자 속성 삭제실패. userAttr : " + userAttr);
			throw new AdminControllerException(ex); 
		}
		
		this.logger.debug(userAttr.toString());		
	}
	
	/**
	 * 사용자 속성 변경
	 * @param request
	 * @param response
	 * @param paramMap
	 * @throws MobileControllerException
	 */
	@RequestMapping(value = "/changeUserAttr.json", method = RequestMethod.POST) 
	@ResponseBody
	public void changeUserAttr(HttpServletRequest request, HttpServletResponse response, 
			@RequestBody Map<String, Object> paramMap) throws MobileControllerException {
		if(this.logger.isDebugEnabled()) { 
			this.logger.debug("request : " + request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));
		}
		

		userAttrService.modifyUserUseAttrOrder(paramMap);
		
	}

}
