package com.jpsoft.shinestar.modules.sys.controller;

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.sys.entity.Menu;
import com.jpsoft.shinestar.modules.sys.service.MenuService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/sys/menu")
public class MenuController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MenuService menuService;

    @ApiOperation(value = "创建空记录")
    @GetMapping("create")
    public MessageResult<Menu> create() {
        MessageResult<Menu> msgResult = new MessageResult<>();

        Menu menu = new Menu();

        msgResult.setData(menu);
        msgResult.setResult(true);

        return msgResult;
    }

    @ApiOperation(value = "添加信息")
    @PostMapping("add")
    public MessageResult<Menu> add(@RequestBody Menu menu, @RequestAttribute String subject) {
        MessageResult<Menu> msgResult = new MessageResult<>();

        try {
            menu.setId(UUID.randomUUID().toString());
            menu.setDelFlag(false);
            menu.setCreateBy(subject);
            menu.setCreateTime(new Date());

            int affectCount = menuService.insert(menu);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(menu);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库添加失败");
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value = "获取信息")
    @GetMapping("edit/{id}")
    public MessageResult<Menu> edit(@PathVariable("id") String id) {
        MessageResult<Menu> msgResult = new MessageResult<>();

        try {
            Menu menu = menuService.get(id);

            if (menu != null) {
                msgResult.setResult(true);
                msgResult.setData(menu);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value = "更新用户")
    @PostMapping("update")
    public MessageResult<Menu> update(@RequestBody Menu menu, @RequestAttribute String subject) {
        MessageResult<Menu> msgResult = new MessageResult<>();

        try {
            menu.setUpdateBy(subject);
            menu.setUpdateTime(new Date());

            int affectCount = menuService.update(menu);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(menu);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库更新失败");
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value = "删除")
    @PostMapping("delete/{id}")
    public MessageResult<Integer> delete(@PathVariable("id") String id, @RequestAttribute String subject) {
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            Menu menu = menuService.get(id);
            menu.setDelFlag(true);
            menu.setUpdateBy(subject);
            menu.setUpdateTime(new Date());

            int affectCount = menuService.update(menu);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value = "批量删除")
    @PostMapping("batchDelete")
    public MessageResult<Integer> batchDelete(@RequestBody List<String> idList, @RequestAttribute String subject) {
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            for (String id : idList) {
                Menu menu = menuService.get(id);
                menu.setDelFlag(true);
                menu.setUpdateBy(subject);
                menu.setUpdateTime(new Date());

                affectCount += menuService.update(menu);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value = "查询")
    @RequestMapping(value = "query", method = RequestMethod.POST)
    public MessageResult<List> query(
            String keywords,
            String excludeId,
            @RequestParam(value = "limit", defaultValue = "20") int limit,
            @RequestAttribute String subject) {
        MessageResult<List> msgResult = new MessageResult<>();

        Map<String, Object> searchParams = new HashMap<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("a.sort_no", "asc"));

        if (StringUtils.isNotEmpty(keywords)) {
            searchParams.put("menuName", "%" + keywords + "%");
        }

        if (StringUtils.isNotEmpty(excludeId)) {
            searchParams.put("excludeId", excludeId);
        }

        List<Menu> menuList = menuService.query(searchParams, limit, sortList);

        msgResult.setResult(true);
        msgResult.setData(menuList);

        return msgResult;
    }

    @ApiOperation(value = "列表")
    @RequestMapping(value = "pageList", method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            String menuName,
            String menuType,
            String parentId,
            @RequestParam(name="pageIndex",defaultValue = "1") int pageIndex,
            @RequestParam(name="pageSize",defaultValue = "10") int pageSize,
            @RequestAttribute String subject) {

        //当前用户ID
        System.out.println(subject);

        MessageResult<Map> msgResult = new MessageResult<>();

        Map<String, Object> searchParams = new HashMap<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("sort_no", "asc"));

        if (StringUtils.isNotEmpty(menuName)) {
            searchParams.put("menuName", "%" + menuName + "%");
        }

        if (StringUtils.isNotEmpty(menuType)) {
            searchParams.put("menuType", menuType);
        }

        if (StringUtils.isNotEmpty(parentId)) {
            searchParams.put("parentId", parentId);
        }

        Page<Menu> page = menuService.pageSearch(searchParams, pageIndex, pageSize, sortList);

        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(page));

        return msgResult;
    }

    @ApiOperation(value = "获取授权菜单")
    @GetMapping("tree")
    public MessageResult<List> tree(@RequestAttribute("subject") String subject) {
        MessageResult<List> msgResult = new MessageResult<>();

        List<Menu> list = menuService.findAllocMenu(subject,null);

        findChildrenLoop(list,subject,0,5);

        msgResult.setData(list);
        msgResult.setResult(true);

        return msgResult;
    }

    private void findChildrenLoop(List<Menu> list, String subject,int deep,int max) {
        if (deep<max) {
            for (Menu menu : list) {
                List<Menu> children = menuService.findAllocMenu(subject,menu.getId());

                menu.setChildren(children);

                findChildrenLoop(children,subject,deep+1,max);
            }
        }
    }
}
