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

import com.wisedu.coeus.core.ConstantStatic;
import com.wisedu.coeus.core.db.PageMaker;
import com.wisedu.coeus.core.security.LoginCheck;
import com.wisedu.coeus.util.Strings;
import com.wisedu.mooc.app.platform.bo.Unit;
import com.wisedu.mooc.app.platform.bo.UnitItem;
import com.wisedu.mooc.app.platform.service.PlatformService;
import com.wisedu.mooc.app.platform.service.UnitItemService;

import com.wisedu.mooc.app.user.bo.UserInfo;
import com.wisedu.mooc.app.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.wisedu.coeus.debug.Logger;
import com.wisedu.coeus.debug.LoggerFactory;
import com.wisedu.coeus.util.json.JSONObject;

import org.springframework.web.bind.annotation.RequestMethod;

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

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

/**
 * 后台管理层
 */
@Controller
@RequestMapping("/platform")
public class PlatformController {
   
	private static final Logger LOGGER = LoggerFactory.getLogger(PlatformController.class);

    @Autowired
    private PlatformService platformService;

    @Autowired
    private UnitItemService unitItemService;

    @Autowired
    private UserInfoService userInfoService;

    /*************************************后台首页****************************************/
    /**
     * 后台管理-首页引导页
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/admin/index", method = RequestMethod.GET)
    public String backend(HttpServletRequest request, ModelMap model) throws Exception {
        return "platform.backend";
    }

    /************************************课件管理**********************************/
    /**
     * 后台-课件列表
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryunit", method = RequestMethod.GET)
    public String queryunit(HttpServletRequest request, ModelMap model) throws Exception {
        List<Map<String,Object>> mapList = this.platformService.queryunit();
        model.addAttribute("unitList",mapList);
        return "platform.unit";
    }

    /**
     * 保存章信息
     * @param unit
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/unit/doSaveUnit", method = RequestMethod.POST)
    public String insertUnit(Unit unit, HttpServletResponse response) throws IOException {
        String retCode="false";
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            unitItemService.insertUnit(unit);
            retCode="success";
        } catch (Exception e) {
            LOGGER.debug(e.getMessage(), e);
            retCode = e.getMessage();
        }
        returnMap.put("retCode", retCode);
        response.getWriter().print(JSONObject.toJSONString(returnMap));
        response.setContentType(ConstantStatic.HTTP_JSON_CONTENTTYPE);
        return null;
    }

    /**
     * 后台-课件-更新章信息
     * @param unitId 指定的章ID
     * @param unit
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/unit/updateUnit", method = RequestMethod.POST)
    public String editUnit(@RequestParam Long unitId, Unit unit,HttpServletResponse response) throws IOException {
        String retCode="false";
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            unitItemService.updateUnit(unitId, unit);
            retCode="success";
        } catch (Exception e) {
            LOGGER.debug(e.getMessage(), e);
            retCode = e.getMessage();
        }
        returnMap.put("retCode", retCode);
        response.getWriter().print(JSONObject.toJSONString(returnMap));
        response.setContentType(ConstantStatic.HTTP_JSON_CONTENTTYPE);
        return null;
    }

    /**
     * 后台-课件-删除章信息
     * @param unitId 指定的章ID
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/unit/delUnit", method = RequestMethod.POST)
    public String delUnit(@RequestParam Long unitId, HttpServletResponse response) throws IOException {
        String retCode="false";
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            unitItemService.deleteUnit(unitId);
            retCode="success";
        } catch (Exception e) {
            LOGGER.debug(e.getMessage(), e);
            retCode = e.getMessage();
        }
        returnMap.put("retCode", retCode);
        response.getWriter().print(JSONObject.toJSONString(returnMap));
        response.setContentType(ConstantStatic.HTTP_JSON_CONTENTTYPE);
        return null;
    }

    /**
     * 后台-课件-章排序
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/unit/sort", method = RequestMethod.POST)
    public String sort(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String retCode="false";
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            String unitIds = request.getParameter("unitIds");
            String displayOrders = request.getParameter("displayOrders");
            unitItemService.updateUnitSort(unitIds, displayOrders);
            retCode="success";
        } catch (Exception e) {
            LOGGER.debug(e.getMessage(), e);
            retCode = e.getMessage();
        }
        returnMap.put("retCode", retCode);
        response.getWriter().print(JSONObject.toJSONString(returnMap));
        response.setContentType(ConstantStatic.HTTP_JSON_CONTENTTYPE);
        return null;
    }

    /**
     * 后台-课件删除视频
     * @param itemId  条目ID
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/item/delItem", method = RequestMethod.POST)
    public String delItem(@RequestParam Long itemId, HttpServletResponse response) throws IOException {
        String retCode="false";
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            unitItemService.deleteItem(itemId);
            retCode="success";
        } catch (Exception e) {
            LOGGER.debug(e.getMessage(), e);
            retCode = e.getMessage();
        }
        returnMap.put("retCode", retCode);
        response.getWriter().print(JSONObject.toJSONString(returnMap));
        response.setContentType(ConstantStatic.HTTP_JSON_CONTENTTYPE);
        return null;
    }

    /**
     * 后台-课件-视频排序
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/item/sort", method = RequestMethod.POST)
    public String itemSort(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String retCode="false";
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            Long unitId = Strings.getLong(request.getParameter("unitId"));
            Long itemId = Strings.getLong(request.getParameter("itemId"));
            String itemChildIds = request.getParameter("itemChildIds");
            String displayOrders = request.getParameter("displayOrders");
            unitItemService.updateItemSort(unitId,itemId,itemChildIds,displayOrders);
            retCode="success";
        } catch (Exception e) {
            LOGGER.debug(e.getMessage(), e);
            retCode = e.getMessage();
        }
        returnMap.put("retCode", retCode);
        response.getWriter().print(JSONObject.toJSONString(returnMap));
        response.setContentType(ConstantStatic.HTTP_JSON_CONTENTTYPE);
        return null;
    }


    /**
     * 去上传或编辑课件视频
     * 
     * @param unitId
     * @param itemId
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/unit/{unitId}/item", method = RequestMethod.GET)
    public String itemPage(@PathVariable Long unitId,
    		@RequestParam(defaultValue = "0", required = false) Long itemId,
    		HttpServletRequest request, ModelMap model) throws Exception {
    	model.addAttribute("unit",this.unitItemService.queryUnitById(unitId));
    	UnitItem item = this.unitItemService.queryUnitItemById(itemId);
    	model.addAttribute("item",item);
    	model.addAttribute("host",ConstantStatic.getResourceDomain());
    	if(null != item){
    		model.addAttribute("currentVideoFilePath",item.getVideoUrl());
    		model.addAttribute("currentThumbFilePath",item.getVideoPic());
    		model.addAttribute("videoFileName",item.getVideoName());
    	}
        return "platform.item.operate";
    }



    @RequestMapping(value = "/item/updateItem", method = RequestMethod.POST)
    public String updateItem(@RequestParam Long itemId,@RequestParam String itemName,HttpServletResponse response) throws IOException {
        String retCode="false";
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            unitItemService.updateItem(itemId, itemName);
            retCode="success";
        } catch (Exception e) {
            LOGGER.debug(e.getMessage(), e);
            retCode = e.getMessage();
        }
        returnMap.put("retCode", retCode);
        response.getWriter().print(JSONObject.toJSONString(returnMap));
        response.setContentType(ConstantStatic.HTTP_JSON_CONTENTTYPE);
        return null;
    }

    /**
     * 保存及编辑课件视频
     *
     * @param response
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(method = RequestMethod.POST, value = "/unit/{unitId}/item/operate")
    public String saveOrUpdateItem(@PathVariable Long unitId, 
    						 HttpServletResponse response,HttpServletRequest request,
    						 @RequestParam(defaultValue = "0", required = false) Long itemId,
                             @RequestParam(defaultValue = "", required = false) String videoRelativePath,
                             @RequestParam(defaultValue = "", required = false) String videoTempPath,
                             @RequestParam(defaultValue = "", required = false) String thumbRelativePath,
                             @RequestParam(defaultValue = "", required = false) String thumbTempPath,
                             @RequestParam(defaultValue = "", required = false) String currentVideoPath,
                             @RequestParam(defaultValue = "", required = false) String currentThumbPath,
                             @RequestParam(defaultValue = "", required = false) String videoFileName) {
        Map params = new HashMap();
        
        try {
        	
            this.unitItemService.saveOrUpdateItem(unitId, itemId, videoRelativePath, videoTempPath,
            		thumbRelativePath, thumbTempPath, currentVideoPath, currentThumbPath, videoFileName);
            params.put("successFlag", true);
            
        } catch (Exception e) {
        	params.put("successFlag", false);
            LOGGER.error(e.getMessage());
        }finally{
        	try {
				response.getWriter().print(JSONObject.toJSONString(params));
			} catch (IOException e) {
				LOGGER.error(e.getMessage());
			}
        }
        return null;
    }



    
    /*****************************************end********************************/

