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

import java.io.IOException;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.wisedu.coeus.core.ConstantStatic;
import com.wisedu.coeus.core.bo.LoginUser;
import com.wisedu.coeus.util.MessageUtils;
import com.wisedu.coeus.util.SecurityUtils;
import com.wisedu.coeus.util.Strings;
import com.wisedu.coeus.util.json.JSONObject;
import com.wisedu.coeus.web.LoginContext;
import com.wisedu.mooc.app.platform.bo.Unit;
import com.wisedu.mooc.app.platform.bo.UnitItem;
import com.wisedu.mooc.app.platform.service.UnitItemService;
import com.wisedu.mooc.app.study.bo.UserStudy;
import com.wisedu.mooc.app.study.service.UserStudyService;
import com.wisedu.mooc.app.user.bo.UserInfo;
import com.wisedu.mooc.app.user.service.UserInfoService;

@Controller
@RequestMapping(value = "/portal")
public class PortalController {

    @Autowired
    private UnitItemService unitItemService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserStudyService userStudyService;

    /**
     * 我的课程页面，获取课程章列表
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/mycourse/index", method = RequestMethod.GET)
    public String myCourseIndex(ModelMap model, HttpServletRequest request) {
        Long userId = LoginContext.getLoginUser().getUserInfo().getUserId();
        UserInfo userInfo = this.userInfoService.queryUserInfo(userId);
        //课程章列表
        List<Map<String, Object>> unitList = this.unitItemService.queryStudyUnit(userId);
        Long lastUnitId = null;
        if (unitList != null && unitList.size() > 0) {//默认加载第一周的课件
            lastUnitId = ((Unit) unitList.get(0).get("unit")).getUnitId();
        }
        if (userInfo.getLastItemId() != null && userInfo.getLastItemId().compareTo(0L) > 0) {
        	//获取上次学习记录，若存在学习记录加载上一次学习的章节课件
            UnitItem lastItem = unitItemService.queryUnitItemById(userInfo.getLastItemId());
            if (lastItem!=null){
            	lastUnitId = lastItem.getUnitId();
            }
        }
        model.put("unitList", unitList);
        model.put("lastUnitId", lastUnitId);
        return "portal.mycourse.index";
    }

    /**
     * 获取课件列表
     */
    @RequestMapping(value = "/mycourse/item/list", method = RequestMethod.POST)
    public String myCourseUnit(@RequestParam Long unitId, ModelMap model) {
        LoginUser loginUser = LoginContext.getLoginUser();
        Long userId = loginUser.getUserInfo().getUserId();
        Unit unit = this.unitItemService.queryUnitById(unitId);
        List<UnitItem> itemList = this.unitItemService.queryItemList(unitId);
        //课件学习记录
        List<UserStudy> studyList = this.userStudyService.queryUserStudy(unitId, UserStudy.IS_OVER_YES, userId);
        //计算学习进度
        if (itemList.size() == 0) {
            unit.setProgress(0);
        } else {
            unit.setProgress(studyList.size() * 100 / itemList.size());
        }
        Map<Long, UserStudy> studyMap = new HashMap<Long, UserStudy>();
        for (UserStudy study : studyList) {
            studyMap.put(study.getItemId(), study);
        }
        List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
        for (UnitItem item : itemList) {//判断每一个课件是否学完
            if (item.getUnitId().compareTo(unit.getUnitId()) == 0) {
                Map<String, Object> itemMap = new HashMap<String, Object>();
                itemMap.put("item", item);
                itemMap.put("study", studyMap.get(item.getItemId()));
                items.add(itemMap);
            }
        }
        model.put("itemList", items);
        model.put("unit", unit);
        return "portal.mycourse.item";
    }

    /**
     * 进入个人设置页面
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/setting", method = RequestMethod.GET)
    public String initSetting(Model model, HttpServletRequest request) {
        Long userId = LoginContext.getLoginUser().getUserInfo().getUserId();
        UserInfo userInfo = this.userInfoService.queryUserInfo(userId);
        model.addAttribute("userInfo", userInfo);
        return "portal.settingIndex";
    }

    /**
     * 个人资料---基本信息
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/basicinfo", method = RequestMethod.POST)
    public String initUserInfo(Model model, HttpServletRequest request) {
        Long userId = LoginContext.getLoginUser().getUserInfo().getUserId();
        UserInfo userInfo = this.userInfoService.queryUserInfo(userId);
        model.addAttribute("host", ConstantStatic.getResourceDomainUrl());
        model.addAttribute("userInfo", userInfo);
        return "portal.basicInfoSet";
    }

    /**
     * 密码设置页面
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/password", method = RequestMethod.POST)
    public String passwordSet(Model model, HttpServletRequest request) {
        Long userId = LoginContext.getLoginUser().getUserInfo().getUserId();
        UserInfo userInfo = this.userInfoService.queryUserInfo(userId);
        model.addAttribute("userInfo", userInfo);
        return "portal.passwordSet";
    }

    /**
     * 更新用户密码
     *
     * @param oldPass
     * @param newPass
     * @param newPass2
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/save/password", method = RequestMethod.POST)
    public String updatePassword(@RequestParam String oldPass, @RequestParam String newPass,
                                 @RequestParam String newPass2, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Long userId = LoginContext.getLoginUser().getUserInfo().getUserId();
        UserInfo userInfo = this.userInfoService.queryUserInfo(userId);
        Map<String, Object> results = new HashMap<String, Object>();
        if (!userInfo.getPassword().equalsIgnoreCase(oldPass)) {
            results.put("errorMsg", MessageUtils.getMessage("userSet.password.current.error"));
            response.getWriter().print(JSONObject.toJSONString(results));
            return null;
        }
        if (Strings.isEmpty(newPass)) {
            results.put("errorMsg", MessageUtils.getMessage("userSet.password.new.empty"));
            response.getWriter().print(JSONObject.toJSONString(results));
            return null;
        }
        if (!newPass.equals(newPass2)) {
            results.put("errorMsg", MessageUtils.getMessage("userSet.password.not.same"));
            response.getWriter().print(JSONObject.toJSONString(results));
            return null;
        }
        userInfo.setPassword(SecurityUtils.hashMD5(newPass).toLowerCase());

        this.userInfoService.updateUserInfo(userInfo);
        LoginContext.getLoginUser().setUserInfo(userInfo);
        response.getWriter().print(JSONObject.toJSONString(results));
        return null;
    }
}
