package com.wisedu.mooc.app.user.web;

import com.wisedu.coeus.core.ConstantStatic;
import com.wisedu.coeus.util.Strings;
import com.wisedu.coeus.util.json.JSONObject;
import com.wisedu.coeus.web.LoginContext;
import com.wisedu.mooc.app.upload.service.UploadFactory;
import com.wisedu.mooc.app.upload.service.UploadService;
import com.wisedu.mooc.app.upload.vo.UploadVo;
import com.wisedu.mooc.app.user.UserConstant;
import com.wisedu.mooc.app.user.bo.UserInfo;
import com.wisedu.mooc.app.user.service.UserInfoService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.wisedu.coeus.debug.Logger;
import com.wisedu.coeus.debug.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserInfoController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserInfoController.class);

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 更新用户头像 及 昵称
     *
     * @param uploadVo
     * @param request
     * @param response
     * @throws java.io.IOException
     */
    @RequestMapping(value = "/update/avatar", method = RequestMethod.POST)
    public void upadteHead(UploadVo uploadVo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        UserInfo userInfo = LoginContext.getLoginUser().getUserInfo();
        String nickName = request.getParameter("nickName");
        try {
            if (StringUtils.isNotEmpty(nickName)) {
                userInfo.setNickName(nickName);
            }
            if (!Strings.isEmpty(uploadVo.getFileRelativePath())) {
                UploadService uploadService = UploadFactory.getInstance("usrimg");
                uploadService.uploadEndOperate(uploadVo);
                Map<String, String> map = uploadVo.getUploadMap();
                String parentPath = map.get("parentPath");
                /**设置头像地址 **/
                userInfo.setUseravatar(parentPath);
                
                returnMap.put("userInfo", userInfo);
                returnMap.put("avatarPath", parentPath);
                returnMap.put("result", ConstantStatic.INT_1);
            } else {
                returnMap.put("result", ConstantStatic.INT_2);
            }
            userInfoService.updateUserInfo(userInfo);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
        response.getWriter().print(JSONObject.toJSONString(returnMap));
    }
}