    /**************************************用户管理**************************/


    /**
     * 后台-用户管理列表
     * @param request
     * @param model
     * @return
     * @throws Exception
     */

    @RequestMapping(value = "/user/index", method = RequestMethod.GET)
    public String userIndex(HttpServletRequest request, ModelMap model) throws Exception {
        String keyword = request.getParameter("keyword");
        int pageIndex = Strings.isEmpty(request.getParameter("pageIndex"))?1:Strings.getInteger(request.getParameter("pageIndex"));
        int pageSize = Strings.isEmpty(request.getParameter("pageSize"))?ConstantStatic.DEFAULT_PAGE10:Strings.getInteger(request.getParameter("pageSize"));;
        PageMaker pm = this.userInfoService.getUserInfo(keyword,pageIndex, pageSize);
        model.addAttribute("pageMaker",pm);
        model.addAttribute("beginRow",(pageIndex-1)*10+1);
        model.addAttribute("keyword",keyword);
        return "platform.user.index";
    }

    /**
     * 删除用户
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/user/delete", method = RequestMethod.POST)
    public String userDelete(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String retCode="false";
        List<Long> userIdList = new ArrayList<Long>();
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            String userIds = request.getParameter("userIds");//逗号隔开的字符串参数
            String[] strUser = userIds.split(",");
            for (int i=0;i<strUser.length;i++){
                userIdList.add(Strings.getLong(strUser[i]));
            }
            this.userInfoService.deleteUser(userIdList);
            retCode="success";
        } catch (Exception e) {
            LOGGER.debug(e.getMessage(), e);
            retCode = e.getMessage();
        }
        returnMap.put("retCode", retCode);
        response.getWriter().print(JSONObject.toJSONString(returnMap));
        response.setContentType(ConstantStatic.HTTP_JSON_CONTENTTYPE);
        return null;
    }

    /**
     * 重置密码
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/user/resetpwd", method = RequestMethod.POST)
    public String resetpwd(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String retCode="false";
        List<Long> userIdList = new ArrayList<Long>();
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            String userIds = request.getParameter("userIds");
            String[] strUser = userIds.split(",");
            for (int i=0;i<strUser.length;i++){
                userIdList.add(Strings.getLong(strUser[i]));
            }
            this.userInfoService.updateUserPassword(userIdList);
            retCode="success";
        } catch (Exception e) {
            LOGGER.debug(e.getMessage(), e);
            retCode = e.getMessage();
        }
        returnMap.put("retCode", retCode);
        response.getWriter().print(JSONObject.toJSONString(returnMap));
        response.setContentType(ConstantStatic.HTTP_JSON_CONTENTTYPE);
        return null;
    }
    /***************************************end***************************/
}