package com.dxhy.admin.sys.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.dxhy.admin.sys.entity.SysMenuEntity;
import com.dxhy.admin.sys.service.SysMenuService;
import com.dxhy.common.aspect.SysLog;
import com.dxhy.common.controller.AbstractController;
import com.dxhy.common.utils.Constant;
import com.dxhy.common.utils.PageUtils;
import com.dxhy.common.utils.R;
import com.dxhy.common.utils.RRException;
import com.dxhy.common.vo.UserInfo;

import lombok.extern.slf4j.Slf4j;

/**
 * 系统菜单
 *
 * @author jiaohongyang
 */

@RestController
@RequestMapping("/sys/menu")
@Slf4j
public class SysMenuController extends AbstractController {
    @Resource
    private SysMenuService sysMenuService;

    /**
     * 导航菜单
     */
    @RequestMapping("/nav")
    public ResponseEntity<?> nav() {
        List<SysMenuEntity> menuList = sysMenuService.getUserMenuList(Long.valueOf(getUserId()));
        return ResponseEntity.ok(R.ok().put("menuList", menuList));
    }

    /**
     * 所有用户列表
     */
    @RequestMapping("/page")

    public ResponseEntity<?> page(@RequestBody Map<String, Object> params) {
        log.debug("传输数据：" + params);
        PageUtils page = sysMenuService.queryPage(params);

        return ResponseEntity.ok(R.ok().put("page", page));
    }

    /**
     * 所有菜单列表
     */
    @RequestMapping("/list")
    public ResponseEntity<?> list() {
        List<SysMenuEntity> menuList = sysMenuService.selectList();
        return ResponseEntity.ok(R.ok().put("data", menuList));
    }

    /**
     * 所有菜单列表
     */
    @RequestMapping("/listInfo")
    public ResponseEntity<?> listInfo() {
        String company = "";
        UserInfo userInfo = getUserInfo();
        if (Long.parseLong(userInfo.getId()) != Constant.SUPER_ADMIN) {
            company = userInfo.getCompany();
        }
        List<SysMenuEntity> menuList = sysMenuService.querylistMenu(company, Long.parseLong(userInfo.getId()));
        return ResponseEntity.ok(R.ok().put("data", menuList));
    }

    /**
     * 所有菜单列表
     */
    @RequestMapping("/listCompanyInfo")
    public ResponseEntity<?> listCompanyInfo(@RequestBody Map<String, Object> params) {
        List<SysMenuEntity> menuList = sysMenuService.queryMenuRoleCompanyList((String)params.get("company"));
        return ResponseEntity.ok(R.ok().put("data", menuList));
    }

    /**
     * 选择菜单(添加、修改菜单)
     */
    @RequestMapping("/select")
    public ResponseEntity<?> select() {
        // 查询列表数据
        List<SysMenuEntity> menuList = sysMenuService.queryNotButtonList();

        // 添加顶级菜单
        SysMenuEntity root = new SysMenuEntity();
        root.setMenuId(0L);
        root.setName("系统名称");
        root.setParentId(-1L);
        root.setOpen(true);
        menuList.add(root);

        return ResponseEntity.ok(R.ok().put("menuList", menuList));
    }

