package com.iamberry.wechat.handles.admin;

import com.iamberry.sys.Admin;
import com.iamberry.sys.Menu;
import com.iamberry.wechat.core.entity.page.PageRequest;
import com.iamberry.wechat.core.entity.page.PagedResult;
import com.iamberry.wechat.face.sys.SysService;
import com.iamberry.wechat.tools.ResponseJson;
import com.iamberry.wechat.tools.StrUtils;
import com.iamberry.wechat.utils.AdminUtils;
import com.iamberry.wechat.utils.StaticModelUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * @author 献
 *
 * @company 深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @tel 18271840547
 * @date 2017/5/15
 */
@Controller
@RequestMapping("/admin/sys")
public class SysController {

    @Autowired
    private SysService sysService;

    private static Logger logger = LoggerFactory.getLogger(SysController.class);

    /**
     * 后台首页，自动判断来源
     * @param request
     * @return
     */
    @RequiresUser
    @RequestMapping("/_index")
    public ModelAndView indexUI(HttpServletRequest request) {
        Subject currentUser = SecurityUtils.getSubject();
        Admin admin = (Admin) currentUser.getPrincipal();
        // 注入数据:管理员名称、管理员部门
        List<Menu> list = sysService.listMenuByRule(AdminUtils.getLoginAdmin().getRuleId());
        return new ModelAndView("home/pc_index")
                .addObject("adminName", admin.getAdminName())
                .addObject("deptName", "WaterO微信商城管理")
                .addObject("menus", list);
    }

    /**
     * 查看我的信息
     * @return
     */
    @ResponseBody
    @RequestMapping("/get/my_info")
    public ResponseJson getMyInfo() {
        // 获取当前用户信息
        Integer adminId = AdminUtils.getLoginAdminId();
        Admin temp = new Admin();
        temp.setAdminId(adminId);

        // 查询数据 & 清空敏感数据
        Admin admin = sysService.get(temp);
        admin.setAdminId(null);
        admin.setAdminPassword(null);
        admin.setAdminSalt(null);
        admin.setAdminTel(StrUtils.phoneFormat(admin.getAdminTel()));
        return new ResponseJson(200, "SUCCESS", 200).addResponseKeyValue("admin", admin);
    }

    /**
     * 进入修改密码页面
     * @return
     */
    @RequiresPermissions("sys:editMyPwd")
    @RequestMapping("/edit/_my_pwd")
    public ModelAndView editMyPasswordUI() {
        return new ModelAndView("sys/edit_pwd");
    }

    /**
     * 执行修改密码
     * @param pwd
     * @return
     */
    @RequiresPermissions("sys:editMyPwd")
    @RequestMapping("/edit/my_pwd")
    @ResponseBody
    public ResponseJson editMyPassword(@RequestParam("pwd") String pwd) {
        // 获取当前用户信息
        Integer adminId = AdminUtils.getLoginAdminId();

        Admin admin = new Admin();
        admin.setAdminPassword(pwd);
        admin.setAdminId(adminId);

        Integer res = sysService.editAdmin(admin);
        if (res == 1) {
            return new ResponseJson(200, "SUCCESS", 200);
        }

        return new ResponseJson(200, "SUCCESS", 400);
    }

    /**
     * 编辑自己的用户信息页面
     * @return
     */
    @RequiresPermissions("sys:editMyInfo")
    @RequestMapping("/_edit_myinfo")
    public ModelAndView editMeInfoUI() {
        // 获取当前用户信息
        Integer adminId = AdminUtils.getLoginAdminId();
        Admin temp = new Admin();
        temp.setAdminId(adminId);
        Admin admin = sysService.get(temp);

        // 返回用户信息
        ModelAndView mv = new ModelAndView("admin/edit");
        mv.addObject("admin", admin);
        return mv;
    }


    @RequiresPermissions("sys:listAdmin")
    @RequestMapping("/_list_admin")
    public ModelAndView listAdminUI(Admin admin, HttpServletRequest request,
                                    @RequestParam(value = "pageNO", defaultValue = "1", required = false) int pageNO,
                                    @RequestParam(value = "pageTotal", required = false) Integer pageTotal,
                                    @RequestParam(value = "pageSize", defaultValue = "20", required = false) int pageSize) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {

        // 封装请求数据
        PageRequest<Admin> pageRequest = new PageRequest<>(admin, pageNO, pageSize, pageTotal == null);

        // 查询
        PagedResult<Admin> result = sysService.listAdmin(pageRequest);
        if (pageTotal != null) {
            result.setPages(pageTotal);
        }

        // 返回
        ModelAndView mv = new ModelAndView("sys/list_admin");
        mv.addObject("page", result);
        mv.addObject("url", request.getRequestURI().replace(request.getContextPath(), "") +
                "?pageTotal=" + result.getPages() + "&pageSize=" + pageSize +
                "&adminName=" + (admin.getAdminName() == null ? "" : admin.getAdminName()) +
                "&adminSex=" + (admin.getAdminSex() == null ? "" : admin.getAdminSex()) +
                "&adminTel=" + (admin.getAdminTel() == null ? "" : admin.getAdminTel()) +
                "&adminMail=" + (admin.getAdminMail() == null ? "" : admin.getAdminMail()) +
                "&pageNO=");

        // 向页面传递数据，注意防止XSS
        mv.addObject("admin", admin);
        mv.addObject("strUtil", StaticModelUtil.useStaticPacker(StrUtils.class.getName()));
        return mv;
    }

