package cn.com.qmth.stmms.admin.campus;

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

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.com.qmth.stmms.biz.campus.model.Campus;
import cn.com.qmth.stmms.biz.campus.query.CampusSearchQuery;
import cn.com.qmth.stmms.biz.campus.service.CampusService;
import cn.com.qmth.stmms.biz.user.model.User;
import cn.com.qmth.stmms.common.auth.annotation.AuthRequire;
import cn.com.qmth.stmms.common.domain.WebUser;
import cn.com.qmth.stmms.common.enums.Auth;
import cn.com.qmth.stmms.common.enums.SchoolLevel;
import cn.com.qmth.stmms.common.utils.RequestUtils;
import cn.com.qmth.stmms.common.utils.RoleAuthUtils;

@Controller
@RequestMapping("/admin/campus")
public class CampusController {

    @Autowired
    private CampusService campusService;

    @RequestMapping("/list")
    @AuthRequire({ Auth.CAMPUS_VIEW_ALL })
    public ModelAndView list(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("admin/campus/list");
        return view;
    }

    @RequestMapping("/pagelist")
    @ResponseBody
    @AuthRequire({ Auth.CAMPUS_VIEW_ALL })
    public Map<String, Object> pageList(HttpServletRequest request, CampusSearchQuery query,
            @RequestParam Integer page, @RequestParam Integer rows) {
        User user = RequestUtils.getWebUser(request).getUser();
        query.setPageNumber(page);
        query.setPageSize(rows);
        query.setSchoolId(user.getSchoolId());
        query = campusService.findByQuery(query);
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("rows", query.getResult());
        result.put("total", query.getTotalCount());
        return result;
    }

    @RequestMapping("/info/{id}")
    @AuthRequire({ Auth.CAMPUS_VIEW_SELF })
    public ModelAndView info(HttpServletRequest request, @PathVariable Integer id) {
        ModelAndView view = new ModelAndView("admin/campus/info");
        view.addObject("campus", campusService.findById(id));
        return view;
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    @AuthRequire(value = { Auth.CAMPUS_CREATE })
    public ModelAndView addInit(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("admin/campus/edit");
        return view;
    }

    @RequestMapping(value = "/edit/{campusId}", method = RequestMethod.GET)
    @AuthRequire(value = { Auth.CAMPUS_EDIT_ALL, Auth.CAMPUS_EDIT_SELF }, isAny = true)
    public ModelAndView editInit(HttpServletRequest request, @PathVariable Integer campusId) {
        WebUser user = RequestUtils.getWebUser(request);
        ModelAndView view = new ModelAndView("admin/campus/edit");
        if (RoleAuthUtils.hasAuth(user, Auth.CAMPUS_EDIT_ALL)) {
            Campus campus = campusService.findById(campusId);
            view.addObject("campus", campus);
            view.addObject("levelList", SchoolLevel.getLevelList());
        } else if (RoleAuthUtils.hasAuth(user, Auth.CAMPUS_EDIT_SELF)) {
            Campus campus = campusService.findById(campusId);
            view = new ModelAndView("admin/campus/edit-self");
            view.addObject("campus", campus);
        } else {
            view = new ModelAndView("redirect:/admin/home");
        }
        RequestUtils.getSession(request).setParameter("campusId", campusId.toString());
        return view;
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @AuthRequire(value = { Auth.CAMPUS_CREATE, Auth.CAMPUS_EDIT_ALL, Auth.CAMPUS_EDIT_SELF }, isAny = true)
    public String save(HttpServletRequest request, Campus campus) throws IOException {
        WebUser user = RequestUtils.getWebUser(request);
        boolean create = !(campus.getId() != null && campus.getId() > 0);
        Campus old = create ? null : campusService.findById(campus.getId());
        String uri = "";
        if (RoleAuthUtils.hasAuth(user, Auth.CAMPUS_EDIT_ALL) || RoleAuthUtils.hasAuth(user, Auth.CAMPUS_CREATE)) {
            if (create) {
                uri = "redirect:/admin/campus/admin/" + campusService.save(campus).getId();
            } else {
                old.setName(campus.getName());
                old.setProvince(campus.getProvince());
                old.setCity(campus.getCity());
                old.setDistrict(campus.getDistrict());
                old.setAddress(campus.getAddress());
                old.setPhone(campus.getPhone());
                old.setDescription(campus.getDescription());
                campusService.save(old);
                uri = "redirect:/admin/campus/list";
            }
        } else if (RoleAuthUtils.hasAuth(user, Auth.CAMPUS_EDIT_SELF)) {
            old.setAddress(campus.getAddress());
            old.setPhone(campus.getPhone());
            old.setDescription(campus.getDescription());
            campusService.save(old);
            uri = "redirect:/admin/campus/info";
        } else {
            uri = "redirect:/admin/home";
        }
        return uri;
    }
}