    /**
     * 菜单信息
     */
    @RequestMapping("/info/{menuId}")
    public ResponseEntity<?> info(@PathVariable("menuId") Long menuId) {
        SysMenuEntity menu = sysMenuService.queryMenuById(menuId);
        return ResponseEntity.ok(R.ok().put("menu", menu));
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @SysLog("保存菜单")
    public ResponseEntity<?> save(@RequestBody SysMenuEntity menu) {
        try {
            if (menu.getType() == 0) {
                menu.setParentId(0L);
            } else {
                menu.setParentId(menu.getMenuId());
            }
            menu.setMenuId(null);
            // 数据校验
            verifyForm(menu);
            sysMenuService.saveMenu(menu);

            return ResponseEntity.ok(R.ok("保存成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok(R.error(e.getMessage()));
        }
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @SysLog("修改菜单")
    public ResponseEntity<?> update(@RequestBody SysMenuEntity menu) {
        try {

            // 数据校验
            verifyForm(menu);

            sysMenuService.updateMenu(menu);

            return ResponseEntity.ok(R.ok("保存成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok(R.error("保存失败"));

        }
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @SysLog("删除菜单")
    public ResponseEntity<?> delete(long menuId) {
        try {

            // 判断是否有子菜单或按钮
            List<SysMenuEntity> menuList = sysMenuService.queryListParentId(menuId);
            if (menuList.size() > 0) {
                return ResponseEntity.ok(R.error("请先删除子菜单或按钮"));
            }

            sysMenuService.delete(menuId);

            return ResponseEntity.ok(R.ok("删除成功"));
        } catch (Exception e) {
            return ResponseEntity.ok(R.error("删除失败"));

        }
    }

    /**
     * 验证参数是否正确
     */
    private void verifyForm(SysMenuEntity menu) {
        if (StringUtils.isBlank(menu.getName())) {
            throw new RRException("菜单名称不能为空");
        }

        if (menu.getParentId() == null) {
            throw new RRException("上级菜单不能为空");
        }

        // 菜单
        if (menu.getType() == Constant.MenuType.MENU.getValue()) {
            if (StringUtils.isBlank(menu.getUrl())) {
                throw new RRException("菜单URL不能为空");
            }
        }

        // 上级菜单类型
        int parentType = Constant.MenuType.CATALOG.getValue();
        if (menu.getParentId() != 0) {
            SysMenuEntity parentMenu = sysMenuService.getById(menu.getParentId());
            parentType = parentMenu.getType();
        }
        // 目录
        if (menu.getType() == Constant.MenuType.CATALOG.getValue()) {
            if (parentType != Constant.MenuType.SYSTEM.getValue()) {
                throw new RRException("上级菜单只能为系统类型");
            }
            return;
        }
        // 菜单
        if (menu.getType() == Constant.MenuType.MENU.getValue()) {
            if (parentType != Constant.MenuType.CATALOG.getValue()) {
                throw new RRException("上级菜单只能为目录类型");
            }
            return;
        }

        // 按钮
        if (menu.getType() == Constant.MenuType.BUTTON.getValue()) {
            if (parentType != Constant.MenuType.MENU.getValue()) {
                throw new RRException("上级菜单只能为菜单类型");
            }
        }
    }

    /**
     * 读取所有菜单信息
     *
     * @return 返回
     */
    @RequestMapping("/getMenuAll")
    public List<SysMenuEntity> getMenuAll() {
        return sysMenuService.getMenuAll();
    }

    /**
     * 根据用户读取权限菜单
     *
     * @return 返回
     *
     */
    @RequestMapping("/getMenuUser")
    public List<SysMenuEntity> getMenuUser() {
        String company = "";
        UserInfo userInfo = getUserInfo();
        if (Long.parseLong(userInfo.getId()) == Constant.SUPER_ADMIN) {
            company = userInfo.getCompany();
        }
        return sysMenuService.querylistMenu(company, Long.parseLong(userInfo.getId()));
    }

    @RequestMapping("/saveQuery")
    @SysLog("保存查询条件")
    public ResponseEntity<?> save(@RequestBody String datalist) {
        int code = sysMenuService.saveQuery(datalist);
        return getSaveResponseEntity(code);
    }

    @NotNull
    private ResponseEntity<?> getSaveResponseEntity(int code) {
        if (code == 1) {
            return ResponseEntity.ok(R.ok("查询条件保存成功"));
        } else if (code == 2) {
            return ResponseEntity.ok(R.error("查询条件保存失败，菜单ID为空"));
        } else if (code == 3) {
            return ResponseEntity.ok(R.error("查询条件保存失败，异常"));
        } else {
            return ResponseEntity.ok(R.error("查询条件保存失败"));
        }
    }
}