    @ResponseBody
    @RequestMapping("/edit_status")
    @RequiresPermissions("sys:listAdmin")
    public ResponseJson editStatus(@RequestParam("adminId") Integer adminId,
                                   @RequestParam("status") Integer status) {

        Admin admin = new Admin();
        admin.setAdminId(adminId);
        admin.setAdminStatus(status);
        Integer res = sysService.editAdmin(admin);
        if (res == null || res <= 0) {
            return new ResponseJson(200, "SUCCESS", 400);
        }
        return new ResponseJson(200, "SUCCESS", 200);
    }

    @RequestMapping("/addAdminUI")
    @RequiresPermissions("sys:listAdmin")
    public ModelAndView addAdminUI() {
        return new ModelAndView("sys/add").addObject("rules", sysService.listRule(AdminUtils.getLoginAdmin().getSupplierId()));
    }

    @ResponseBody
    @RequestMapping("/addAdmin")
    @RequiresPermissions("sys:listAdmin")
    public ResponseJson addAdmin(Admin admin) {
        admin.setAdminStatus(2);
        admin.setSupplierId(AdminUtils.getLoginAdmin().getSupplierId());
        Integer res = sysService.saveAdmin(admin);
        return res <= 0 ? ResponseJson.FAILURE : ResponseJson.SUCCESS;
    }

    @RequestMapping("/editAdminUI")
    @RequiresPermissions("sys:listAdmin")
    public ModelAndView editAdminUI(Admin admin) {
        return new ModelAndView("sys/edit")
                .addObject("obj", sysService.get(admin))
                .addObject("rules", sysService.listRule(AdminUtils.getLoginAdmin().getSupplierId()));
    }

    @ResponseBody
    @RequestMapping("/editAdmin")
    @RequiresPermissions("sys:listAdmin")
    public ResponseJson editAdmin(Admin admin) {
        Integer res = sysService.editAdmin(admin);
        return res <= 0 ? ResponseJson.FAILURE : ResponseJson.SUCCESS;
    }

    @RequestMapping("/listRule")
    @RequiresPermissions("sys:listRule")
    public ModelAndView listRule() {
        return new ModelAndView("sys/list_rule")
                .addObject("rules", sysService.listRule(AdminUtils.getLoginAdmin().getSupplierId()));
    }

    @RequestMapping("/addRuleUI")
    @RequiresPermissions("sys:listRule")
    public ModelAndView addRuleUI() {
        return new ModelAndView("sys/add_rule").addObject("menus", sysService.listMenu());
    }

    @ResponseBody
    @RequestMapping("/addRule")
    @RequiresPermissions("sys:listRule")
    public ResponseJson addRule(@RequestParam("name") String name,
                                @RequestParam("menuId") Integer[] menuId) {
        return sysService.addRule(AdminUtils.getLoginAdmin().getSupplierId(), name, menuId) <= 0 ? ResponseJson.FAILURE : ResponseJson.SUCCESS;
    }

    @RequestMapping("/editRuleUI")
    @RequiresPermissions("sys:listRule")
    public ModelAndView editRuleUI(@RequestParam("id") Integer id) {
        return new ModelAndView("sys/edit_rule")
                .addObject("obj", sysService.getRule(id))
                .addObject("menus", sysService.listMenu());
    }

    @ResponseBody
    @RequestMapping("/editRule")
    @RequiresPermissions("sys:listRule")
    public ResponseJson editRule(@RequestParam("ruleId") Integer ruleId,
                                 @RequestParam("name") String name,
                                 @RequestParam("menuId") Integer[] menuId) {
        return sysService.editRule(ruleId, name, menuId) <= 0 ? ResponseJson.FAILURE : ResponseJson.SUCCESS;
    }

    @RequestMapping("/accountInfo")
    @RequiresPermissions("sys:accountInfo")
    public ModelAndView accountInfo() {
        return new ModelAndView("sys/edit_pwd")
                .addObject("obj", AdminUtils.getLoginAdmin())
                .addObject("rule", sysService.getRule(AdminUtils.getLoginAdmin().getRuleId()));
    }
}
